From 87703534836168ecca2bcf6bc1719460e6b5b9bd Mon Sep 17 00:00:00 2001 From: "Rafael H. Schloming" Date: Tue, 19 Sep 2006 22:06:50 +0000 Subject: Import of qpid from etp: URL: https://etp.108.redhat.com/svn/etp/trunk/blaze Repository Root: https://etp.108.redhat.com/svn/etp Repository UUID: 06e15bec-b515-0410-bef0-cc27a458cf48 Revision: 608 git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@447994 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/AMQChannelClosedException.java | 31 + .../src/org/apache/qpid/AMQChannelException.java | 46 ++ .../apache/qpid/AMQConnectionClosedException.java | 31 + .../org/apache/qpid/AMQConnectionException.java | 27 + .../org/apache/qpid/AMQDisconnectedException.java | 31 + .../common/src/org/apache/qpid/AMQException.java | 74 ++ .../org/apache/qpid/AMQUndeliveredException.java | 41 ++ .../apache/qpid/AMQUnresolvedAddressException.java | 26 + .../common/src/org/apache/qpid/bio/Reader.java | 98 +++ .../common/src/org/apache/qpid/bio/Sequence.java | 29 + .../org/apache/qpid/bio/SimpleSocketChannel.java | 82 +++ .../src/org/apache/qpid/bio/SocketAcceptor.java | 277 ++++++++ .../src/org/apache/qpid/bio/SocketConnector.java | 150 ++++ .../src/org/apache/qpid/bio/SocketFilterChain.java | 62 ++ .../src/org/apache/qpid/bio/SocketSessionImpl.java | 421 +++++++++++ .../src/org/apache/qpid/codec/AMQCodecFactory.java | 50 ++ .../src/org/apache/qpid/codec/AMQDecoder.java | 96 +++ .../src/org/apache/qpid/codec/AMQEncoder.java | 38 + .../org/apache/qpid/configuration/Configured.java | 41 ++ .../qpid/configuration/PropertyException.java | 62 ++ .../apache/qpid/configuration/PropertyUtils.java | 153 ++++ .../org/apache/qpid/exchange/ExchangeDefaults.java | 33 + .../src/org/apache/qpid/framing/AMQBody.java | 35 + .../src/org/apache/qpid/framing/AMQDataBlock.java | 40 ++ .../apache/qpid/framing/AMQDataBlockDecoder.java | 113 +++ .../apache/qpid/framing/AMQDataBlockEncoder.java | 62 ++ .../src/org/apache/qpid/framing/AMQFrame.java | 73 ++ .../qpid/framing/AMQFrameDecodingException.java | 45 ++ .../src/org/apache/qpid/framing/AMQMethodBody.java | 87 +++ .../apache/qpid/framing/AMQMethodBodyFactory.java | 43 ++ .../qpid/framing/AMQProtocolClassException.java | 26 + .../qpid/framing/AMQProtocolHeaderException.java | 28 + .../qpid/framing/AMQProtocolInstanceException.java | 26 + .../qpid/framing/AMQProtocolVersionException.java | 30 + .../qpid/framing/BasicContentHeaderProperties.java | 592 ++++++++++++++++ .../src/org/apache/qpid/framing/BodyFactory.java | 28 + .../apache/qpid/framing/CompositeAMQDataBlock.java | 100 +++ .../src/org/apache/qpid/framing/ContentBody.java | 64 ++ .../apache/qpid/framing/ContentBodyFactory.java | 44 ++ .../org/apache/qpid/framing/ContentHeaderBody.java | 112 +++ .../qpid/framing/ContentHeaderBodyFactory.java | 47 ++ .../qpid/framing/ContentHeaderProperties.java | 55 ++ .../framing/ContentHeaderPropertiesFactory.java | 51 ++ .../apache/qpid/framing/EncodableAMQDataBlock.java | 32 + .../src/org/apache/qpid/framing/EncodingUtils.java | 519 ++++++++++++++ .../src/org/apache/qpid/framing/FieldTable.java | 319 +++++++++ .../qpid/framing/FieldTableKeyEnumeration.java | 44 ++ .../src/org/apache/qpid/framing/HeartbeatBody.java | 54 ++ .../apache/qpid/framing/HeartbeatBodyFactory.java | 28 + .../apache/qpid/framing/ProtocolInitiation.java | 176 +++++ .../src/org/apache/qpid/nio/SocketAcceptor.java | 31 + .../apache/qpid/nio/SocketAcceptorDelegate.java | 602 ++++++++++++++++ .../src/org/apache/qpid/nio/SocketConnector.java | 32 + .../apache/qpid/nio/SocketConnectorDelegate.java | 402 +++++++++++ .../src/org/apache/qpid/nio/SocketFilterChain.java | 48 ++ .../src/org/apache/qpid/nio/SocketIoProcessor.java | 770 +++++++++++++++++++++ .../src/org/apache/qpid/nio/SocketSessionImpl.java | 404 +++++++++++ .../common/src/org/apache/qpid/pool/Event.java | 111 +++ qpid/java/common/src/org/apache/qpid/pool/Job.java | 110 +++ .../src/org/apache/qpid/pool/PoolingFilter.java | 183 +++++ .../org/apache/qpid/pool/ReadWriteThreadModel.java | 37 + .../pool/ReferenceCountingExecutorService.java | 95 +++ .../src/org/apache/qpid/protocol/AMQConstant.java | 105 +++ .../apache/qpid/ssl/BogusSSLContextFactory.java | 156 +++++ .../apache/qpid/ssl/BogusTrustManagerFactory.java | 79 +++ .../apache/qpid/ssl/SSLServerSocketFactory.java | 105 +++ .../src/org/apache/qpid/ssl/SSLSocketFactory.java | 135 ++++ .../src/org/apache/qpid/url/AMQBindingURL.java | 260 +++++++ .../common/src/org/apache/qpid/url/BindingURL.java | 65 ++ .../common/src/org/apache/qpid/url/URLHelper.java | 173 +++++ .../org/apache/qpid/url/URLSyntaxException.java | 94 +++ 71 files changed, 8769 insertions(+) create mode 100644 qpid/java/common/src/org/apache/qpid/AMQChannelClosedException.java create mode 100644 qpid/java/common/src/org/apache/qpid/AMQChannelException.java create mode 100644 qpid/java/common/src/org/apache/qpid/AMQConnectionClosedException.java create mode 100644 qpid/java/common/src/org/apache/qpid/AMQConnectionException.java create mode 100644 qpid/java/common/src/org/apache/qpid/AMQDisconnectedException.java create mode 100644 qpid/java/common/src/org/apache/qpid/AMQException.java create mode 100644 qpid/java/common/src/org/apache/qpid/AMQUndeliveredException.java create mode 100644 qpid/java/common/src/org/apache/qpid/AMQUnresolvedAddressException.java create mode 100644 qpid/java/common/src/org/apache/qpid/bio/Reader.java create mode 100644 qpid/java/common/src/org/apache/qpid/bio/Sequence.java create mode 100644 qpid/java/common/src/org/apache/qpid/bio/SimpleSocketChannel.java create mode 100644 qpid/java/common/src/org/apache/qpid/bio/SocketAcceptor.java create mode 100644 qpid/java/common/src/org/apache/qpid/bio/SocketConnector.java create mode 100644 qpid/java/common/src/org/apache/qpid/bio/SocketFilterChain.java create mode 100644 qpid/java/common/src/org/apache/qpid/bio/SocketSessionImpl.java create mode 100644 qpid/java/common/src/org/apache/qpid/codec/AMQCodecFactory.java create mode 100644 qpid/java/common/src/org/apache/qpid/codec/AMQDecoder.java create mode 100644 qpid/java/common/src/org/apache/qpid/codec/AMQEncoder.java create mode 100644 qpid/java/common/src/org/apache/qpid/configuration/Configured.java create mode 100644 qpid/java/common/src/org/apache/qpid/configuration/PropertyException.java create mode 100644 qpid/java/common/src/org/apache/qpid/configuration/PropertyUtils.java create mode 100644 qpid/java/common/src/org/apache/qpid/exchange/ExchangeDefaults.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/AMQBody.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/AMQDataBlock.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/AMQDataBlockDecoder.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/AMQDataBlockEncoder.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/AMQFrame.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/AMQFrameDecodingException.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/AMQMethodBody.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/AMQMethodBodyFactory.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/AMQProtocolClassException.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/AMQProtocolHeaderException.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/AMQProtocolInstanceException.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/AMQProtocolVersionException.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/BasicContentHeaderProperties.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/BodyFactory.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/CompositeAMQDataBlock.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/ContentBody.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/ContentBodyFactory.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/ContentHeaderBody.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/ContentHeaderBodyFactory.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/ContentHeaderProperties.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/EncodableAMQDataBlock.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/EncodingUtils.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/FieldTable.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/FieldTableKeyEnumeration.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/HeartbeatBody.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/HeartbeatBodyFactory.java create mode 100644 qpid/java/common/src/org/apache/qpid/framing/ProtocolInitiation.java create mode 100644 qpid/java/common/src/org/apache/qpid/nio/SocketAcceptor.java create mode 100644 qpid/java/common/src/org/apache/qpid/nio/SocketAcceptorDelegate.java create mode 100644 qpid/java/common/src/org/apache/qpid/nio/SocketConnector.java create mode 100644 qpid/java/common/src/org/apache/qpid/nio/SocketConnectorDelegate.java create mode 100644 qpid/java/common/src/org/apache/qpid/nio/SocketFilterChain.java create mode 100644 qpid/java/common/src/org/apache/qpid/nio/SocketIoProcessor.java create mode 100644 qpid/java/common/src/org/apache/qpid/nio/SocketSessionImpl.java create mode 100644 qpid/java/common/src/org/apache/qpid/pool/Event.java create mode 100644 qpid/java/common/src/org/apache/qpid/pool/Job.java create mode 100644 qpid/java/common/src/org/apache/qpid/pool/PoolingFilter.java create mode 100644 qpid/java/common/src/org/apache/qpid/pool/ReadWriteThreadModel.java create mode 100644 qpid/java/common/src/org/apache/qpid/pool/ReferenceCountingExecutorService.java create mode 100644 qpid/java/common/src/org/apache/qpid/protocol/AMQConstant.java create mode 100644 qpid/java/common/src/org/apache/qpid/ssl/BogusSSLContextFactory.java create mode 100644 qpid/java/common/src/org/apache/qpid/ssl/BogusTrustManagerFactory.java create mode 100644 qpid/java/common/src/org/apache/qpid/ssl/SSLServerSocketFactory.java create mode 100644 qpid/java/common/src/org/apache/qpid/ssl/SSLSocketFactory.java create mode 100644 qpid/java/common/src/org/apache/qpid/url/AMQBindingURL.java create mode 100644 qpid/java/common/src/org/apache/qpid/url/BindingURL.java create mode 100644 qpid/java/common/src/org/apache/qpid/url/URLHelper.java create mode 100644 qpid/java/common/src/org/apache/qpid/url/URLSyntaxException.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/org/apache/qpid/AMQChannelClosedException.java b/qpid/java/common/src/org/apache/qpid/AMQChannelClosedException.java new file mode 100644 index 0000000000..694fe75cda --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/AMQChannelClosedException.java @@ -0,0 +1,31 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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; + +/** + * AMQ channel closed exception. + */ +public class AMQChannelClosedException extends AMQException +{ + public AMQChannelClosedException(int errorCode, String msg) + { + super(errorCode, msg); + } +} + + diff --git a/qpid/java/common/src/org/apache/qpid/AMQChannelException.java b/qpid/java/common/src/org/apache/qpid/AMQChannelException.java new file mode 100644 index 0000000000..677a4938a0 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/AMQChannelException.java @@ -0,0 +1,46 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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; + +import org.apache.qpid.framing.ChannelCloseBody; +import org.apache.qpid.framing.AMQFrame; + +public class AMQChannelException extends AMQException +{ + private final int _classId; + private final int _methodId; + + public AMQChannelException(int errorCode, String msg, int classId, int methodId, Throwable t) + { + super(errorCode, msg, t); + _classId = classId; + _methodId = methodId; + } + + public AMQChannelException(int errorCode, String msg, int classId, int methodId) + { + super(errorCode, msg); + _classId = classId; + _methodId = methodId; + } + + public AMQFrame getCloseFrame(int channel) + { + return ChannelCloseBody.createAMQFrame(channel, getErrorCode(), getMessage(), _classId, _methodId); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/AMQConnectionClosedException.java b/qpid/java/common/src/org/apache/qpid/AMQConnectionClosedException.java new file mode 100644 index 0000000000..dcf393eb65 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/AMQConnectionClosedException.java @@ -0,0 +1,31 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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; + +/** + * AMQ channel closed exception. + */ +public class AMQConnectionClosedException extends AMQException +{ + public AMQConnectionClosedException(int errorCode, String msg) + { + super(errorCode, msg); + } +} + + diff --git a/qpid/java/common/src/org/apache/qpid/AMQConnectionException.java b/qpid/java/common/src/org/apache/qpid/AMQConnectionException.java new file mode 100644 index 0000000000..171af23500 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/AMQConnectionException.java @@ -0,0 +1,27 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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; + +public class AMQConnectionException extends AMQException +{ + public AMQConnectionException(String message) + { + super(message); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/AMQDisconnectedException.java b/qpid/java/common/src/org/apache/qpid/AMQDisconnectedException.java new file mode 100644 index 0000000000..616a95bd1b --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/AMQDisconnectedException.java @@ -0,0 +1,31 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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; + +/** + * AMQ disconnected exception. + */ +public class AMQDisconnectedException extends AMQException +{ + public AMQDisconnectedException(String msg) + { + super(msg); + } +} + + diff --git a/qpid/java/common/src/org/apache/qpid/AMQException.java b/qpid/java/common/src/org/apache/qpid/AMQException.java new file mode 100644 index 0000000000..423cbf8975 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/AMQException.java @@ -0,0 +1,74 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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; + +import org.apache.log4j.Logger; + +/** + * Generic AMQ exception. + */ +public class AMQException extends Exception +{ + private int _errorCode; + + public AMQException(String message) + { + super(message); + } + + public AMQException(String msg, Throwable t) + { + super(msg, t); + } + + public AMQException(int errorCode, String msg, Throwable t) + { + super(msg + " [error code " + errorCode + ']', t); + _errorCode = errorCode; + } + + public AMQException(int errorCode, String msg) + { + super(msg + " [error code " + errorCode + ']'); + _errorCode = errorCode; + } + + public AMQException(Logger logger, String msg, Throwable t) + { + this(msg, t); + logger.error(getMessage(), this); + } + + public AMQException(Logger logger, String msg) + { + this(msg); + logger.error(getMessage(), this); + } + + public AMQException(Logger logger, int errorCode, String msg) + { + this(errorCode, msg); + logger.error(getMessage(), this); + } + + public int getErrorCode() + { + return _errorCode; + } + +} diff --git a/qpid/java/common/src/org/apache/qpid/AMQUndeliveredException.java b/qpid/java/common/src/org/apache/qpid/AMQUndeliveredException.java new file mode 100644 index 0000000000..9424fe8eb1 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/AMQUndeliveredException.java @@ -0,0 +1,41 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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; + +/** + * Generic AMQ exception. + */ +public class AMQUndeliveredException extends AMQException +{ + private Object _bounced; + + public AMQUndeliveredException(int errorCode, String msg, Object bounced) + { + super(errorCode, msg); + + _bounced = bounced; + } + + public Object getUndeliveredMessage() + { + return _bounced; + } + +} + + diff --git a/qpid/java/common/src/org/apache/qpid/AMQUnresolvedAddressException.java b/qpid/java/common/src/org/apache/qpid/AMQUnresolvedAddressException.java new file mode 100644 index 0000000000..b290e1e4c7 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/AMQUnresolvedAddressException.java @@ -0,0 +1,26 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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; + +public class AMQUnresolvedAddressException extends AMQException +{ + public AMQUnresolvedAddressException(String message) + { + super(message); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/bio/Reader.java b/qpid/java/common/src/org/apache/qpid/bio/Reader.java new file mode 100644 index 0000000000..165a323337 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/bio/Reader.java @@ -0,0 +1,98 @@ +/* + * @(#) $Id: SocketSessionImpl.java 398039 2006-04-28 23:36:27Z proyal $ + * + * Copyright 2004 The Apache Software Foundation + * + * Licensed 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.bio; + +import org.apache.mina.common.ByteBuffer; +import org.apache.mina.common.IoHandler; + +import java.io.IOException; +import java.nio.channels.ByteChannel; +import java.nio.channels.ClosedByInterruptException; + +class Reader implements Runnable +{ + private final IoHandler handler; + private final SocketSessionImpl session; + private final ByteChannel channel; + private volatile boolean stopped; + + Reader(IoHandler handler, SocketSessionImpl session) + { + this.handler = handler; + this.session = session; + channel = session.getChannel(); + } + + void stop() + { + stopped = true; + } + + public void run() + { + while (!stopped) + { + try + { + ByteBuffer buffer = ByteBuffer.allocate(session.getReadBufferSize()); + int read = channel.read(buffer.buf()); + if(read > 0) + { + buffer.flip(); + ((SocketFilterChain) session.getFilterChain()).messageReceived(session, buffer); + } + else + { + stopped = true; + } + } + catch (ClosedByInterruptException e) + { + stopped = true; + } + catch (IOException e) + { + if (!stopped) + { + signalException(e); + session.close(); + } + } + catch (Exception e) + { + if (!stopped) + { + signalException(e); + } + } + } + } + + private void signalException(Exception e) + { + try + { + handler.exceptionCaught(session, e); + } + catch (Exception e2) + { + e.printStackTrace(); + } + } +} diff --git a/qpid/java/common/src/org/apache/qpid/bio/Sequence.java b/qpid/java/common/src/org/apache/qpid/bio/Sequence.java new file mode 100644 index 0000000000..dcaae4d6d7 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/bio/Sequence.java @@ -0,0 +1,29 @@ +/* + * @(#) $Id: SocketSessionImpl.java 398039 2006-04-28 23:36:27Z proyal $ + * + * Copyright 2004 The Apache Software Foundation + * + * Licensed 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.bio; + +class Sequence +{ + private int nextId = 0; + + synchronized int nextId() + { + return nextId++; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/bio/SimpleSocketChannel.java b/qpid/java/common/src/org/apache/qpid/bio/SimpleSocketChannel.java new file mode 100644 index 0000000000..0495654f73 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/bio/SimpleSocketChannel.java @@ -0,0 +1,82 @@ +/* + * @(#) $Id: SocketSessionImpl.java 398039 2006-04-28 23:36:27Z proyal $ + * + * Copyright 2004 The Apache Software Foundation + * + * Licensed 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.bio; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.channels.ByteChannel; + +/** + * A simpler alternative to the non-blocking enabled SocketChannel for + * use with blocking io only. Not threadsafe. + */ +class SimpleSocketChannel implements ByteChannel +{ + private final Socket socket; + private final OutputStream out; + private final InputStream in; + private final byte[] buffer = new byte[2048]; + + SimpleSocketChannel(Socket socket) throws IOException + { + this.socket = socket; + out = socket.getOutputStream(); + in = socket.getInputStream(); + } + + Socket socket() + { + return socket; + } + + public int read(ByteBuffer dst) throws IOException + { + if (dst == null) + { + throw new NullPointerException("Null buffer passed into read"); + } + int read = in.read(buffer, 0, Math.min(buffer.length, dst.limit() - dst.position())); + if (read > 0) + { + dst.put(buffer, 0, read); + } + return read; + } + + public int write(ByteBuffer dst) throws IOException + { + byte[] data = new byte[dst.remaining()]; + dst.get(data); + out.write(data); + return data.length; + } + + public boolean isOpen() + { + return socket.isConnected(); + } + + public void close() throws IOException + { + socket.close(); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/bio/SocketAcceptor.java b/qpid/java/common/src/org/apache/qpid/bio/SocketAcceptor.java new file mode 100644 index 0000000000..d47a29a047 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/bio/SocketAcceptor.java @@ -0,0 +1,277 @@ +/* + * @(#) $Id: SocketAcceptor.java 389042 2006-03-27 07:49:41Z trustin $ + * + * Copyright 2004 The Apache Software Foundation + * + * Licensed 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.bio; + +import org.apache.mina.common.IoHandler; +import org.apache.mina.common.IoServiceConfig; +import org.apache.mina.common.support.BaseIoAcceptor; +import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; +import org.apache.mina.transport.socket.nio.SocketSessionConfig; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.nio.channels.ByteChannel; +import java.nio.channels.ServerSocketChannel; +import java.util.*; + +/** + */ +public class SocketAcceptor extends BaseIoAcceptor +{ + private static final Sequence acceptorSeq = new Sequence(); + + private final int id = acceptorSeq.nextId(); + private final String threadName = "SocketAcceptor-" + id; + private final IoServiceConfig defaultConfig = new SocketAcceptorConfig(); + private final Map services = new HashMap();//SocketAddress => SocketBinding + + public SocketAcceptor() + { + } + + /** + * Binds to the specified address and handles incoming connections with the specified + * handler. Backlog value is configured to the value of backlog property. + * + * @throws IOException if failed to bind + */ + public void bind(SocketAddress address, IoHandler handler, IoServiceConfig config) throws IOException + { + if (address == null) + { + throw new NullPointerException("address"); + } + + if (handler == null) + { + throw new NullPointerException("handler"); + } + + if (!(address instanceof InetSocketAddress)) + { + throw new IllegalArgumentException("Unexpected address type: " + address.getClass()); + } + + if (((InetSocketAddress) address).getPort() == 0) + { + throw new IllegalArgumentException("Unsupported port number: 0"); + } + + if (config == null) + { + config = getDefaultConfig(); + } + + SocketBinding service = new SocketBinding(address, handler, config); + synchronized (services) + { + services.put(address, service); + } + service.start(); + } + + public Set getManagedSessions(SocketAddress address) + { + if (address == null) + { + throw new NullPointerException("address"); + } + + SocketBinding service = (SocketBinding) services.get(address); + + if (service == null) + { + throw new IllegalArgumentException("Address not bound: " + address); + } + + return Collections.unmodifiableSet(new HashSet(service.sessions)); + } + + public void unbind(SocketAddress address) + { + if (address == null) + { + throw new NullPointerException("address"); + } + + SocketBinding service; + synchronized (services) + { + service = (SocketBinding) services.remove(address); + } + + if (service == null) + { + throw new IllegalArgumentException("Address not bound: " + address); + } + + try + { + service.unbind(); + } + catch (IOException e) + { + //TODO: handle properly + e.printStackTrace(); + } + } + + public void unbindAll() + { + synchronized (services) + { + for (Iterator i = services.entrySet().iterator(); i.hasNext();) + { + SocketBinding service = (SocketBinding) i.next(); + try + { + service.unbind(); + } + catch (IOException e) + { + //TODO: handle properly + e.printStackTrace(); + } + i.remove(); + } + } + } + + public boolean isBound(SocketAddress address) + { + synchronized (services) + { + return services.containsKey(address); + } + } + + public Set getBoundAddresses() + { + throw new UnsupportedOperationException("getBoundAddresses() not supported by blocking IO Acceptor"); + } + + public IoServiceConfig getDefaultConfig() + { + return defaultConfig; + } + + private class SocketBinding implements Runnable + { + private final SocketAddress address; + private final ServerSocketChannel service; + //private final ServerSocket service; + private final IoServiceConfig config; + private final IoHandler handler; + private final List sessions = new ArrayList(); + private volatile boolean stopped = false; + private Thread runner; + + SocketBinding(SocketAddress address, IoHandler handler, IoServiceConfig config) throws IOException + { + this.address = address; + this.handler = handler; + this.config = config; + + service = ServerSocketChannel.open(); + service.socket().bind(address); + + //service = new ServerSocket(); + //service.bind(address); + } + + void unbind() throws IOException + { + stopped = true; + //shutdown all sessions + for (Iterator i = sessions.iterator(); i.hasNext();) + { + ((SocketSessionImpl) i.next()).close(); + i.remove(); + } + + //close server socket + service.close(); + if (runner != null) + { + try + { + runner.join(); + } + catch (InterruptedException e) + { + //ignore and return + System.err.println("Warning: interrupted on unbind(" + address + ")"); + } + } + } + + void start() + { + runner = new Thread(this); + runner.start(); + } + + public void run() + { + while (!stopped) + { + try + { + accept(); + } + catch (Exception e) + { + //handle this better... + e.printStackTrace(); + } + } + } + + private void accept() throws Exception + { + //accept(new SimpleSocketChannel(service.accept())); + accept(service.accept()); + } + + private void accept(ByteChannel channel) throws Exception + { + //SocketChannel channel; + //start session + SocketSessionImpl session = new SocketSessionImpl(SocketAcceptor.this, + (SocketSessionConfig) defaultConfig.getSessionConfig(), + handler, + channel, + address); + //signal start etc... + sessions.add(session); + + //TODO + //need to set up filter chains somehow... (this is copied from connector...) + getFilterChainBuilder().buildFilterChain(session.getFilterChain()); + config.getFilterChainBuilder().buildFilterChain(session.getFilterChain()); + config.getThreadModel().buildFilterChain(session.getFilterChain()); + ((SocketFilterChain) session.getFilterChain()).sessionCreated(session); + + session.start(); + //not sure if this will work... socket is already opened before the created callback is called... + ((SocketFilterChain) session.getFilterChain()).sessionOpened(session); + } + } +} diff --git a/qpid/java/common/src/org/apache/qpid/bio/SocketConnector.java b/qpid/java/common/src/org/apache/qpid/bio/SocketConnector.java new file mode 100644 index 0000000000..b107c44726 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/bio/SocketConnector.java @@ -0,0 +1,150 @@ +/* + * @(#) $Id: SocketConnector.java 389042 2006-03-27 07:49:41Z trustin $ + * + * Copyright 2004 The Apache Software Foundation + * + * Licensed 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.bio; + +import org.apache.mina.common.ConnectFuture; +import org.apache.mina.common.IoHandler; +import org.apache.mina.common.IoServiceConfig; +import org.apache.mina.common.support.BaseIoConnector; +import org.apache.mina.common.support.DefaultConnectFuture; +import org.apache.mina.transport.socket.nio.SocketConnectorConfig; +import org.apache.mina.transport.socket.nio.SocketSessionConfig; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.nio.channels.ByteChannel; +import java.nio.channels.SocketChannel; + +/** + */ +public class SocketConnector extends BaseIoConnector +{ + /** + * @noinspection StaticNonFinalField + */ + private static final Sequence idSequence = new Sequence(); + + private final Object lock = new Object(); + private final String threadName = "SocketConnector-" + idSequence.nextId(); + private final IoServiceConfig defaultConfig = new SocketConnectorConfig(); + private final Set managedSessions = Collections.synchronizedSet(new HashSet()); + + /** + * Create a connector with a single processing thread + */ + public SocketConnector() + { + } + + public IoServiceConfig getDefaultConfig() + { + return defaultConfig; + } + + public ConnectFuture connect(SocketAddress address, IoHandler handler, IoServiceConfig config) + { + return connect(address, null, handler, config); + } + + public ConnectFuture connect(SocketAddress address, SocketAddress localAddress, + IoHandler handler, IoServiceConfig config) + { + if (address == null) + { + throw new NullPointerException("address"); + } + if (handler == null) + { + throw new NullPointerException("handler"); + } + + if (! (address instanceof InetSocketAddress)) + { + throw new IllegalArgumentException("Unexpected address type: " + address.getClass()); + } + if (localAddress != null && !(localAddress instanceof InetSocketAddress)) + { + throw new IllegalArgumentException("Unexpected local address type: " + localAddress.getClass()); + } + if (config == null) + { + config = getDefaultConfig(); + } + + DefaultConnectFuture future = new DefaultConnectFuture(); + try + { + + //Socket socket = new Socket(); + //socket.connect(address); + //SimpleSocketChannel channel = new SimpleSocketChannel(socket); + //SocketAddress serviceAddress = socket.getRemoteSocketAddress(); + + SocketChannel channel = SocketChannel.open(address); + channel.configureBlocking(true); + SocketAddress serviceAddress = channel.socket().getRemoteSocketAddress(); + + + SocketSessionImpl session = newSession(channel, handler, config, channel.socket().getRemoteSocketAddress()); + future.setSession(session); + } + catch (IOException e) + { + future.setException(e); + } + + return future; + } + + private SocketSessionImpl newSession(ByteChannel channel, IoHandler handler, IoServiceConfig config, SocketAddress serviceAddress) + throws IOException + { + SocketSessionImpl session = new SocketSessionImpl(this, + (SocketSessionConfig) config.getSessionConfig(), + handler, + channel, + serviceAddress); + try + { + getFilterChainBuilder().buildFilterChain(session.getFilterChain()); + config.getFilterChainBuilder().buildFilterChain(session.getFilterChain()); + config.getThreadModel().buildFilterChain(session.getFilterChain()); + ((SocketFilterChain) session.getFilterChain()).sessionCreated(session); + + session.start(); + //not sure if this will work... socket is already opened before the created callback is called... + ((SocketFilterChain) session.getFilterChain()).sessionOpened(session); + } + catch (Throwable e) + { + throw (IOException) new IOException("Failed to create a session.").initCause(e); + } + + //TODO: figure out how the managed session are used/ what they are etc. + //session.getManagedSessions().add( session ); + + + return session; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/bio/SocketFilterChain.java b/qpid/java/common/src/org/apache/qpid/bio/SocketFilterChain.java new file mode 100644 index 0000000000..f00a1535aa --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/bio/SocketFilterChain.java @@ -0,0 +1,62 @@ +/* + * @(#) $Id: SocketFilterChain.java 398039 2006-04-28 23:36:27Z proyal $ + * + * Copyright 2004 The Apache Software Foundation + * + * Licensed 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.bio; + +import org.apache.mina.common.ByteBuffer; +import org.apache.mina.common.IoFilter.WriteRequest; +import org.apache.mina.common.IoSession; +import org.apache.mina.common.support.AbstractIoFilterChain; + +import java.io.IOException; +import java.nio.channels.ClosedByInterruptException; + +/** + */ +class SocketFilterChain extends AbstractIoFilterChain +{ + + SocketFilterChain(IoSession parent) + { + super(parent); + } + + protected void doWrite(IoSession session, WriteRequest writeRequest) throws Exception + { + SocketSessionImpl s = (SocketSessionImpl) session; + + //write to socket + try + { + s.getChannel().write(((ByteBuffer) writeRequest.getMessage()).buf()); + + //notify of completion + writeRequest.getFuture().setWritten(true); + } + catch(ClosedByInterruptException e) + { + writeRequest.getFuture().setWritten(false); + } + } + + protected void doClose(IoSession session) throws IOException + { + SocketSessionImpl s = (SocketSessionImpl) session; + s.shutdown(); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/bio/SocketSessionImpl.java b/qpid/java/common/src/org/apache/qpid/bio/SocketSessionImpl.java new file mode 100644 index 0000000000..d534093533 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/bio/SocketSessionImpl.java @@ -0,0 +1,421 @@ +/* + * @(#) $Id: SocketSessionImpl.java 398039 2006-04-28 23:36:27Z proyal $ + * + * Copyright 2004 The Apache Software Foundation + * + * Licensed 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.bio; + +import org.apache.mina.common.IoFilter.WriteRequest; +import org.apache.mina.common.IoFilterChain; +import org.apache.mina.common.IoHandler; +import org.apache.mina.common.IoService; +import org.apache.mina.common.IoSessionConfig; +import org.apache.mina.common.RuntimeIOException; +import org.apache.mina.common.TransportType; +import org.apache.mina.common.support.BaseIoSession; +import org.apache.mina.common.support.BaseIoSessionConfig; +import org.apache.mina.transport.socket.nio.SocketSessionConfig; +import org.apache.mina.transport.socket.nio.SocketSessionConfigImpl; + +import java.io.IOException; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.SocketException; +import java.nio.channels.ByteChannel; +import java.nio.channels.SocketChannel; + +/** + */ +class SocketSessionImpl extends BaseIoSession +{ + private final IoService manager; + private final SocketSessionConfig config; + private final SocketFilterChain filterChain; + private final IoHandler handler; + private final SocketAddress remoteAddress; + private final SocketAddress localAddress; + private final SocketAddress serviceAddress; + private final Socket socket; + private final ByteChannel channel; + private final Reader reader; + private Thread runner; + private int readBufferSize; + + /** + * Creates a new instance. + */ + SocketSessionImpl(IoService manager, + SocketSessionConfig config, + IoHandler handler, + ByteChannel channel, + SocketAddress serviceAddress) throws IOException + { + this.manager = manager; + this.filterChain = new SocketFilterChain(this); + this.handler = handler; + this.channel = channel; + if(channel instanceof SocketChannel) + { + socket = ((SocketChannel) channel).socket(); + } + else if(channel instanceof SimpleSocketChannel) + { + socket = ((SimpleSocketChannel) channel).socket(); + } + else + { + throw new IllegalArgumentException("Unrecognised channel type: " + channel.getClass()); + } + + this.remoteAddress = socket.getRemoteSocketAddress(); + this.localAddress = socket.getLocalSocketAddress(); + this.serviceAddress = serviceAddress; + + this.config = new SessionConfigImpl(config); + + reader = new Reader(handler, this); + } + + void start() + { + //create & start thread for this... + runner = new Thread(reader); + runner.start(); + } + + void shutdown() throws IOException + { + filterChain.sessionClosed( this ); + reader.stop(); + channel.close(); + } + + ByteChannel getChannel() + { + return channel; + } + + protected void write0(WriteRequest writeRequest) + { + filterChain.filterWrite(this, writeRequest); + } + + protected void close0() + { + filterChain.filterClose(this); + super.close0(); + } + + protected void updateTrafficMask() + { + //TODO + } + + public IoService getService() + { + return manager; + } + + public IoSessionConfig getConfig() + { + return config; + } + + public IoFilterChain getFilterChain() + { + return filterChain; + } + + public IoHandler getHandler() + { + return handler; + } + + public int getScheduledWriteRequests() + { + return 0; + } + + public int getScheduledWriteBytes() + { + return 0; + } + + public TransportType getTransportType() + { + return TransportType.SOCKET; + } + + public SocketAddress getRemoteAddress() + { + return remoteAddress; + } + + public SocketAddress getLocalAddress() + { + return localAddress; + } + + public SocketAddress getServiceAddress() + { + return serviceAddress; + } + + int getReadBufferSize() + { + return readBufferSize; + } + + private class SessionConfigImpl extends BaseIoSessionConfig implements SocketSessionConfig + { + SessionConfigImpl() + { + } + + SessionConfigImpl(SocketSessionConfig cfg) + { + setKeepAlive(cfg.isKeepAlive()); + setOobInline(cfg.isOobInline()); + setReceiveBufferSize(cfg.getReceiveBufferSize()); + readBufferSize = cfg.getReceiveBufferSize(); + setReuseAddress(cfg.isReuseAddress()); + setSendBufferSize(cfg.getSendBufferSize()); + setSoLinger(cfg.getSoLinger()); + setTcpNoDelay(cfg.isTcpNoDelay()); + if (getTrafficClass() != cfg.getTrafficClass()) + { + setTrafficClass(cfg.getTrafficClass()); + } + } + + + public boolean isKeepAlive() + { + try + { + return socket.getKeepAlive(); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + + public void setKeepAlive(boolean on) + { + try + { + socket.setKeepAlive(on); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + + public boolean isOobInline() + { + try + { + return socket.getOOBInline(); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + + public void setOobInline(boolean on) + { + try + { + socket.setOOBInline(on); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + + public boolean isReuseAddress() + { + try + { + return socket.getReuseAddress(); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + + public void setReuseAddress(boolean on) + { + try + { + socket.setReuseAddress(on); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + + public int getSoLinger() + { + try + { + return socket.getSoLinger(); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + + public void setSoLinger(int linger) + { + try + { + if (linger < 0) + { + socket.setSoLinger(false, 0); + } + else + { + socket.setSoLinger(true, linger); + } + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + + public boolean isTcpNoDelay() + { + try + { + return socket.getTcpNoDelay(); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + + public void setTcpNoDelay(boolean on) + { + try + { + socket.setTcpNoDelay(on); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + + public int getTrafficClass() + { + if (SocketSessionConfigImpl.isGetTrafficClassAvailable()) + { + try + { + return socket.getTrafficClass(); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + else + { + return 0; + } + } + + public void setTrafficClass(int tc) + { + if (SocketSessionConfigImpl.isSetTrafficClassAvailable()) + { + try + { + socket.setTrafficClass(tc); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + } + + public int getSendBufferSize() + { + try + { + return socket.getSendBufferSize(); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + + public void setSendBufferSize(int size) + { + if (SocketSessionConfigImpl.isSetSendBufferSizeAvailable()) + { + try + { + socket.setSendBufferSize(size); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + } + + public int getReceiveBufferSize() + { + try + { + return socket.getReceiveBufferSize(); + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + + public void setReceiveBufferSize(int size) + { + if (SocketSessionConfigImpl.isSetReceiveBufferSizeAvailable()) + { + try + { + socket.setReceiveBufferSize(size); + SocketSessionImpl.this.readBufferSize = size; + } + catch (SocketException e) + { + throw new RuntimeIOException(e); + } + } + } + } +} diff --git a/qpid/java/common/src/org/apache/qpid/codec/AMQCodecFactory.java b/qpid/java/common/src/org/apache/qpid/codec/AMQCodecFactory.java new file mode 100644 index 0000000000..c62befce6b --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/codec/AMQCodecFactory.java @@ -0,0 +1,50 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.codec; + +import org.apache.mina.filter.codec.ProtocolCodecFactory; +import org.apache.mina.filter.codec.ProtocolDecoder; +import org.apache.mina.filter.codec.ProtocolEncoder; + +public class AMQCodecFactory implements ProtocolCodecFactory +{ + private AMQEncoder _encoder = new AMQEncoder(); + + private AMQDecoder _frameDecoder; + + /** + * @param expectProtocolInitiation true if the first frame received is going to be + * a protocol initiation frame, false if it is going to be a standard AMQ data block. + * The former case is used for the broker, which always expects to received the + * protocol initiation first from a newly connected client. + */ + public AMQCodecFactory(boolean expectProtocolInitiation) + { + _frameDecoder = new AMQDecoder(expectProtocolInitiation); + } + + public ProtocolEncoder getEncoder() + { + return _encoder; + } + + public ProtocolDecoder getDecoder() + { + return _frameDecoder; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/codec/AMQDecoder.java b/qpid/java/common/src/org/apache/qpid/codec/AMQDecoder.java new file mode 100644 index 0000000000..594ae11233 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/codec/AMQDecoder.java @@ -0,0 +1,96 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.codec; + +import org.apache.mina.common.ByteBuffer; +import org.apache.mina.common.IoSession; +import org.apache.mina.filter.codec.CumulativeProtocolDecoder; +import org.apache.mina.filter.codec.ProtocolDecoderOutput; +import org.apache.qpid.framing.AMQDataBlockDecoder; +import org.apache.qpid.framing.ProtocolInitiation; + +/** + * There is one instance of this class per session. Any changes or configuration done + * at run time to the encoders or decoders only affects decoding/encoding of the + * protocol session data to which is it bound. + * + */ +public class AMQDecoder extends CumulativeProtocolDecoder +{ + private AMQDataBlockDecoder _dataBlockDecoder = new AMQDataBlockDecoder(); + + private ProtocolInitiation.Decoder _piDecoder = new ProtocolInitiation.Decoder(); + + private boolean _expectProtocolInitiation; + + public AMQDecoder(boolean expectProtocolInitiation) + { + _expectProtocolInitiation = expectProtocolInitiation; + } + + protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception + { + if (_expectProtocolInitiation) + { + return doDecodePI(session, in, out); + } + else + { + return doDecodeDataBlock(session, in, out); + } + } + + protected boolean doDecodeDataBlock(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception + { + int pos = in.position(); + boolean enoughData = _dataBlockDecoder.decodable(session, in); + in.position(pos); + if (!enoughData) + { + // returning false means it will leave the contents in the buffer and + // call us again when more data has been read + return false; + } + else + { + _dataBlockDecoder.decode(session, in, out); + return true; + } + } + + private boolean doDecodePI(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception + { + boolean enoughData = _piDecoder.decodable(session, in); + if (!enoughData) + { + // returning false means it will leave the contents in the buffer and + // call us again when more data has been read + return false; + } + else + { + _piDecoder.decode(session, in, out); + return true; + } + } + + public void setExpectProtocolInitiation(boolean expectProtocolInitiation) + { + _expectProtocolInitiation = expectProtocolInitiation; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/codec/AMQEncoder.java b/qpid/java/common/src/org/apache/qpid/codec/AMQEncoder.java new file mode 100644 index 0000000000..7d5e8182a6 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/codec/AMQEncoder.java @@ -0,0 +1,38 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.codec; + +import org.apache.mina.filter.codec.ProtocolEncoder; +import org.apache.mina.filter.codec.ProtocolEncoderOutput; +import org.apache.mina.common.IoSession; +import org.apache.qpid.framing.AMQDataBlockEncoder; + +public class AMQEncoder implements ProtocolEncoder +{ + private AMQDataBlockEncoder _dataBlockEncoder = new AMQDataBlockEncoder(); + + public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception + { + _dataBlockEncoder.encode(session, message, out); + } + + public void dispose(IoSession session) throws Exception + { + + } +} diff --git a/qpid/java/common/src/org/apache/qpid/configuration/Configured.java b/qpid/java/common/src/org/apache/qpid/configuration/Configured.java new file mode 100644 index 0000000000..cb5e8aff1d --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/configuration/Configured.java @@ -0,0 +1,41 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.configuration; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +/** + * Marks a field as being "configured" externally. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Configured +{ + /** + * The Commons Configuration path to the configuration element + */ + String path(); + + /** + * The default value to use should the path not be found in the configuration source + */ + String defaultValue(); +} diff --git a/qpid/java/common/src/org/apache/qpid/configuration/PropertyException.java b/qpid/java/common/src/org/apache/qpid/configuration/PropertyException.java new file mode 100644 index 0000000000..f148ffc0b7 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/configuration/PropertyException.java @@ -0,0 +1,62 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.configuration; + +import org.apache.qpid.AMQException; +import org.apache.log4j.Logger; + +/** + * Indicates an error parsing a property expansion. + */ +public class PropertyException extends AMQException +{ + public PropertyException(String message) + { + super(message); + } + + public PropertyException(String msg, Throwable t) + { + super(msg, t); + } + + public PropertyException(int errorCode, String msg, Throwable t) + { + super(errorCode, msg, t); + } + + public PropertyException(int errorCode, String msg) + { + super(errorCode, msg); + } + + public PropertyException(Logger logger, String msg, Throwable t) + { + super(logger, msg, t); + } + + public PropertyException(Logger logger, String msg) + { + super(logger, msg); + } + + public PropertyException(Logger logger, int errorCode, String msg) + { + super(logger, errorCode, msg); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/configuration/PropertyUtils.java b/qpid/java/common/src/org/apache/qpid/configuration/PropertyUtils.java new file mode 100644 index 0000000000..bd4000d3c4 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/configuration/PropertyUtils.java @@ -0,0 +1,153 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.configuration; + +import java.util.ArrayList; +import java.util.Iterator; + +/** + * Based on code in Apache Ant, this utility class handles property expansion. This + * is most useful in config files and so on. + */ +public class PropertyUtils +{ + /** + * Replaces ${xxx} style constructions in the given value + * with the string value of the corresponding data types. Replaces only system + * properties + * + * @param value The string to be scanned for property references. + * May be null, in which case this + * method returns immediately with no effect. + * @return the original string with the properties replaced, or + * null if the original string is null. + * @throws PropertyException if the string contains an opening + * ${ without a closing + * } + */ + public static String replaceProperties(String value) throws PropertyException + { + if (value == null) + { + return null; + } + + ArrayList fragments = new ArrayList(); + ArrayList propertyRefs = new ArrayList(); + parsePropertyString(value, fragments, propertyRefs); + + StringBuffer sb = new StringBuffer(); + Iterator j = propertyRefs.iterator(); + + for (String fragment : fragments) + { + if (fragment == null) + { + String propertyName = (String) j.next(); + + // try to get it from the project or keys + // Backward compatibility + String replacement = System.getProperty(propertyName); + + if (replacement == null) + { + throw new PropertyException("Property ${" + propertyName + + "} has not been set"); + } + fragment = replacement; + } + sb.append(fragment); + } + + return sb.toString(); + } + + /** + * Default parsing method. Parses the supplied value for properties which are specified + * using ${foo} syntax. $X is left as is, and $$ specifies a single $. + * @param value the property string to parse + * @param fragments is populated with the string fragments. A null means "insert a + * property value here. The number of nulls in the list when populated is equal to the + * size of the propertyRefs list + * @param propertyRefs populated with the property names to be added into the final + * String. + */ + private static void parsePropertyString(String value, ArrayList fragments, + ArrayList propertyRefs) + throws PropertyException + { + int prev = 0; + int pos; + //search for the next instance of $ from the 'prev' position + while ((pos = value.indexOf("$", prev)) >= 0) + { + + //if there was any text before this, add it as a fragment + if (pos > 0) + { + fragments.add(value.substring(prev, pos)); + } + //if we are at the end of the string, we tack on a $ + //then move past it + if (pos == (value.length() - 1)) + { + fragments.add("$"); + prev = pos + 1; + } + else if (value.charAt(pos + 1) != '{') + { + //peek ahead to see if the next char is a property or not + //not a property: insert the char as a literal + if (value.charAt(pos + 1) == '$') + { + // two $ map to one $ + fragments.add("$"); + prev = pos + 2; + } + else + { + // $X maps to $X for all values of X!='$' + fragments.add(value.substring(pos, pos + 2)); + prev = pos + 2; + } + } + else + { + // property found, extract its name or bail on a typo + int endName = value.indexOf('}', pos); + if (endName < 0) + { + throw new PropertyException("Syntax error in property: " + + value); + } + String propertyName = value.substring(pos + 2, endName); + fragments.add(null); + propertyRefs.add(propertyName); + prev = endName + 1; + } + } + //no more $ signs found + //if there is any tail to the file, append it + if (prev < value.length()) + { + fragments.add(value.substring(prev)); + } + } + + +} diff --git a/qpid/java/common/src/org/apache/qpid/exchange/ExchangeDefaults.java b/qpid/java/common/src/org/apache/qpid/exchange/ExchangeDefaults.java new file mode 100644 index 0000000000..84a5836ff7 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/exchange/ExchangeDefaults.java @@ -0,0 +1,33 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.exchange; + +public class ExchangeDefaults +{ + public final static String TOPIC_EXCHANGE_NAME = "amq.topic"; + + public final static String TOPIC_EXCHANGE_CLASS = "topic"; + + public final static String DIRECT_EXCHANGE_NAME = "amq.direct"; + + public final static String DIRECT_EXCHANGE_CLASS = "direct"; + + public final static String HEADERS_EXCHANGE_NAME = "amq.match"; + + public final static String HEADERS_EXCHANGE_CLASS = "headers"; +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/AMQBody.java b/qpid/java/common/src/org/apache/qpid/framing/AMQBody.java new file mode 100644 index 0000000000..fad0450960 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/AMQBody.java @@ -0,0 +1,35 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; + +public abstract class AMQBody +{ + protected abstract byte getType(); + + /** + * Get the size of the body + * @return unsigned short + */ + protected abstract int getSize(); + + protected abstract void writePayload(ByteBuffer buffer); + + protected abstract void populateFromBuffer(ByteBuffer buffer, long size) throws AMQFrameDecodingException; +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/AMQDataBlock.java b/qpid/java/common/src/org/apache/qpid/framing/AMQDataBlock.java new file mode 100644 index 0000000000..797df391c3 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/AMQDataBlock.java @@ -0,0 +1,40 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; + +/** + * A data block represents something that has a size in bytes and the ability to write itself to a byte + * buffer (similar to a byte array). + */ +public abstract class AMQDataBlock implements EncodableAMQDataBlock +{ + /** + * Get the size of buffer needed to store the byte representation of this + * frame. + * @return unsigned integer + */ + public abstract long getSize(); + + /** + * Writes the datablock to the specified buffer. + * @param buffer + */ + public abstract void writePayload(ByteBuffer buffer); +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/AMQDataBlockDecoder.java b/qpid/java/common/src/org/apache/qpid/framing/AMQDataBlockDecoder.java new file mode 100644 index 0000000000..3379cc18e9 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/AMQDataBlockDecoder.java @@ -0,0 +1,113 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.log4j.Logger; +import org.apache.mina.common.ByteBuffer; +import org.apache.mina.common.IoSession; +import org.apache.mina.filter.codec.ProtocolDecoderOutput; + +import java.util.HashMap; +import java.util.Map; + +public class AMQDataBlockDecoder +{ + Logger _logger = Logger.getLogger(AMQDataBlockDecoder.class); + + private final Map _supportedBodies = new HashMap(); + + public AMQDataBlockDecoder() + { + _supportedBodies.put(new Byte(AMQMethodBody.TYPE), AMQMethodBodyFactory.getInstance()); + _supportedBodies.put(new Byte(ContentHeaderBody.TYPE), ContentHeaderBodyFactory.getInstance()); + _supportedBodies.put(new Byte(ContentBody.TYPE), ContentBodyFactory.getInstance()); + _supportedBodies.put(new Byte(HeartbeatBody.TYPE), new HeartbeatBodyFactory()); + } + + public boolean decodable(IoSession session, ByteBuffer in) throws AMQFrameDecodingException + { + // type, channel, body size and end byte + if (in.remaining() < (1 + 2 + 4 + 1)) + { + return false; + } + + final byte type = in.get(); + final int channel = in.getUnsignedShort(); + final long bodySize = in.getUnsignedInt(); + + // bodySize can be zero + if (type <= 0 || channel < 0 || bodySize < 0) + { + throw new AMQFrameDecodingException("Undecodable frame: type = " + type + " channel = " + channel + + " bodySize = " + bodySize); + } + + if (in.remaining() < (bodySize + 1)) + { + return false; + } + return true; + } + + private boolean isSupportedFrameType(byte frameType) + { + final boolean result = _supportedBodies.containsKey(new Byte(frameType)); + + if (!result) + { + _logger.warn("AMQDataBlockDecoder does not handle frame type " + frameType); + } + + return result; + } + + protected Object createAndPopulateFrame(ByteBuffer in) + throws AMQFrameDecodingException + { + final byte type = in.get(); + if (!isSupportedFrameType(type)) + { + throw new AMQFrameDecodingException("Unsupported frame type: " + type); + } + final int channel = in.getUnsignedShort(); + final long bodySize = in.getUnsignedInt(); + + BodyFactory bodyFactory = (BodyFactory) _supportedBodies.get(new Byte(type)); + if (bodyFactory == null) + { + throw new AMQFrameDecodingException("Unsupported body type: " + type); + } + AMQFrame frame = new AMQFrame(); + + frame.populateFromBuffer(in, channel, bodySize, bodyFactory); + + byte marker = in.get(); + if ((marker & 0xFF) != 0xCE) + { + throw new AMQFrameDecodingException("End of frame marker not found. Read " + marker + " size=" + bodySize + " type=" + type); + } + return frame; + } + + public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) + throws Exception + { + out.write(createAndPopulateFrame(in)); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/AMQDataBlockEncoder.java b/qpid/java/common/src/org/apache/qpid/framing/AMQDataBlockEncoder.java new file mode 100644 index 0000000000..b0430afac9 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/AMQDataBlockEncoder.java @@ -0,0 +1,62 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.log4j.Logger; +import org.apache.mina.common.ByteBuffer; +import org.apache.mina.common.IoSession; +import org.apache.mina.filter.codec.demux.MessageEncoder; +import org.apache.mina.filter.codec.ProtocolEncoderOutput; + +import java.util.HashSet; +import java.util.Set; + +public class AMQDataBlockEncoder implements MessageEncoder +{ + Logger _logger = Logger.getLogger(AMQDataBlockEncoder.class); + + private Set _messageTypes; + + public AMQDataBlockEncoder() + { + _messageTypes = new HashSet(); + _messageTypes.add(EncodableAMQDataBlock.class); + } + + public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception + { + final AMQDataBlock frame = (AMQDataBlock) message; + int frameSize = (int)frame.getSize(); + final ByteBuffer buffer = ByteBuffer.allocate(frameSize); + //buffer.setAutoExpand(true); + frame.writePayload(buffer); + + if (_logger.isDebugEnabled()) + { + _logger.debug("Encoded frame byte-buffer is '" + EncodingUtils.convertToHexString(buffer) + "'"); + } + + buffer.flip(); + out.write(buffer); + } + + public Set getMessageTypes() + { + return _messageTypes; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/AMQFrame.java b/qpid/java/common/src/org/apache/qpid/framing/AMQFrame.java new file mode 100644 index 0000000000..17f635c06a --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/AMQFrame.java @@ -0,0 +1,73 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; + +public class AMQFrame extends AMQDataBlock implements EncodableAMQDataBlock +{ + public int channel; + + public AMQBody bodyFrame; + + public AMQFrame() + { + } + + public AMQFrame(int channel, AMQBody bodyFrame) + { + this.channel = channel; + this.bodyFrame = bodyFrame; + } + + public long getSize() + { + return 1 + 2 + 4 + bodyFrame.getSize() + 1; + } + + public void writePayload(ByteBuffer buffer) + { + buffer.put(bodyFrame.getType()); + // TODO: how does channel get populated + EncodingUtils.writeUnsignedShort(buffer, channel); + EncodingUtils.writeUnsignedInteger(buffer, bodyFrame.getSize()); + bodyFrame.writePayload(buffer); + buffer.put((byte) 0xCE); + } + + /** + * + * @param buffer + * @param channel unsigned short + * @param bodySize unsigned integer + * @param bodyFactory + * @throws AMQFrameDecodingException + */ + public void populateFromBuffer(ByteBuffer buffer, int channel, long bodySize, BodyFactory bodyFactory) + throws AMQFrameDecodingException + { + this.channel = channel; + bodyFrame = bodyFactory.createBody(buffer); + bodyFrame.populateFromBuffer(buffer, bodySize); + } + + public String toString() + { + return "Frame channelId: " + channel + ", bodyFrame: " + String.valueOf(bodyFrame); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/AMQFrameDecodingException.java b/qpid/java/common/src/org/apache/qpid/framing/AMQFrameDecodingException.java new file mode 100644 index 0000000000..4e8a8c62b1 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/AMQFrameDecodingException.java @@ -0,0 +1,45 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.log4j.Logger; +import org.apache.qpid.AMQException; + +public class AMQFrameDecodingException extends AMQException +{ + public AMQFrameDecodingException(String message) + { + super(message); + } + + public AMQFrameDecodingException(String message, Throwable t) + { + super(message, t); + } + + public AMQFrameDecodingException(Logger log, String message) + { + super(log, message); + } + + public AMQFrameDecodingException(Logger log, String message, Throwable t) + { + super(log, message, t); + } + +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/AMQMethodBody.java b/qpid/java/common/src/org/apache/qpid/framing/AMQMethodBody.java new file mode 100644 index 0000000000..841295e538 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/AMQMethodBody.java @@ -0,0 +1,87 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; +import org.apache.qpid.AMQChannelException; + +public abstract class AMQMethodBody extends AMQBody +{ + public static final byte TYPE = 1; + + /** unsigned short */ + protected abstract int getBodySize(); + + /** + * @return unsigned short + */ + protected abstract int getClazz(); + + /** + * @return unsigned short + */ + protected abstract int getMethod(); + + protected abstract void writeMethodPayload(ByteBuffer buffer); + + protected byte getType() + { + return TYPE; + } + + protected int getSize() + { + return 2 + 2 + getBodySize(); + } + + protected void writePayload(ByteBuffer buffer) + { + EncodingUtils.writeUnsignedShort(buffer, getClazz()); + EncodingUtils.writeUnsignedShort(buffer, getMethod()); + writeMethodPayload(buffer); + } + + protected abstract void populateMethodBodyFromBuffer(ByteBuffer buffer) throws AMQFrameDecodingException; + + protected void populateFromBuffer(ByteBuffer buffer, long size) throws AMQFrameDecodingException + { + populateMethodBodyFromBuffer(buffer); + } + + public String toString() + { + StringBuffer buf = new StringBuffer(getClass().toString()); + buf.append(" Class: ").append(getClazz()); + buf.append(" Method: ").append(getMethod()); + return buf.toString(); + } + + /** + * Creates an AMQChannelException for the corresponding body type (a channel exception + * should include the class and method ids of the body it resulted from). + */ + public AMQChannelException getChannelException(int code, String message) + { + return new AMQChannelException(code, message, getClazz(), getMethod()); + } + + public AMQChannelException getChannelException(int code, String message, Throwable cause) + { + return new AMQChannelException(code, message, getClazz(), getMethod(), cause); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/AMQMethodBodyFactory.java b/qpid/java/common/src/org/apache/qpid/framing/AMQMethodBodyFactory.java new file mode 100644 index 0000000000..97f594061e --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/AMQMethodBodyFactory.java @@ -0,0 +1,43 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.log4j.Logger; +import org.apache.mina.common.ByteBuffer; + +public class AMQMethodBodyFactory implements BodyFactory +{ + private static final Logger _log = Logger.getLogger(AMQMethodBodyFactory.class); + + private static final AMQMethodBodyFactory _instance = new AMQMethodBodyFactory(); + + public static AMQMethodBodyFactory getInstance() + { + return _instance; + } + + private AMQMethodBodyFactory() + { + _log.debug("Creating method body factory"); + } + + public AMQBody createBody(ByteBuffer in) throws AMQFrameDecodingException + { + return MethodBodyDecoderRegistry.get(in.getUnsignedShort(), in.getUnsignedShort()); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/AMQProtocolClassException.java b/qpid/java/common/src/org/apache/qpid/framing/AMQProtocolClassException.java new file mode 100644 index 0000000000..8a8175bbc8 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/AMQProtocolClassException.java @@ -0,0 +1,26 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +public class AMQProtocolClassException extends AMQProtocolHeaderException +{ + public AMQProtocolClassException(String message) + { + super(message); + } +} \ No newline at end of file diff --git a/qpid/java/common/src/org/apache/qpid/framing/AMQProtocolHeaderException.java b/qpid/java/common/src/org/apache/qpid/framing/AMQProtocolHeaderException.java new file mode 100644 index 0000000000..6809c3d21e --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/AMQProtocolHeaderException.java @@ -0,0 +1,28 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.qpid.AMQException; + +public class AMQProtocolHeaderException extends AMQException +{ + public AMQProtocolHeaderException(String message) + { + super(message); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/AMQProtocolInstanceException.java b/qpid/java/common/src/org/apache/qpid/framing/AMQProtocolInstanceException.java new file mode 100644 index 0000000000..7f5b26010d --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/AMQProtocolInstanceException.java @@ -0,0 +1,26 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +public class AMQProtocolInstanceException extends AMQProtocolHeaderException +{ + public AMQProtocolInstanceException(String message) + { + super(message); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/AMQProtocolVersionException.java b/qpid/java/common/src/org/apache/qpid/framing/AMQProtocolVersionException.java new file mode 100644 index 0000000000..4f5677b41a --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/AMQProtocolVersionException.java @@ -0,0 +1,30 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +/** + * Exception that is thrown when the client and server differ on expected protocol version (header) information. + * + */ +public class AMQProtocolVersionException extends AMQProtocolHeaderException +{ + public AMQProtocolVersionException(String message) + { + super(message); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/BasicContentHeaderProperties.java b/qpid/java/common/src/org/apache/qpid/framing/BasicContentHeaderProperties.java new file mode 100644 index 0000000000..20eafa0be7 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/BasicContentHeaderProperties.java @@ -0,0 +1,592 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.log4j.Logger; +import org.apache.mina.common.ByteBuffer; + +public class BasicContentHeaderProperties implements ContentHeaderProperties +{ + private static final Logger _logger = Logger.getLogger(BasicContentHeaderProperties.class); + + /** + * We store the encoded form when we decode the content header so that if we need to + * write it out without modifying it we can do so without incurring the expense of + * reencoding it + */ + private byte[] _encodedForm; + + /** + * Flag indicating whether the entire content header has been decoded yet + */ + private boolean _decoded = true; + + /** + * We have some optimisations for partial decoding for maximum performance. The headers are used in the broker + * for routing in some cases so we can decode that separately. + */ + private boolean _decodedHeaders = true; + + /** + * We have some optimisations for partial decoding for maximum performance. The content type is used by all + * clients to determine the message type + */ + private boolean _decodedContentType = true; + + private String _contentType; + + private String _encoding; + + private FieldTable _headers; + + private byte _deliveryMode; + + private byte _priority; + + private String _correlationId; + + private String _replyTo; + + private long _expiration; + + private String _messageId; + + private long _timestamp; + + private String _type; + + private String _userId; + + private String _appId; + + private String _clusterId; + + private int _propertyFlags = 0; + + public BasicContentHeaderProperties() + { + } + + public int getPropertyListSize() + { + if (_encodedForm != null) + { + return _encodedForm.length; + } + else + { + int size = 0; + + if ((_propertyFlags & (1 << 15)) > 0) + { + size += EncodingUtils.encodedShortStringLength(_contentType); + } + if ((_propertyFlags & (1 << 14)) > 0) + { + size += EncodingUtils.encodedShortStringLength(_encoding); + } + if ((_propertyFlags & (1 << 13)) > 0) + { + size += EncodingUtils.encodedFieldTableLength(_headers); + } + if ((_propertyFlags & (1 << 12)) > 0) + { + size += 1; + } + if ((_propertyFlags & (1 << 11)) > 0) + { + size += 1; + } + if ((_propertyFlags & (1 << 10)) > 0) + { + size += EncodingUtils.encodedShortStringLength(_correlationId); + } + if ((_propertyFlags & (1 << 9)) > 0) + { + size += EncodingUtils.encodedShortStringLength(_replyTo); + } + if ((_propertyFlags & (1 << 8)) > 0) + { + size += EncodingUtils.encodedShortStringLength(String.valueOf(_expiration)); + } + if ((_propertyFlags & (1 << 7)) > 0) + { + size += EncodingUtils.encodedShortStringLength(_messageId); + } + if ((_propertyFlags & (1 << 6)) > 0) + { + size += 8; + } + if ((_propertyFlags & (1 << 5)) > 0) + { + size += EncodingUtils.encodedShortStringLength(_type); + } + if ((_propertyFlags & (1 << 4)) > 0) + { + size += EncodingUtils.encodedShortStringLength(_userId); + } + if ((_propertyFlags & (1 << 3)) > 0) + { + size += EncodingUtils.encodedShortStringLength(_appId); + } + if ((_propertyFlags & (1 << 2)) > 0) + { + size += EncodingUtils.encodedShortStringLength(_clusterId); + } + return size; + } + } + + private void clearEncodedForm() + { + if (!_decoded && _encodedForm != null) + { + //decode(); + } + _encodedForm = null; + } + + public void setPropertyFlags(int propertyFlags) + { + clearEncodedForm(); + _propertyFlags = propertyFlags; + } + + public int getPropertyFlags() + { + return _propertyFlags; + } + + public void writePropertyListPayload(ByteBuffer buffer) + { + if (_encodedForm != null) + { + buffer.put(_encodedForm); + } + else + { + if ((_propertyFlags & (1 << 15)) > 0) + { + EncodingUtils.writeShortStringBytes(buffer, _contentType); + } + if ((_propertyFlags & (1 << 14)) > 0) + { + EncodingUtils.writeShortStringBytes(buffer, _encoding); + } + if ((_propertyFlags & (1 << 13)) > 0) + { + EncodingUtils.writeFieldTableBytes(buffer, _headers); + } + if ((_propertyFlags & (1 << 12)) > 0) + { + buffer.put(_deliveryMode); + } + if ((_propertyFlags & (1 << 11)) > 0) + { + buffer.put(_priority); + } + if ((_propertyFlags & (1 << 10)) > 0) + { + EncodingUtils.writeShortStringBytes(buffer, _correlationId); + } + if ((_propertyFlags & (1 << 9)) > 0) + { + EncodingUtils.writeShortStringBytes(buffer, _replyTo); + } + if ((_propertyFlags & (1 << 8)) > 0) + { + EncodingUtils.writeShortStringBytes(buffer, String.valueOf(_expiration)); + } + if ((_propertyFlags & (1 << 7)) > 0) + { + EncodingUtils.writeShortStringBytes(buffer, _messageId); + } + if ((_propertyFlags & (1 << 6)) > 0) + { + EncodingUtils.writeUnsignedInteger(buffer, 0/*timestamp msb*/); + EncodingUtils.writeUnsignedInteger(buffer, _timestamp); + } + if ((_propertyFlags & (1 << 5)) > 0) + { + EncodingUtils.writeShortStringBytes(buffer, _type); + } + if ((_propertyFlags & (1 << 4)) > 0) + { + EncodingUtils.writeShortStringBytes(buffer, _userId); + } + if ((_propertyFlags & (1 << 3)) > 0) + { + EncodingUtils.writeShortStringBytes(buffer, _appId); + } + if ((_propertyFlags & (1 << 2)) > 0) + { + EncodingUtils.writeShortStringBytes(buffer, _clusterId); + } + } + } + + public void populatePropertiesFromBuffer(ByteBuffer buffer, int propertyFlags, int size) + throws AMQFrameDecodingException + { + _propertyFlags = propertyFlags; + + if (_logger.isDebugEnabled()) + { + _logger.debug("Property flags: " + _propertyFlags); + } + decode(buffer); + /*_encodedForm = new byte[size]; + buffer.get(_encodedForm, 0, size); + _decoded = false; + _decodedHeaders = false; + _decodedContentType = false;*/ + } + + private void decode(ByteBuffer buffer) + { + //ByteBuffer buffer = ByteBuffer.wrap(_encodedForm); + int pos = buffer.position(); + try + { + if ((_propertyFlags & (1 << 15)) > 0) + { + _contentType = EncodingUtils.readShortString(buffer); + } + if ((_propertyFlags & (1 << 14)) > 0) + { + _encoding = EncodingUtils.readShortString(buffer); + } + if ((_propertyFlags & (1 << 13)) > 0) + { + _headers = EncodingUtils.readFieldTable(buffer); + } + if ((_propertyFlags & (1 << 12)) > 0) + { + _deliveryMode = buffer.get(); + } + if ((_propertyFlags & (1 << 11)) > 0) + { + _priority = buffer.get(); + } + if ((_propertyFlags & (1 << 10)) > 0) + { + _correlationId = EncodingUtils.readShortString(buffer); + } + if ((_propertyFlags & (1 << 9)) > 0) + { + _replyTo = EncodingUtils.readShortString(buffer); + } + if ((_propertyFlags & (1 << 8)) > 0) + { + _expiration = Long.parseLong(EncodingUtils.readShortString(buffer)); + } + if ((_propertyFlags & (1 << 7)) > 0) + { + _messageId = EncodingUtils.readShortString(buffer); + } + if ((_propertyFlags & (1 << 6)) > 0) + { + // Discard msb from AMQ timestamp + buffer.getUnsignedInt(); + _timestamp = buffer.getUnsignedInt(); + } + if ((_propertyFlags & (1 << 5)) > 0) + { + _type = EncodingUtils.readShortString(buffer); + } + if ((_propertyFlags & (1 << 4)) > 0) + { + _userId = EncodingUtils.readShortString(buffer); + } + if ((_propertyFlags & (1 << 3)) > 0) + { + _appId = EncodingUtils.readShortString(buffer); + } + if ((_propertyFlags & (1 << 2)) > 0) + { + _clusterId = EncodingUtils.readShortString(buffer); + } + } + catch (AMQFrameDecodingException e) + { + throw new RuntimeException("Error in content header data: " + e); + } + + final int endPos = buffer.position(); + buffer.position(pos); + final int len = endPos - pos; + _encodedForm = new byte[len]; + final int limit = buffer.limit(); + buffer.limit(endPos); + buffer.get(_encodedForm, 0, len); + buffer.limit(limit); + buffer.position(endPos); + _decoded = true; + } + + + private void decodeUpToHeaders() + { + ByteBuffer buffer = ByteBuffer.wrap(_encodedForm); + try + { + if ((_propertyFlags & (1 << 15)) > 0) + { + byte length = buffer.get(); + buffer.skip(length); + } + if ((_propertyFlags & (1 << 14)) > 0) + { + byte length = buffer.get(); + buffer.skip(length); + } + if ((_propertyFlags & (1 << 13)) > 0) + { + _headers = EncodingUtils.readFieldTable(buffer); + } + _decodedHeaders = true; + } + catch (AMQFrameDecodingException e) + { + throw new RuntimeException("Error in content header data: " + e); + } + } + + private void decodeUpToContentType() + { + ByteBuffer buffer = ByteBuffer.wrap(_encodedForm); + + if ((_propertyFlags & (1 << 15)) > 0) + { + _contentType = EncodingUtils.readShortString(buffer); + } + + _decodedContentType = true; + } + + private void decodeIfNecessary() + { + if (!_decoded) + { + //decode(); + } + } + + private void decodeHeadersIfNecessary() + { + if (!_decoded && !_decodedHeaders) + { + decodeUpToHeaders(); + } + } + + private void decodeContentTypeIfNecessary() + { + if (!_decoded && !_decodedContentType) + { + decodeUpToContentType(); + } + } + public String getContentType() + { + decodeContentTypeIfNecessary(); + return _contentType; + } + + public void setContentType(String contentType) + { + clearEncodedForm(); + _propertyFlags |= (1 << 15); + _contentType = contentType; + } + + public String getEncoding() + { + decodeIfNecessary(); + return _encoding; + } + + public void setEncoding(String encoding) + { + clearEncodedForm(); + _propertyFlags |= (1 << 14); + _encoding = encoding; + } + + public FieldTable getHeaders() + { + decodeHeadersIfNecessary(); + return _headers; + } + + public void setHeaders(FieldTable headers) + { + clearEncodedForm(); + _propertyFlags |= (1 << 13); + _headers = headers; + } + + public byte getDeliveryMode() + { + decodeIfNecessary(); + return _deliveryMode; + } + + public void setDeliveryMode(byte deliveryMode) + { + clearEncodedForm(); + _propertyFlags |= (1 << 12); + _deliveryMode = deliveryMode; + } + + public byte getPriority() + { + decodeIfNecessary(); + return _priority; + } + + public void setPriority(byte priority) + { + clearEncodedForm(); + _propertyFlags |= (1 << 11); + _priority = priority; + } + + public String getCorrelationId() + { + decodeIfNecessary(); + return _correlationId; + } + + public void setCorrelationId(String correlationId) + { + clearEncodedForm(); + _propertyFlags |= (1 << 10); + _correlationId = correlationId; + } + + public String getReplyTo() + { + decodeIfNecessary(); + return _replyTo; + } + + public void setReplyTo(String replyTo) + { + clearEncodedForm(); + _propertyFlags |= (1 << 9); + _replyTo = replyTo; + } + + public long getExpiration() + { + decodeIfNecessary(); + return _expiration; + } + + public void setExpiration(long expiration) + { + clearEncodedForm(); + _propertyFlags |= (1 << 8); + _expiration = expiration; + } + + + public String getMessageId() + { + decodeIfNecessary(); + return _messageId; + } + + public void setMessageId(String messageId) + { + clearEncodedForm(); + _propertyFlags |= (1 << 7); + _messageId = messageId; + } + + public long getTimestamp() + { + decodeIfNecessary(); + return _timestamp; + } + + public void setTimestamp(long timestamp) + { + clearEncodedForm(); + _propertyFlags |= (1 << 6); + _timestamp = timestamp; + } + + public String getType() + { + decodeIfNecessary(); + return _type; + } + + public void setType(String type) + { + clearEncodedForm(); + _propertyFlags |= (1 << 5); + _type = type; + } + + public String getUserId() + { + decodeIfNecessary(); + return _userId; + } + + public void setUserId(String userId) + { + clearEncodedForm(); + _propertyFlags |= (1 << 4); + _userId = userId; + } + + public String getAppId() + { + decodeIfNecessary(); + return _appId; + } + + public void setAppId(String appId) + { + clearEncodedForm(); + _propertyFlags |= (1 << 3); + _appId = appId; + } + + public String getClusterId() + { + decodeIfNecessary(); + return _clusterId; + } + + public void setClusterId(String clusterId) + { + clearEncodedForm(); + _propertyFlags |= (1 << 2); + _clusterId = clusterId; + } + + public String toString() + { + return "reply-to = " + _replyTo + " propertyFlags = " + _propertyFlags; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/BodyFactory.java b/qpid/java/common/src/org/apache/qpid/framing/BodyFactory.java new file mode 100644 index 0000000000..cd40558de8 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/BodyFactory.java @@ -0,0 +1,28 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; + +/** + * Any class that is capable of turning a stream of bytes into an AMQ structure must implement this interface. + */ +public interface BodyFactory +{ + AMQBody createBody(ByteBuffer in) throws AMQFrameDecodingException; +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/CompositeAMQDataBlock.java b/qpid/java/common/src/org/apache/qpid/framing/CompositeAMQDataBlock.java new file mode 100644 index 0000000000..35e29aa064 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/CompositeAMQDataBlock.java @@ -0,0 +1,100 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; + +public class CompositeAMQDataBlock extends AMQDataBlock implements EncodableAMQDataBlock +{ + private ByteBuffer _encodedBlock; + + private AMQDataBlock[] _blocks; + + public CompositeAMQDataBlock(AMQDataBlock[] blocks) + { + _blocks = blocks; + } + + /** + * The encoded block will be logically first before the AMQDataBlocks which are encoded + * into the buffer afterwards. + * @param encodedBlock already-encoded data + * @param blocks some blocks to be encoded. + */ + public CompositeAMQDataBlock(ByteBuffer encodedBlock, AMQDataBlock[] blocks) + { + this(blocks); + _encodedBlock = encodedBlock; + } + + public AMQDataBlock[] getBlocks() + { + return _blocks; + } + + public ByteBuffer getEncodedBlock() + { + return _encodedBlock; + } + + public long getSize() + { + long frameSize = 0; + for (int i = 0; i < _blocks.length; i++) + { + frameSize += _blocks[i].getSize(); + } + if (_encodedBlock != null) + { + _encodedBlock.rewind(); + frameSize += _encodedBlock.remaining(); + } + return frameSize; + } + + public void writePayload(ByteBuffer buffer) + { + if (_encodedBlock != null) + { + buffer.put(_encodedBlock); + } + for (int i = 0; i < _blocks.length; i++) + { + _blocks[i].writePayload(buffer); + } + } + + public String toString() + { + if (_blocks == null) + { + return "No blocks contained in composite frame"; + } + else + { + StringBuilder buf = new StringBuilder(this.getClass().getName()); + buf.append("{encodedBlock=").append(_encodedBlock); + for (int i = 0 ; i < _blocks.length; i++) + { + buf.append(" ").append(i).append("=[").append(_blocks[i].toString()).append("]"); + } + buf.append("}"); + return buf.toString(); + } + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/ContentBody.java b/qpid/java/common/src/org/apache/qpid/framing/ContentBody.java new file mode 100644 index 0000000000..a345d1d225 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/ContentBody.java @@ -0,0 +1,64 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; + +public class ContentBody extends AMQBody +{ + public static final byte TYPE = 3; + + public ByteBuffer payload; + + protected byte getType() + { + return TYPE; + } + + public int getSize() + { + return (payload == null?0:payload.limit()); + } + + public void writePayload(ByteBuffer buffer) + { + if (payload != null) + { + ByteBuffer copy = payload.duplicate(); + buffer.put(copy.rewind()); + } + } + + protected void populateFromBuffer(ByteBuffer buffer, long size) throws AMQFrameDecodingException + { + if (size > 0) + { + payload = buffer.slice(); + payload.limit((int)size); + buffer.skip((int)size); + } + } + + public static AMQFrame createAMQFrame(int channelId, ContentBody body) + { + final AMQFrame frame = new AMQFrame(); + frame.channel = channelId; + frame.bodyFrame = body; + return frame; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/ContentBodyFactory.java b/qpid/java/common/src/org/apache/qpid/framing/ContentBodyFactory.java new file mode 100644 index 0000000000..1d6b72ce76 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/ContentBodyFactory.java @@ -0,0 +1,44 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.log4j.Logger; +import org.apache.mina.common.ByteBuffer; + +public class ContentBodyFactory implements BodyFactory +{ + private static final Logger _log = Logger.getLogger(AMQMethodBodyFactory.class); + + private static final ContentBodyFactory _instance = new ContentBodyFactory(); + + public static ContentBodyFactory getInstance() + { + return _instance; + } + + private ContentBodyFactory() + { + _log.debug("Creating content body factory"); + } + + public AMQBody createBody(ByteBuffer in) throws AMQFrameDecodingException + { + return new ContentBody(); + } +} + diff --git a/qpid/java/common/src/org/apache/qpid/framing/ContentHeaderBody.java b/qpid/java/common/src/org/apache/qpid/framing/ContentHeaderBody.java new file mode 100644 index 0000000000..35ce107831 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/ContentHeaderBody.java @@ -0,0 +1,112 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; + +public class ContentHeaderBody extends AMQBody +{ + public static final byte TYPE = 2; + + public int classId; + + public int weight; + + /** unsigned long but java can't handle that anyway when allocating byte array */ + public long bodySize; + + /** must never be null */ + public ContentHeaderProperties properties; + + public ContentHeaderBody() + { + } + + public ContentHeaderBody(ContentHeaderProperties props, int classId) + { + properties = props; + this.classId = classId; + } + + public ContentHeaderBody(int classId, int weight, ContentHeaderProperties props, long bodySize) + { + this(props, classId); + this.weight = weight; + this.bodySize = bodySize; + } + + protected byte getType() + { + return TYPE; + } + + protected void populateFromBuffer(ByteBuffer buffer, long size) throws AMQFrameDecodingException + { + classId = buffer.getUnsignedShort(); + weight = buffer.getUnsignedShort(); + bodySize = buffer.getLong(); + int propertyFlags = buffer.getUnsignedShort(); + ContentHeaderPropertiesFactory factory = ContentHeaderPropertiesFactory.getInstance(); + properties = factory.createContentHeaderProperties(classId, propertyFlags, buffer, (int)size - 14); + } + + /** + * Helper method that is used currently by the persistence layer (by BDB at the moment). + * @param buffer + * @param size + * @return + * @throws AMQFrameDecodingException + */ + public static ContentHeaderBody createFromBuffer(ByteBuffer buffer, long size) throws AMQFrameDecodingException + { + ContentHeaderBody body = new ContentHeaderBody(); + body.populateFromBuffer(buffer, size); + return body; + } + + public int getSize() + { + return 2 + 2 + 8 + 2 + properties.getPropertyListSize(); + } + + public void writePayload(ByteBuffer buffer) + { + EncodingUtils.writeUnsignedShort(buffer, classId); + EncodingUtils.writeUnsignedShort(buffer, weight); + buffer.putLong(bodySize); + EncodingUtils.writeUnsignedShort(buffer, properties.getPropertyFlags()); + properties.writePropertyListPayload(buffer); + } + + public static AMQFrame createAMQFrame(int channelId, int classId, int weight, BasicContentHeaderProperties properties, + long bodySize) + { + final AMQFrame frame = new AMQFrame(); + frame.channel = channelId; + frame.bodyFrame = new ContentHeaderBody(classId, weight, properties, bodySize); + return frame; + } + + public static AMQFrame createAMQFrame(int channelId, ContentHeaderBody body) + { + final AMQFrame frame = new AMQFrame(); + frame.channel = channelId; + frame.bodyFrame = body; + return frame; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/ContentHeaderBodyFactory.java b/qpid/java/common/src/org/apache/qpid/framing/ContentHeaderBodyFactory.java new file mode 100644 index 0000000000..236c5094fc --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/ContentHeaderBodyFactory.java @@ -0,0 +1,47 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.log4j.Logger; +import org.apache.mina.common.ByteBuffer; + +public class ContentHeaderBodyFactory implements BodyFactory +{ + private static final Logger _log = Logger.getLogger(AMQMethodBodyFactory.class); + + private static final ContentHeaderBodyFactory _instance = new ContentHeaderBodyFactory(); + + public static ContentHeaderBodyFactory getInstance() + { + return _instance; + } + + private ContentHeaderBodyFactory() + { + _log.debug("Creating content header body factory"); + } + + public AMQBody createBody(ByteBuffer in) throws AMQFrameDecodingException + { + // all content headers are the same - it is only the properties that differ. + // the content header body further delegates construction of properties + return new ContentHeaderBody(); + } + + +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/ContentHeaderProperties.java b/qpid/java/common/src/org/apache/qpid/framing/ContentHeaderProperties.java new file mode 100644 index 0000000000..65b629bf17 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/ContentHeaderProperties.java @@ -0,0 +1,55 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; + +/** + * There will be an implementation of this interface for each content type. All content types have associated + * header properties and this provides a way to encode and decode them. + */ +public interface ContentHeaderProperties +{ + /** + * Writes the property list to the buffer, in a suitably encoded form. + * @param buffer The buffer to write to + */ + void writePropertyListPayload(ByteBuffer buffer); + + /** + * Populates the properties from buffer. + * @param buffer The buffer to read from. + * @param propertyFlags he property flags. + * @throws AMQFrameDecodingException when the buffer does not contain valid data + */ + void populatePropertiesFromBuffer(ByteBuffer buffer, int propertyFlags, int size) + throws AMQFrameDecodingException; + + /** + * @return the size of the encoded property list in bytes. + */ + int getPropertyListSize(); + + /** + * Gets the property flags. Property flags indicate which properties are set in the list. The + * position and meaning of each flag is defined in the protocol specification for the particular + * content type with which these properties are associated. + * @return flags + */ + int getPropertyFlags(); +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java b/qpid/java/common/src/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java new file mode 100644 index 0000000000..ea1b0d6ef5 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java @@ -0,0 +1,51 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; + +public class ContentHeaderPropertiesFactory +{ + private static final ContentHeaderPropertiesFactory _instance = new ContentHeaderPropertiesFactory(); + + public static ContentHeaderPropertiesFactory getInstance() + { + return _instance; + } + + private ContentHeaderPropertiesFactory() + { + } + + public ContentHeaderProperties createContentHeaderProperties(int classId, int propertyFlags, + ByteBuffer buffer, int size) + throws AMQFrameDecodingException + { + ContentHeaderProperties properties; + switch (classId) + { + case BasicConsumeBody.CLASS_ID: + properties = new BasicContentHeaderProperties(); + break; + default: + throw new AMQFrameDecodingException("Unsupport content header class id: " + classId); + } + properties.populatePropertiesFromBuffer(buffer, propertyFlags, size); + return properties; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/EncodableAMQDataBlock.java b/qpid/java/common/src/org/apache/qpid/framing/EncodableAMQDataBlock.java new file mode 100644 index 0000000000..3d493979eb --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/EncodableAMQDataBlock.java @@ -0,0 +1,32 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +/** + * Marker interface to indicate to MINA that a data block should be encoded with the + * single encoder/decoder that we have defined. + * + * Note that due to a bug in MINA all classes must directly implement this interface, even if + * a superclass implements it. + * TODO: fix MINA so that this is not necessary + * + */ +public interface EncodableAMQDataBlock +{ + +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/EncodingUtils.java b/qpid/java/common/src/org/apache/qpid/framing/EncodingUtils.java new file mode 100644 index 0000000000..f2f7a3b7a2 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/EncodingUtils.java @@ -0,0 +1,519 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.log4j.Logger; +import org.apache.mina.common.ByteBuffer; + +import java.nio.charset.Charset; + +public class EncodingUtils +{ + private static final Logger _logger = Logger.getLogger(EncodingUtils.class); + + private static final String STRING_ENCODING = "iso8859-15"; + + private static final Charset _charset = Charset.forName("iso8859-15"); + + public static final int SIZEOF_UNSIGNED_SHORT = 2; + public static final int SIZEOF_UNSIGNED_INT = 4; + + public static int encodedShortStringLength(String s) + { + if (s == null) + { + return 1; + } + else + { + return (short) (1 + s.length()); + } + } + + public static int encodedLongStringLength(String s) + { + if (s == null) + { + return 4; + } + else + { + return 4 + s.length(); + } + } + + public static int encodedLongStringLength(char[] s) + { + if (s == null) + { + return 4; + } + else + { + return 4 + s.length; + } + } + + public static int encodedLongstrLength(byte[] bytes) + { + if (bytes == null) + { + return 4; + } + else + { + return 4 + bytes.length; + } + } + + public static int encodedFieldTableLength(FieldTable table) + { + if (table == null) + { + // size is encoded as 4 octets + return 4; + } + else + { + // size of the table plus 4 octets for the size + return (int)table.getEncodedSize() + 4; + } + } + + public static void writeShortStringBytes(ByteBuffer buffer, String s) + { + if (s != null) + { + byte[] encodedString = new byte[s.length()]; + char[] cha = s.toCharArray(); + for (int i = 0; i < cha.length; i++) + { + encodedString[i] = (byte) cha[i]; + } + // TODO: check length fits in an unsigned byte + writeUnsignedByte(buffer, (short)encodedString.length); + buffer.put(encodedString); + } + else + { + // really writing out unsigned byte + buffer.put((byte) 0); + } + } + + public static void writeLongStringBytes(ByteBuffer buffer, String s) + { + assert s == null || s.length() <= 0xFFFE; + if (s != null) + { + int len = s.length(); + writeUnsignedInteger(buffer, s.length()); + byte[] encodedString = new byte[len]; + char[] cha = s.toCharArray(); + for (int i = 0; i < cha.length; i++) + { + encodedString[i] = (byte) cha[i]; + } + buffer.put(encodedString); + } + else + { + writeUnsignedInteger(buffer, 0); + } + } + + public static void writeLongStringBytes(ByteBuffer buffer, char[] s) + { + assert s == null || s.length <= 0xFFFE; + if (s != null) + { + int len = s.length; + writeUnsignedInteger(buffer, s.length); + byte[] encodedString = new byte[len]; + for (int i = 0; i < s.length; i++) + { + encodedString[i] = (byte) s[i]; + } + buffer.put(encodedString); + } + else + { + writeUnsignedInteger(buffer, 0); + } + } + + public static void writeLongStringBytes(ByteBuffer buffer, byte[] bytes) + { + assert bytes == null || bytes.length <= 0xFFFE; + if (bytes != null) + { + writeUnsignedInteger(buffer, bytes.length); + buffer.put(bytes); + } + else + { + writeUnsignedInteger(buffer, 0); + } + } + + public static void writeUnsignedByte(ByteBuffer buffer, short b) + { + byte bv = (byte) b; + buffer.put(bv); + } + + public static void writeUnsignedShort(ByteBuffer buffer, int s) + { + // TODO: Is this comparison safe? Do I need to cast RHS to long? + if (s < Short.MAX_VALUE) + { + buffer.putShort((short)s); + } + else + { + short sv = (short) s; + buffer.put((byte) (0xFF & (sv >> 8))); + buffer.put((byte)(0xFF & sv)); + } + } + + public static void writeUnsignedInteger(ByteBuffer buffer, long l) + { + // TODO: Is this comparison safe? Do I need to cast RHS to long? + if (l < Integer.MAX_VALUE) + { + buffer.putInt((int)l); + } + else + { + int iv = (int) l; + + // FIXME: This *may* go faster if we build this into a local 4-byte array and then + // put the array in a single call. + buffer.put((byte) (0xFF & (iv >> 24))); + buffer.put((byte) (0xFF & (iv >> 16))); + buffer.put((byte) (0xFF & (iv >> 8 ))); + buffer.put((byte) (0xFF & iv)); + } + } + + public static void writeFieldTableBytes(ByteBuffer buffer, FieldTable table) + { + if (table != null) + { + table.writeToBuffer(buffer); + } + else + { + EncodingUtils.writeUnsignedInteger(buffer, 0); + } + } + + public static void writeBooleans(ByteBuffer buffer, boolean[] values) + { + byte packedValue = 0; + for (int i = 0; i < values.length; i++) + { + if (values[i]) + { + packedValue = (byte)(packedValue | (1 << i)); + } + } + + buffer.put(packedValue); + } + + /** + * This is used for writing longstrs. + * @param buffer + * @param data + */ + public static void writeLongstr(ByteBuffer buffer, byte[] data) + { + if (data != null) + { + writeUnsignedInteger(buffer, data.length); + buffer.put(data); + } + else + { + writeUnsignedInteger(buffer, 0); + } + } + + public static boolean[] readBooleans(ByteBuffer buffer) + { + byte packedValue = buffer.get(); + boolean[] result = new boolean[8]; + + for (int i = 0; i < 8; i++) + { + result[i] = ((packedValue & (1 << i)) != 0); + } + return result; + } + + public static FieldTable readFieldTable(ByteBuffer buffer) throws AMQFrameDecodingException + { + long length = buffer.getUnsignedInt(); + if (length == 0) + { + return null; + } + else + { + return new FieldTable(buffer, length); + } + } + + public static String readShortString(ByteBuffer buffer) + { + short length = buffer.getUnsigned(); + if (length == 0) + { + return null; + } + else + { + // this may seem rather odd to declare two array but testing has shown + // that constructing a string from a byte array is 5 (five) times slower + // than constructing one from a char array. + // this approach here is valid since we know that all the chars are + // ASCII (0-127) + byte[] stringBytes = new byte[length]; + buffer.get(stringBytes, 0, length); + char[] stringChars = new char[length]; + for (int i = 0; i < stringChars.length; i++) + { + stringChars[i] = (char) stringBytes[i]; + } + + return new String(stringChars); + } + } + + public static String readLongString(ByteBuffer buffer) + { + long length = buffer.getUnsignedInt(); + if (length == 0) + { + return null; + } + else + { + // this may seem rather odd to declare two array but testing has shown + // that constructing a string from a byte array is 5 (five) times slower + // than constructing one from a char array. + // this approach here is valid since we know that all the chars are + // ASCII (0-127) + byte[] stringBytes = new byte[(int)length]; + buffer.get(stringBytes, 0, (int)length); + char[] stringChars = new char[(int)length]; + for (int i = 0; i < stringChars.length; i++) + { + stringChars[i] = (char) stringBytes[i]; + } + return new String(stringChars); + } + } + + public static byte[] readLongstr(ByteBuffer buffer) throws AMQFrameDecodingException + { + long length = buffer.getUnsignedInt(); + if (length == 0) + { + return null; + } + else + { + byte[] result = new byte[(int)length]; + buffer.get(result); + return result; + } + } + + // Will barf with a NPE on a null input. Not sure whether it should return null or + // an empty field-table (which would be slower - perhaps unnecessarily). + // + // Some sample input and the result output: + // + // Input: "a=1" "a=2 c=3" "a=3 c=4 d" "a='four' b='five'" "a=bad" + // + // Parsing ... + // {a=1} + // Parsing ... + // {a=2, c=3} + // Parsing ... + // {a=3, c=4, d=null} + // Parsing ... + // {a=four, b=five} + // Parsing ... + // java.lang.IllegalArgumentException: a: Invalid integer in from . + // + public static FieldTable createFieldTableFromMessageSelector(String selector) + { + boolean debug = _logger.isDebugEnabled(); + + // TODO: Doesn't support embedded quotes properly. + String[] expressions = selector.split(" +"); + + FieldTable result = new FieldTable(); + + for(int i = 0; i < expressions.length; i++) + { + String expr = expressions[i]; + + if (debug) _logger.debug("Expression = <" + expr + ">"); + + int equals = expr.indexOf('='); + + if (equals < 0) + { + // Existence check + result.put("S" + expr.trim(),null); + } + else + { + String key = expr.substring(0,equals).trim(); + String value = expr.substring(equals + 1).trim(); + + if (debug) _logger.debug("Key = <" + key + ">, Value = <" + value + ">"); + + if (value.charAt(0) == '\'') + { + if (value.charAt(value.length()- 1) != '\'') + { + throw new IllegalArgumentException(key + ": Missing quote in <" + value + "> from <" + selector + ">."); + } + else + { + value = value.substring(1,value.length() - 1); + + result.put("S" + key,value); + } + } + else + { + try + { + int intValue = Integer.parseInt(value); + + result.put("i" + key,value); + } + catch(NumberFormatException e) + { + throw new IllegalArgumentException(key + ": Invalid integer in <" + value + "> from <" + selector + ">."); + + } + } + } + } + + if (debug) _logger.debug("Field-table created from <" + selector + "> is <" + result + ">"); + + return(result); + + } + + static byte[] hexToByteArray(String id) + { + // Should check param for null, long enough for this check, upper-case and trailing char + String s = (id.charAt(1) == 'x') ? id.substring(2) : id; // strip 0x + + int len = s.length(); + int byte_len = len / 2; + byte[] b = new byte[byte_len]; + + for(int i = 0; i < byte_len; i++) + { + // fixme: refine these repetitive subscript calcs. + int ch = i * 2; + + byte b1 = Byte.parseByte(s.substring(ch,ch + 1),16); + byte b2 = Byte.parseByte(s.substring(ch + 1,ch + 2),16); + + b[i] = (byte)(b1 * 16 + b2); + } + + return(b); + } + + public static char[] convertToHexCharArray(byte[] from) + { + int length = from.length; + char[] result_buff = new char[length * 2 + 2]; + + result_buff[0] = '0'; + result_buff[1] = 'x'; + + int bite; + int dest = 2; + + for(int i = 0; i < length; i++) + { + bite = from[i]; + + if (bite < 0) bite += 256; + + result_buff[dest++] = hex_chars[bite >> 4]; + result_buff[dest++] = hex_chars[bite & 0x0f]; + } + + return(result_buff); + } + + public static String convertToHexString(byte[] from) + { + return(new String(convertToHexCharArray(from))); + } + + public static String convertToHexString(ByteBuffer bb) + { + int size = bb.limit(); + + byte[] from = new byte[size]; + + for(int i = 0; i < size; i++) + { + from[i] = bb.get(i); + } + + return(new String(convertToHexCharArray(from))); + } + + public static void main(String[] args) + { + for(int i = 0; i < args.length; i++) + { + String selector = args[i]; + + System.err.println("Parsing <" + selector + ">..."); + + try + { + System.err.println(createFieldTableFromMessageSelector(selector)); + } + catch(IllegalArgumentException e) + { + System.err.println(e); + } + } + } + + private static char hex_chars[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/FieldTable.java b/qpid/java/common/src/org/apache/qpid/framing/FieldTable.java new file mode 100644 index 0000000000..30f41205dd --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/FieldTable.java @@ -0,0 +1,319 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.log4j.Logger; +import org.apache.mina.common.ByteBuffer; + +import java.util.*; + +/** + * From the protocol document: + * field-table = short-integer *field-value-pair + * field-value-pair = field-name field-value + * field-name = short-string + * field-value = 'S' long-string + * / 'I' long-integer + * / 'D' decimal-value + * / 'T' long-integer + * decimal-value = decimals long-integer + * decimals = OCTET + */ +public class FieldTable extends LinkedHashMap +{ + private static final Logger _logger = Logger.getLogger(FieldTable.class); + private long _encodedSize = 0; + + public FieldTable() + { + super(); + } + + /** + * Construct a new field table. + * + * @param buffer the buffer from which to read data. The length byte must be read already + * @param length the length of the field table. Must be > 0. + * @throws AMQFrameDecodingException if there is an error decoding the table + */ + public FieldTable(ByteBuffer buffer, long length) throws AMQFrameDecodingException + { + super(); + final boolean debug = _logger.isDebugEnabled(); + assert length > 0; + _encodedSize = length; + int sizeRead = 0; + while (sizeRead < _encodedSize) + { + int sizeRemaining = buffer.remaining(); + final String key = EncodingUtils.readShortString(buffer); + // TODO: use proper charset decoder + byte iType = buffer.get(); + final char type = (char) iType; + Object value; + switch (type) + { + case 'S': + value = EncodingUtils.readLongString(buffer); + break; + case 'I': + value = new Long(buffer.getUnsignedInt()); + break; + default: + String msg = "Field '" + key + "' - unsupported field table type: " + type; + //some extra debug information... + msg += " (" + iType + "), length=" + length + ", sizeRead=" + sizeRead + ", sizeRemaining=" + sizeRemaining; + throw new AMQFrameDecodingException(msg); + } + sizeRead += (sizeRemaining - buffer.remaining()); + + if (debug) + { + _logger.debug("FieldTable::FieldTable(buffer," + length + "): Read type '" + type + "', key '" + key + "', value '" + value + "' (now read " + sizeRead + " of " + length + " encoded bytes)..."); + } + + // we deliberately want to call put in the parent class since we do + // not need to do the size calculations + super.put(key, value); + } + + if (debug) + { + _logger.debug("FieldTable::FieldTable(buffer," + length + "): Done."); + } + } + + public void writeToBuffer(ByteBuffer buffer) + { + final boolean debug = _logger.isDebugEnabled(); + + if (debug) + { + _logger.debug("FieldTable::writeToBuffer: Writing encoded size of " + _encodedSize + "..."); + } + + // write out the total length, which we have kept up to date as data is added + EncodingUtils.writeUnsignedInteger(buffer, _encodedSize); + final Iterator it = this.entrySet().iterator(); + while (it.hasNext()) + { + Map.Entry me = (Map.Entry) it.next(); + String key = (String) me.getKey(); + + EncodingUtils.writeShortStringBytes(buffer, key); + Object value = me.getValue(); + + if (debug) + { + _logger.debug("FieldTable::writeToBuffer: Writing key '" + key + "' of type " + value.getClass() + ", value '" + value + "'..."); + } + + if (value instanceof byte[]) + { + buffer.put((byte) 'S'); + EncodingUtils.writeLongstr(buffer, (byte[]) value); + } + else if (value instanceof String) + { + // TODO: look at using proper charset encoder + buffer.put((byte) 'S'); + EncodingUtils.writeLongStringBytes(buffer, (String) value); + } + else if (value instanceof Long) + { + // TODO: look at using proper charset encoder + buffer.put((byte) 'I'); + EncodingUtils.writeUnsignedInteger(buffer, ((Long) value).longValue()); + } + else + { + // Should never get here + throw new IllegalArgumentException("Key '" + key + "': Unsupported type in field table, type: " + ((value == null) ? "null-object" : value.getClass())); + } + } + + if (debug) + { + _logger.debug("FieldTable::writeToBuffer: Done."); + } + } + + public byte[] getDataAsBytes() + { + final ByteBuffer buffer = ByteBuffer.allocate((int) _encodedSize); // XXX: Is cast a problem? + final Iterator it = this.entrySet().iterator(); + while (it.hasNext()) + { + Map.Entry me = (Map.Entry) it.next(); + String key = (String) me.getKey(); + EncodingUtils.writeShortStringBytes(buffer, key); + Object value = me.getValue(); + if (value instanceof byte[]) + { + buffer.put((byte) 'S'); + EncodingUtils.writeLongstr(buffer, (byte[]) value); + } + else if (value instanceof String) + { + // TODO: look at using proper charset encoder + buffer.put((byte) 'S'); + EncodingUtils.writeLongStringBytes(buffer, (String) value); + } + else if (value instanceof char[]) + { + // TODO: look at using proper charset encoder + buffer.put((byte) 'S'); + EncodingUtils.writeLongStringBytes(buffer, (char[]) value); + } + else if (value instanceof Long || value instanceof Integer) + { + // TODO: look at using proper charset encoder + buffer.put((byte) 'I'); + EncodingUtils.writeUnsignedInteger(buffer, ((Long) value).longValue()); + } + else + { + // Should never get here + assert false; + } + } + final byte[] result = new byte[(int) _encodedSize]; + buffer.flip(); + buffer.get(result); + buffer.release(); + return result; + } + + public Object put(Object key, Object value) + { + final boolean debug = _logger.isDebugEnabled(); + + if (key == null) + { + throw new IllegalArgumentException("All keys must be Strings - was passed: null"); + } + else if (!(key instanceof String)) + { + throw new IllegalArgumentException("All keys must be Strings - was passed: " + key.getClass()); + } + + Object existing; + + if ((existing = super.remove(key)) != null) + { + if (debug) + { + _logger.debug("Found duplicate of key '" + key + "', previous value '" + existing + "' (" + existing.getClass() + "), to be replaced by '" + value + "', (" + value.getClass() + ") - stack trace of source of duplicate follows...", new Throwable().fillInStackTrace()); + } + + // If we are in effect deleting the value (see comment on null values being deleted + // below) then we also need to remove the name from the encoding length. + if (value == null) + { + _encodedSize -= EncodingUtils.encodedShortStringLength((String) key); + } + + // FIXME: Should be able to short-cut this process if the old and new values are + // the same object and/or type and size... + _encodedSize -= getEncodingSize(existing); + } + else + { + if (value != null) + { + _encodedSize += EncodingUtils.encodedShortStringLength((String) key); + } + } + + // For now: Setting a null value is the equivalent of deleting it. + // This is ambiguous in the JMS spec and needs thrashing out and potentially + // testing against other implementations. + if (value != null) + { + _encodedSize += getEncodingSize(value); + } + + return super.put(key, value); + } + + public Object remove(Object key) + { + if (super.containsKey(key)) + { + final Object value = super.remove(key); + _encodedSize -= EncodingUtils.encodedShortStringLength((String) key); + + // This check is, for now, unnecessary (we don't store null values). + if (value != null) + { + _encodedSize -= getEncodingSize(value); + } + + return value; + } + else + { + return null; + } + } + + /** + * @return unsigned integer + */ + public long getEncodedSize() + { + return _encodedSize; + } + + /** + * @return integer + */ + private static int getEncodingSize(Object value) + { + int encodingSize; + + // the extra byte if for the type indicator that is written out + if (value instanceof String) + { + encodingSize = 1 + EncodingUtils.encodedLongStringLength((String) value); + } + else if (value instanceof char[]) + { + encodingSize = 1 + EncodingUtils.encodedLongStringLength((char[]) value); + } + else if (value instanceof Integer) + { + encodingSize = 1 + 4; + } + else if (value instanceof Long) + { + encodingSize = 1 + 4; + } + else + { + throw new IllegalArgumentException("Unsupported type in field table: " + value.getClass()); + } + + return encodingSize; + } + + public Enumeration keys() + { + return new FieldTableKeyEnumeration(this); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/FieldTableKeyEnumeration.java b/qpid/java/common/src/org/apache/qpid/framing/FieldTableKeyEnumeration.java new file mode 100644 index 0000000000..2bc890ebbc --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/FieldTableKeyEnumeration.java @@ -0,0 +1,44 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import java.util.Enumeration; +import java.util.Iterator; + + +public class FieldTableKeyEnumeration implements Enumeration +{ + protected FieldTable _table; + protected Iterator _iterator; + + public FieldTableKeyEnumeration(FieldTable ft) + { + _table = ft; + _iterator = ft.keySet().iterator(); + } + + public boolean hasMoreElements() + { + return _iterator.hasNext(); + } + + public Object nextElement() + { + return _iterator.next(); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/HeartbeatBody.java b/qpid/java/common/src/org/apache/qpid/framing/HeartbeatBody.java new file mode 100644 index 0000000000..4dda794427 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/HeartbeatBody.java @@ -0,0 +1,54 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; + +public class HeartbeatBody extends AMQBody +{ + public static final byte TYPE = 8; + public static AMQFrame FRAME = new HeartbeatBody().toFrame(); + + protected byte getType() + { + return TYPE; + } + + protected int getSize() + { + return 0;//heartbeats we generate have no payload + } + + protected void writePayload(ByteBuffer buffer) + { + } + + protected void populateFromBuffer(ByteBuffer buffer, long size) throws AMQFrameDecodingException + { + if(size > 0) + { + //allow other implementations to have a payload, but ignore it: + buffer.skip((int) size); + } + } + + public AMQFrame toFrame() + { + return new AMQFrame(0, this); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/HeartbeatBodyFactory.java b/qpid/java/common/src/org/apache/qpid/framing/HeartbeatBodyFactory.java new file mode 100644 index 0000000000..1d63f3827b --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/HeartbeatBodyFactory.java @@ -0,0 +1,28 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; + +public class HeartbeatBodyFactory implements BodyFactory +{ + public AMQBody createBody(ByteBuffer in) throws AMQFrameDecodingException + { + return new HeartbeatBody(); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/framing/ProtocolInitiation.java b/qpid/java/common/src/org/apache/qpid/framing/ProtocolInitiation.java new file mode 100644 index 0000000000..e500a683dc --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/framing/ProtocolInitiation.java @@ -0,0 +1,176 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.framing; + +import org.apache.mina.common.ByteBuffer; +import org.apache.mina.common.IoSession; +import org.apache.mina.filter.codec.ProtocolDecoderOutput; +import org.apache.qpid.AMQException; + +public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQDataBlock +{ + public char[] header = new char[]{'A','M','Q','P'}; + // TODO: generate these constants automatically from the xml protocol spec file + + private static byte CURRENT_PROTOCOL_CLASS = 1; + private static final int CURRENT_PROTOCOL_INSTANCE = 1; + + public byte protocolClass = CURRENT_PROTOCOL_CLASS; + public byte protocolInstance = CURRENT_PROTOCOL_INSTANCE; + public byte protocolMajor; + public byte protocolMinor; + +// public ProtocolInitiation() {} + + public ProtocolInitiation(byte major, byte minor) + { + protocolMajor = major; + protocolMinor = minor; + } + + public long getSize() + { + return 4 + 1 + 1 + 1 + 1; + } + + public void writePayload(ByteBuffer buffer) + { + for (int i = 0; i < header.length; i++) + { + buffer.put((byte) header[i]); + } + buffer.put(protocolClass); + buffer.put(protocolInstance); + buffer.put(protocolMajor); + buffer.put(protocolMinor); + } + + public void populateFromBuffer(ByteBuffer buffer) throws AMQException + { + throw new AMQException("Method not implemented"); + } + + public boolean equals(Object o) + { + if (!(o instanceof ProtocolInitiation)) + { + return false; + } + + ProtocolInitiation pi = (ProtocolInitiation) o; + if (pi.header == null) + { + return false; + } + + if (header.length != pi.header.length) + { + return false; + } + + for (int i = 0; i < header.length; i++) + { + if (header[i] != pi.header[i]) + { + return false; + } + } + + return (protocolClass == pi.protocolClass && + protocolInstance == pi.protocolInstance && + protocolMajor == pi.protocolMajor && + protocolMinor == pi.protocolMinor); + } + + public static class Decoder //implements MessageDecoder + { + /** + * + * @param session + * @param in + * @return true if we have enough data to decode the PI frame fully, false if more + * data is required + */ + public boolean decodable(IoSession session, ByteBuffer in) + { + return (in.remaining() >= 8); + } + + public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) + throws Exception + { + byte[] theHeader = new byte[4]; + in.get(theHeader); + ProtocolInitiation pi = new ProtocolInitiation((byte)0, (byte)0); + pi.header = new char[]{(char) theHeader[0],(char) theHeader[CURRENT_PROTOCOL_INSTANCE],(char) theHeader[2], (char) theHeader[3]}; + String stringHeader = new String(pi.header); + if (!"AMQP".equals(stringHeader)) + { + throw new AMQProtocolHeaderException("Invalid protocol header - read " + stringHeader); + } + pi.protocolClass = in.get(); + pi.protocolInstance = in.get(); + pi.protocolMajor = in.get(); + pi.protocolMinor = in.get(); + out.write(pi); + } + } + + public void checkVersion(ProtocolVersionList pvl) throws AMQException + { + if (protocolClass != CURRENT_PROTOCOL_CLASS) + { + throw new AMQProtocolClassException("Protocol class " + CURRENT_PROTOCOL_CLASS + " was expected; received " + + protocolClass); + } + if (protocolInstance != CURRENT_PROTOCOL_INSTANCE) + { + throw new AMQProtocolInstanceException("Protocol instance " + CURRENT_PROTOCOL_INSTANCE + " was expected; received " + + protocolInstance); + } + /* + if (protocolMajor != CURRENT_PROTOCOL_VERSION_MAJOR) + { + throw new AMQProtocolVersionException("Protocol major version " + CURRENT_PROTOCOL_VERSION_MAJOR + + " was expected; received " + protocolMajor); + } + if (protocolMinor != CURRENT_PROTOCOL_VERSION_MINOR) + { + throw new AMQProtocolVersionException("Protocol minor version " + CURRENT_PROTOCOL_VERSION_MINOR + + " was expected; received " + protocolMinor); + } + */ + + /* Look through list of available protocol versions */ + boolean found = false; + for (int i=0; iaddress and handles incoming + * connections with the specified handler. Backlog value + * is configured to the value of backlog property. + * + * @throws IOException if failed to bind + */ + public void bind(SocketAddress address, IoHandler handler, IoServiceConfig config) throws IOException + { + if (address == null) + { + throw new NullPointerException("address"); + } + + if (handler == null) + { + throw new NullPointerException("handler"); + } + + if (!(address instanceof InetSocketAddress)) + { + throw new IllegalArgumentException("Unexpected address type: " + address.getClass()); + } + + if (((InetSocketAddress) address).getPort() == 0) + { + throw new IllegalArgumentException("Unsupported port number: 0"); + } + + if (config == null) + { + config = getDefaultConfig(); + } + + RegistrationRequest request = new RegistrationRequest(address, handler, config); + + synchronized (this) + { + synchronized (registerQueue) + { + registerQueue.push(request); + } + startupWorker(); + } + + selector.wakeup(); + + synchronized (request) + { + while (!request.done) + { + try + { + request.wait(); + } + catch (InterruptedException e) + { + } + } + } + + if (request.exception != null) + { + throw request.exception; + } + } + + + private synchronized void startupWorker() throws IOException + { + if (worker == null) + { + selector = Selector.open(); + worker = new Worker(); + + worker.start(); + } + } + + public Set getManagedSessions(SocketAddress address) + { + if (address == null) + { + throw new NullPointerException("address"); + } + + Set managedSessions = (Set) sessions.get(address); + + if (managedSessions == null) + { + throw new IllegalArgumentException("Address not bound: " + address); + } + + return Collections.unmodifiableSet( + new IdentityHashSet(Arrays.asList(managedSessions.toArray()))); + } + + public void unbind(SocketAddress address) + { + if (address == null) + { + throw new NullPointerException("address"); + } + + final Set managedSessions = (Set) sessions.get(address); + CancellationRequest request = new CancellationRequest(address); + synchronized (this) + { + try + { + startupWorker(); + } + catch (IOException e) + { + // IOException is thrown only when Worker thread is not + // running and failed to open a selector. We simply throw + // IllegalArgumentException here because we can simply + // conclude that nothing is bound to the selector. + throw new IllegalArgumentException("Address not bound: " + address); + } + + synchronized (cancelQueue) + { + cancelQueue.push(request); + } + } + + selector.wakeup(); + + synchronized (request) + { + while (!request.done) + { + try + { + request.wait(); + } + catch (InterruptedException e) + { + } + } + } + + if (request.exception != null) + { + request.exception.fillInStackTrace(); + + throw request.exception; + } + + // Disconnect all clients + IoServiceConfig cfg = request.registrationRequest.config; + boolean disconnectOnUnbind; + if (cfg instanceof IoAcceptorConfig) + { + disconnectOnUnbind = ((IoAcceptorConfig) cfg).isDisconnectOnUnbind(); + } + else + { + disconnectOnUnbind = ((IoAcceptorConfig) getDefaultConfig()).isDisconnectOnUnbind(); + } + + if (disconnectOnUnbind && managedSessions != null) + { + IoSession[] tempSessions = (IoSession[]) + managedSessions.toArray(new IoSession[ 0 ]); + + final Object lock = new Object(); + + for (int i = 0; i < tempSessions.length; i++) + { + if (!managedSessions.contains(tempSessions[i])) + { + // The session has already been closed and have been + // removed from managedSessions by the SocketIoProcessor. + continue; + } + tempSessions[i].close().setCallback(new IoFuture.Callback() + { + public void operationComplete(IoFuture future) + { + synchronized (lock) + { + lock.notify(); + } + } + }); + } + + try + { + synchronized (lock) + { + while (!managedSessions.isEmpty()) + { + lock.wait(1000); + } + } + } + catch (InterruptedException ie) + { + // Ignored + } + } + } + + public void unbindAll() + { + List addresses; + synchronized (channels) + { + addresses = new ArrayList(channels.keySet()); + } + + for (Iterator i = addresses.iterator(); i.hasNext();) + { + unbind((SocketAddress) i.next()); + } + } + + public boolean isBound(SocketAddress address) + { + synchronized (channels) + { + return channels.containsKey(address); + } + } + + public Set getBoundAddresses() + { + return wrapper.getBoundAddresses(); + } + + private class Worker extends Thread + { + public Worker() + { + super(SocketAcceptorDelegate.this.threadName); + } + + public void run() + { + for (; ;) + { + try + { + int nKeys = selector.select(); + + registerNew(); + cancelKeys(); + + if (nKeys > 0) + { + processSessions(selector.selectedKeys()); + } + + if (selector.keys().isEmpty()) + { + synchronized (SocketAcceptorDelegate.this) + { + if (selector.keys().isEmpty() && + registerQueue.isEmpty() && + cancelQueue.isEmpty()) + { + worker = null; + try + { + selector.close(); + } + catch (IOException e) + { + ExceptionMonitor.getInstance().exceptionCaught(e); + } + finally + { + selector = null; + } + break; + } + } + } + } + catch (IOException e) + { + ExceptionMonitor.getInstance().exceptionCaught(e); + + try + { + Thread.sleep(1000); + } + catch (InterruptedException e1) + { + } + } + } + } + + private void processSessions(Set keys) throws IOException + { + Iterator it = keys.iterator(); + while (it.hasNext()) + { + SelectionKey key = (SelectionKey) it.next(); + + it.remove(); + + if (!key.isAcceptable()) + { + continue; + } + + ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); + + SocketChannel ch = ssc.accept(); + + if (ch == null) + { + continue; + } + + boolean success = false; + SocketSessionImpl session = null; + try + { + RegistrationRequest req = (RegistrationRequest) key.attachment(); + session = new SocketSessionImpl( + SocketAcceptorDelegate.this.wrapper, + (Set) sessions.get(req.address), + (SocketSessionConfig) req.config.getSessionConfig(), + ch, req.handler, + req.address); + getFilterChainBuilder().buildFilterChain(session.getFilterChain()); + req.config.getFilterChainBuilder().buildFilterChain(session.getFilterChain()); + ((SocketFilterChain) session.getFilterChain()).sessionCreated(session); + session.getManagedSessions().add(session); + session.getIoProcessor().addNew(session); + success = true; + } + catch (Throwable t) + { + ExceptionMonitor.getInstance().exceptionCaught(t); + } + finally + { + if (!success) + { + if (session != null) + { + session.getManagedSessions().remove(session); + } + ch.close(); + } + } + } + } + } + + public IoServiceConfig getDefaultConfig() + { + return defaultConfig; + } + + private void registerNew() + { + if (registerQueue.isEmpty()) + { + return; + } + + for (; ;) + { + RegistrationRequest req; + + synchronized (registerQueue) + { + req = (RegistrationRequest) registerQueue.pop(); + } + + if (req == null) + { + break; + } + + ServerSocketChannel ssc = null; + + try + { + ssc = ServerSocketChannel.open(); + ssc.configureBlocking(false); + + // Configure the server socket, + SocketAcceptorConfig cfg; + if (req.config instanceof SocketAcceptorConfig) + { + cfg = (SocketAcceptorConfig) req.config; + } + else + { + cfg = (SocketAcceptorConfig) getDefaultConfig(); + } + + ssc.socket().setReuseAddress(cfg.isReuseAddress()); + ssc.socket().setReceiveBufferSize( + ((SocketSessionConfig) cfg.getSessionConfig()).getReceiveBufferSize()); + + // and bind. + ssc.socket().bind(req.address, cfg.getBacklog()); + ssc.register(selector, SelectionKey.OP_ACCEPT, req); + + synchronized (channels) + { + channels.put(req.address, ssc); + } + sessions.put(req.address, Collections.synchronizedSet(new HashSet())); + } + catch (IOException e) + { + req.exception = e; + } + finally + { + synchronized (req) + { + req.done = true; + + req.notify(); + } + + if (ssc != null && req.exception != null) + { + try + { + ssc.close(); + } + catch (IOException e) + { + ExceptionMonitor.getInstance().exceptionCaught(e); + } + } + } + } + } + + + private void cancelKeys() + { + if (cancelQueue.isEmpty()) + { + return; + } + + for (; ;) + { + CancellationRequest request; + + synchronized (cancelQueue) + { + request = (CancellationRequest) cancelQueue.pop(); + } + + if (request == null) + { + break; + } + + sessions.remove(request.address); + ServerSocketChannel ssc; + synchronized (channels) + { + ssc = (ServerSocketChannel) channels.remove(request.address); + } + + // close the channel + try + { + if (ssc == null) + { + request.exception = new IllegalArgumentException("Address not bound: " + request.address); + } + else + { + SelectionKey key = ssc.keyFor(selector); + request.registrationRequest = (RegistrationRequest) key.attachment(); + key.cancel(); + + selector.wakeup(); // wake up again to trigger thread death + + ssc.close(); + } + } + catch (IOException e) + { + ExceptionMonitor.getInstance().exceptionCaught(e); + } + finally + { + synchronized (request) + { + request.done = true; + request.notify(); + } + } + } + } + + private static class RegistrationRequest + { + private final SocketAddress address; + private final IoHandler handler; + private final IoServiceConfig config; + private IOException exception; + private boolean done; + + private RegistrationRequest(SocketAddress address, IoHandler handler, IoServiceConfig config) + { + this.address = address; + this.handler = handler; + this.config = config; + } + } + + + private static class CancellationRequest + { + private final SocketAddress address; + private boolean done; + private RegistrationRequest registrationRequest; + private RuntimeException exception; + + private CancellationRequest(SocketAddress address) + { + this.address = address; + } + } +} diff --git a/qpid/java/common/src/org/apache/qpid/nio/SocketConnector.java b/qpid/java/common/src/org/apache/qpid/nio/SocketConnector.java new file mode 100644 index 0000000000..ce74fd0c96 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/nio/SocketConnector.java @@ -0,0 +1,32 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.nio; + +import org.apache.mina.common.support.DelegatedIoConnector; +import org.apache.mina.transport.socket.nio.support.*; + +public class SocketConnector extends DelegatedIoConnector +{ + /** + * Creates a new instance. + */ + public SocketConnector() + { + init(new SocketConnectorDelegate(this)); + } +} \ No newline at end of file diff --git a/qpid/java/common/src/org/apache/qpid/nio/SocketConnectorDelegate.java b/qpid/java/common/src/org/apache/qpid/nio/SocketConnectorDelegate.java new file mode 100644 index 0000000000..50c122d1c8 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/nio/SocketConnectorDelegate.java @@ -0,0 +1,402 @@ +/* + * @(#) $Id: SocketConnectorDelegate.java 379044 2006-02-20 07:40:37Z trustin $ + * + * Copyright 2004 The Apache Software Foundation + * + * Licensed 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.nio; + +import org.apache.mina.common.*; +import org.apache.mina.common.support.BaseIoConnector; +import org.apache.mina.common.support.DefaultConnectFuture; +import org.apache.mina.transport.socket.nio.SocketConnectorConfig; +import org.apache.mina.util.Queue; + +import java.io.IOException; +import java.net.ConnectException; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.SocketChannel; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +/** + * {@link IoConnector} for socket transport (TCP/IP). + * + * @author The Apache Directory Project (dev@directory.apache.org) + * @version $Rev: 379044 $, $Date: 2006-02-20 07:40:37 +0000 (Mon, 20 Feb 2006) $ + */ +public class SocketConnectorDelegate extends BaseIoConnector +{ + private static volatile int nextId = 0; + + private final IoConnector wrapper; + private final int id = nextId++; + private final String threadName = "SocketConnector-" + id; + private final IoServiceConfig defaultConfig = new SocketConnectorConfig(); + private Selector selector; + private final Queue connectQueue = new Queue(); + private final Set managedSessions = Collections.synchronizedSet(new HashSet()); + private Worker worker; + + /** + * Creates a new instance. + */ + public SocketConnectorDelegate(IoConnector wrapper) + { + this.wrapper = wrapper; + } + + public ConnectFuture connect(SocketAddress address, IoHandler handler, IoServiceConfig config) + { + return connect(address, null, handler, config); + } + + public ConnectFuture connect(SocketAddress address, SocketAddress localAddress, + IoHandler handler, IoServiceConfig config) + { + if (address == null) + { + throw new NullPointerException("address"); + } + if (handler == null) + { + throw new NullPointerException("handler"); + } + + if (! (address instanceof InetSocketAddress)) + { + throw new IllegalArgumentException("Unexpected address type: " + + address.getClass()); + } + + if (localAddress != null && !(localAddress instanceof InetSocketAddress)) + { + throw new IllegalArgumentException("Unexpected local address type: " + + localAddress.getClass()); + } + + if (config == null) + { + config = getDefaultConfig(); + } + + SocketChannel ch = null; + boolean success = false; + try + { + ch = SocketChannel.open(); + ch.socket().setReuseAddress(true); + if (localAddress != null) + { + ch.socket().bind(localAddress); + } + + ch.configureBlocking(false); + + if (ch.connect(address)) + { + SocketSessionImpl session = newSession(ch, handler, config); + success = true; + ConnectFuture future = new DefaultConnectFuture(); + future.setSession(session); + return future; + } + + success = true; + } + catch (IOException e) + { + return DefaultConnectFuture.newFailedFuture(e); + } + finally + { + if (!success && ch != null) + { + try + { + ch.close(); + } + catch (IOException e) + { + ExceptionMonitor.getInstance().exceptionCaught(e); + } + } + } + + ConnectionRequest request = new ConnectionRequest(ch, handler, config); + synchronized (this) + { + try + { + startupWorker(); + } + catch (IOException e) + { + try + { + ch.close(); + } + catch (IOException e2) + { + ExceptionMonitor.getInstance().exceptionCaught(e2); + } + + return DefaultConnectFuture.newFailedFuture(e); + } + synchronized (connectQueue) + { + connectQueue.push(request); + } + selector.wakeup(); + } + + return request; + } + + public IoServiceConfig getDefaultConfig() + { + return defaultConfig; + } + + private synchronized void startupWorker() throws IOException + { + if (worker == null) + { + selector = Selector.open(); + worker = new Worker(); + worker.start(); + } + } + + private void registerNew() + { + if (connectQueue.isEmpty()) + { + return; + } + + for (; ;) + { + ConnectionRequest req; + synchronized (connectQueue) + { + req = (ConnectionRequest) connectQueue.pop(); + } + + if (req == null) + { + break; + } + + SocketChannel ch = req.channel; + try + { + ch.register(selector, SelectionKey.OP_CONNECT, req); + } + catch (IOException e) + { + req.setException(e); + } + } + } + + private void processSessions(Set keys) + { + Iterator it = keys.iterator(); + + while (it.hasNext()) + { + SelectionKey key = (SelectionKey) it.next(); + + if (!key.isConnectable()) + { + continue; + } + + SocketChannel ch = (SocketChannel) key.channel(); + ConnectionRequest entry = (ConnectionRequest) key.attachment(); + + boolean success = false; + try + { + ch.finishConnect(); + SocketSessionImpl session = newSession(ch, entry.handler, entry.config); + entry.setSession(session); + success = true; + } + catch (Throwable e) + { + entry.setException(e); + } + finally + { + key.cancel(); + if (!success) + { + try + { + ch.close(); + } + catch (IOException e) + { + ExceptionMonitor.getInstance().exceptionCaught(e); + } + } + } + } + + keys.clear(); + } + + private void processTimedOutSessions(Set keys) + { + long currentTime = System.currentTimeMillis(); + Iterator it = keys.iterator(); + + while (it.hasNext()) + { + SelectionKey key = (SelectionKey) it.next(); + + if (!key.isValid()) + { + continue; + } + + ConnectionRequest entry = (ConnectionRequest) key.attachment(); + + if (currentTime >= entry.deadline) + { + entry.setException(new ConnectException()); + key.cancel(); + } + } + } + + private SocketSessionImpl newSession(SocketChannel ch, IoHandler handler, IoServiceConfig config) throws IOException + { + SocketSessionImpl session = new SocketSessionImpl( + wrapper, managedSessions, + config.getSessionConfig(), + ch, handler, ch.socket().getRemoteSocketAddress()); + try + { + getFilterChainBuilder().buildFilterChain(session.getFilterChain()); + config.getFilterChainBuilder().buildFilterChain(session.getFilterChain()); + ((SocketFilterChain) session.getFilterChain()).sessionCreated(session); + } + catch (Throwable e) + { + throw (IOException) new IOException("Failed to create a session.").initCause(e); + } + session.getManagedSessions().add(session); + session.getIoProcessor().addNew(session); + return session; + } + + private class Worker extends Thread + { + public Worker() + { + super(SocketConnectorDelegate.this.threadName); + } + + public void run() + { + for (; ;) + { + try + { + int nKeys = selector.select(1000); + + registerNew(); + + if (nKeys > 0) + { + processSessions(selector.selectedKeys()); + } + + processTimedOutSessions(selector.keys()); + + if (selector.keys().isEmpty()) + { + synchronized (SocketConnectorDelegate.this) + { + if (selector.keys().isEmpty() && + connectQueue.isEmpty()) + { + worker = null; + try + { + selector.close(); + } + catch (IOException e) + { + ExceptionMonitor.getInstance().exceptionCaught(e); + } + finally + { + selector = null; + } + break; + } + } + } + } + catch (IOException e) + { + ExceptionMonitor.getInstance().exceptionCaught(e); + + try + { + Thread.sleep(1000); + } + catch (InterruptedException e1) + { + } + } + } + } + } + + private class ConnectionRequest extends DefaultConnectFuture + { + private final SocketChannel channel; + private final long deadline; + private final IoHandler handler; + private final IoServiceConfig config; + + private ConnectionRequest(SocketChannel channel, IoHandler handler, IoServiceConfig config) + { + this.channel = channel; + long timeout; + if (config instanceof IoConnectorConfig) + { + timeout = ((IoConnectorConfig) config).getConnectTimeoutMillis(); + } + else + { + timeout = ((IoConnectorConfig) getDefaultConfig()).getConnectTimeoutMillis(); + } + this.deadline = System.currentTimeMillis() + timeout; + this.handler = handler; + this.config = config; + } + } +} \ No newline at end of file diff --git a/qpid/java/common/src/org/apache/qpid/nio/SocketFilterChain.java b/qpid/java/common/src/org/apache/qpid/nio/SocketFilterChain.java new file mode 100644 index 0000000000..07143512b5 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/nio/SocketFilterChain.java @@ -0,0 +1,48 @@ +package org.apache.qpid.nio; + +import java.io.IOException; + +import org.apache.mina.common.ByteBuffer; +import org.apache.mina.common.IoFilterChain; +import org.apache.mina.common.IoSession; +import org.apache.mina.common.IoFilter.WriteRequest; +import org.apache.mina.common.support.AbstractIoFilterChain; +import org.apache.mina.util.Queue; + +/** + * An {@link IoFilterChain} for socket transport (TCP/IP). + * + * @author The Apache Directory Project + */ +class SocketFilterChain extends AbstractIoFilterChain { + + public SocketFilterChain( IoSession parent ) + { + super( parent ); + } + + protected void doWrite( IoSession session, WriteRequest writeRequest ) + { + SocketSessionImpl s = ( SocketSessionImpl ) session; + Queue writeRequestQueue = s.getWriteRequestQueue(); + + // SocketIoProcessor.doFlush() will reset it after write is finished + // because the buffer will be passed with messageSent event. + ( ( ByteBuffer ) writeRequest.getMessage() ).mark(); + synchronized( writeRequestQueue ) + { + writeRequestQueue.push( writeRequest ); + if( writeRequestQueue.size() == 1 && session.getTrafficMask().isWritable() ) + { + // Notify SocketIoProcessor only when writeRequestQueue was empty. + s.getIoProcessor().flush( s ); + } + } + } + + protected void doClose( IoSession session ) throws IOException + { + SocketSessionImpl s = ( SocketSessionImpl ) session; + s.getIoProcessor().remove( s ); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/nio/SocketIoProcessor.java b/qpid/java/common/src/org/apache/qpid/nio/SocketIoProcessor.java new file mode 100644 index 0000000000..d20ab41b96 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/nio/SocketIoProcessor.java @@ -0,0 +1,770 @@ +/* + * @(#) $Id: SocketIoProcessor.java 372449 2006-01-26 05:24:58Z trustin $ + * + * Copyright 2004 The Apache Software Foundation + * + * Licensed 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.nio; + +import org.apache.log4j.Logger; +import org.apache.mina.common.ByteBuffer; +import org.apache.mina.common.ExceptionMonitor; +import org.apache.mina.common.IdleStatus; +import org.apache.mina.common.IoFilter.WriteRequest; +import org.apache.mina.common.WriteTimeoutException; +import org.apache.mina.util.Queue; + +import java.io.IOException; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.SocketChannel; +import java.util.Iterator; +import java.util.Set; + +/** + * Performs all I/O operations for sockets which is connected or bound. + * This class is used by MINA internally. + * + * @author The Apache Directory Project (dev@directory.apache.org) + * @version $Rev: 372449 $, $Date: 2006-01-26 05:24:58 +0000 (Thu, 26 Jan 2006) $, + */ +class SocketIoProcessor +{ + private static final Logger _logger = Logger.getLogger(SocketIoProcessor.class); + + private static final String PROCESSORS_PROPERTY = "mina.socket.processors"; + private static final String THREAD_PREFIX = "SocketIoProcessor-"; + private static final int DEFAULT_PROCESSORS = 1; + private static final int PROCESSOR_COUNT; + private static final SocketIoProcessor[] PROCESSORS; + + private static int nextId; + + static + { + PROCESSOR_COUNT = configureProcessorCount(); + PROCESSORS = createProcessors(); + } + + /** + * Returns the {@link SocketIoProcessor} to be used for a newly + * created session + * + * @return The processor to be employed + */ + static synchronized SocketIoProcessor getInstance() + { + SocketIoProcessor processor = PROCESSORS[nextId ++]; + nextId %= PROCESSOR_COUNT; + return processor; + } + + private final String threadName; + private Selector selector; + + private final Queue newSessions = new Queue(); + private final Queue removingSessions = new Queue(); + private final Queue flushingSessions = new Queue(); + private final Queue trafficControllingSessions = new Queue(); + + private Worker worker; + private long lastIdleCheckTime = System.currentTimeMillis(); + + private SocketIoProcessor(String threadName) + { + this.threadName = threadName; + } + + void addNew(SocketSessionImpl session) throws IOException + { + synchronized (this) + { + synchronized (newSessions) + { + newSessions.push(session); + } + startupWorker(); + } + + selector.wakeup(); + } + + void remove(SocketSessionImpl session) throws IOException + { + scheduleRemove(session); + startupWorker(); + selector.wakeup(); + } + + private synchronized void startupWorker() throws IOException + { + if (worker == null) + { + selector = Selector.open(); + worker = new Worker(); + worker.start(); + } + } + + void flush(SocketSessionImpl session) + { + scheduleFlush(session); + Selector selector = this.selector; + if (selector != null) + { + selector.wakeup(); + } + } + + void updateTrafficMask(SocketSessionImpl session) + { + scheduleTrafficControl(session); + Selector selector = this.selector; + if (selector != null) + { + selector.wakeup(); + } + } + + private void scheduleRemove(SocketSessionImpl session) + { + synchronized (removingSessions) + { + removingSessions.push(session); + } + } + + private void scheduleFlush(SocketSessionImpl session) + { + synchronized (flushingSessions) + { + flushingSessions.push(session); + } + } + + private void scheduleTrafficControl(SocketSessionImpl session) + { + synchronized (trafficControllingSessions) + { + trafficControllingSessions.push(session); + } + } + + private void doAddNew() + { + if (newSessions.isEmpty()) + { + return; + } + + SocketSessionImpl session; + + for (; ;) + { + synchronized (newSessions) + { + session = (SocketSessionImpl) newSessions.pop(); + } + + if (session == null) + { + break; + } + + SocketChannel ch = session.getChannel(); + boolean registered; + + try + { + ch.configureBlocking(false); + session.setSelectionKey(ch.register(selector, + SelectionKey.OP_READ, + session)); + registered = true; + } + catch (IOException e) + { + session.getManagedSessions().remove(session); + registered = false; + ((SocketFilterChain) session.getFilterChain()).exceptionCaught(session, e); + } + + if (registered) + { + ((SocketFilterChain) session.getFilterChain()).sessionOpened(session); + } + } + } + + private void doRemove() + { + if (removingSessions.isEmpty()) + { + return; + } + + for (; ;) + { + SocketSessionImpl session; + + synchronized (removingSessions) + { + session = (SocketSessionImpl) removingSessions.pop(); + } + + if (session == null) + { + break; + } + + SocketChannel ch = session.getChannel(); + SelectionKey key = session.getSelectionKey(); + // Retry later if session is not yet fully initialized. + // (In case that Session.close() is called before addSession() is processed) + if (key == null) + { + scheduleRemove(session); + break; + } + // skip if channel is already closed + if (!key.isValid()) + { + continue; + } + + try + { + key.cancel(); + ch.close(); + } + catch (IOException e) + { + ((SocketFilterChain) session.getFilterChain()).exceptionCaught(session, e); + } + finally + { + releaseWriteBuffers(session); + session.getManagedSessions().remove(session); + + ((SocketFilterChain) session.getFilterChain()).sessionClosed(session); + session.getCloseFuture().setClosed(); + } + } + } + + private void process(Set selectedKeys) + { + Iterator it = selectedKeys.iterator(); + + while (it.hasNext()) + { + SelectionKey key = (SelectionKey) it.next(); + SocketSessionImpl session = (SocketSessionImpl) key.attachment(); + + if (key.isReadable() && session.getTrafficMask().isReadable()) + { + read(session); + } + + if (key.isWritable() && session.getTrafficMask().isWritable()) + { + scheduleFlush(session); + } + } + + selectedKeys.clear(); + } + + private void read(SocketSessionImpl session) + { + ByteBuffer buf = ByteBuffer.allocate(session.getReadBufferSize()); + SocketChannel ch = session.getChannel(); + + try + { + int readBytes = 0; + int ret; + + buf.clear(); + + try + { + while ((ret = ch.read(buf.buf())) > 0) + { + readBytes += ret; + } + } + finally + { + buf.flip(); + } + + session.increaseReadBytes(readBytes); + + if (readBytes > 0) + { + /*ByteBuffer newBuf = ByteBuffer.allocate(readBytes); + newBuf.put(buf); + newBuf.flip();*/ + //((SocketFilterChain) session.getFilterChain()).messageReceived(session, newBuf); + ((SocketFilterChain) session.getFilterChain()).messageReceived(session, buf); + } + if (ret < 0) + { + scheduleRemove(session); + } + } + catch (Throwable e) + { + if (e instanceof IOException) + { + scheduleRemove(session); + } + buf.release(); + ((SocketFilterChain) session.getFilterChain()).exceptionCaught(session, e); + } + /*finally + { + buf.release(); + } */ + } + + private void notifyIdleness() + { + // process idle sessions + long currentTime = System.currentTimeMillis(); + if ((currentTime - lastIdleCheckTime) >= 1000) + { + lastIdleCheckTime = currentTime; + Set keys = selector.keys(); + if (keys != null) + { + for (Iterator it = keys.iterator(); it.hasNext();) + { + SelectionKey key = (SelectionKey) it.next(); + SocketSessionImpl session = (SocketSessionImpl) key.attachment(); + notifyIdleness(session, currentTime); + } + } + } + } + + private void notifyIdleness(SocketSessionImpl session, long currentTime) + { + notifyIdleness0( + session, currentTime, + session.getIdleTimeInMillis(IdleStatus.BOTH_IDLE), + IdleStatus.BOTH_IDLE, + Math.max(session.getLastIoTime(), session.getLastIdleTime(IdleStatus.BOTH_IDLE))); + notifyIdleness0( + session, currentTime, + session.getIdleTimeInMillis(IdleStatus.READER_IDLE), + IdleStatus.READER_IDLE, + Math.max(session.getLastReadTime(), session.getLastIdleTime(IdleStatus.READER_IDLE))); + notifyIdleness0( + session, currentTime, + session.getIdleTimeInMillis(IdleStatus.WRITER_IDLE), + IdleStatus.WRITER_IDLE, + Math.max(session.getLastWriteTime(), session.getLastIdleTime(IdleStatus.WRITER_IDLE))); + + notifyWriteTimeout(session, currentTime, session + .getWriteTimeoutInMillis(), session.getLastWriteTime()); + } + + private void notifyIdleness0(SocketSessionImpl session, long currentTime, + long idleTime, IdleStatus status, + long lastIoTime) + { + if (idleTime > 0 && lastIoTime != 0 + && (currentTime - lastIoTime) >= idleTime) + { + session.increaseIdleCount(status); + ((SocketFilterChain) session.getFilterChain()).sessionIdle(session, status); + } + } + + private void notifyWriteTimeout(SocketSessionImpl session, + long currentTime, + long writeTimeout, long lastIoTime) + { + SelectionKey key = session.getSelectionKey(); + if (writeTimeout > 0 + && (currentTime - lastIoTime) >= writeTimeout + && key != null && key.isValid() + && (key.interestOps() & SelectionKey.OP_WRITE) != 0) + { + ((SocketFilterChain) session.getFilterChain()).exceptionCaught(session, new WriteTimeoutException()); + } + } + + private void doFlush() + { + if (flushingSessions.size() == 0) + { + return; + } + + for (; ;) + { + SocketSessionImpl session; + + synchronized (flushingSessions) + { + session = (SocketSessionImpl) flushingSessions.pop(); + } + + if (session == null) + { + break; + } + + if (!session.isConnected()) + { + releaseWriteBuffers(session); + continue; + } + + SelectionKey key = session.getSelectionKey(); + // Retry later if session is not yet fully initialized. + // (In case that Session.write() is called before addSession() is processed) + if (key == null) + { + scheduleFlush(session); + break; + } + // skip if channel is already closed + if (!key.isValid()) + { + continue; + } + + try + { + doFlush(session); + } + catch (IOException e) + { + scheduleRemove(session); + ((SocketFilterChain) session.getFilterChain()).exceptionCaught(session, e); + } + } + } + + private void releaseWriteBuffers(SocketSessionImpl session) + { + Queue writeRequestQueue = session.getWriteRequestQueue(); + WriteRequest req; + + while ((req = (WriteRequest) writeRequestQueue.pop()) != null) + { + try + { + ((ByteBuffer) req.getMessage()).release(); + } + catch (IllegalStateException e) + { + ((SocketFilterChain) session.getFilterChain()).exceptionCaught(session, e); + } + finally + { + req.getFuture().setWritten(false); + } + } + } + + private void doFlush(SocketSessionImpl session) throws IOException + { + // Clear OP_WRITE + SelectionKey key = session.getSelectionKey(); + key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE)); + + SocketChannel ch = session.getChannel(); + Queue writeRequestQueue = session.getWriteRequestQueue(); + + WriteRequest req; + for (; ;) + { + synchronized (writeRequestQueue) + { + req = (WriteRequest) writeRequestQueue.first(); + } + + if (req == null) + { + break; + } + + ByteBuffer buf = (ByteBuffer) req.getMessage(); + if (buf.remaining() == 0) + { + synchronized (writeRequestQueue) + { + writeRequestQueue.pop(); + } + + session.increaseWrittenWriteRequests(); + buf.reset(); + ((SocketFilterChain) session.getFilterChain()).messageSent(session, req); + continue; + } + + int writtenBytes = ch.write(buf.buf()); + if (writtenBytes > 0) + { + session.increaseWrittenBytes(writtenBytes); + } + + if (buf.hasRemaining()) + { + //_logger.info("Kernel buf full"); + // Kernel buffer is full + key.interestOps(key.interestOps() | SelectionKey.OP_WRITE); + selector.wakeup(); + break; + } + } + } + + private void doUpdateTrafficMask() + { + if (trafficControllingSessions.isEmpty()) + { + return; + } + + for (; ;) + { + SocketSessionImpl session; + + synchronized (trafficControllingSessions) + { + session = (SocketSessionImpl) trafficControllingSessions.pop(); + } + + if (session == null) + { + break; + } + + SelectionKey key = session.getSelectionKey(); + // Retry later if session is not yet fully initialized. + // (In case that Session.suspend??() or session.resume??() is + // called before addSession() is processed) + if (key == null) + { + scheduleTrafficControl(session); + break; + } + // skip if channel is already closed + if (!key.isValid()) + { + continue; + } + + // The normal is OP_READ and, if there are write requests in the + // session's write queue, set OP_WRITE to trigger flushing. + int ops = SelectionKey.OP_READ; + Queue writeRequestQueue = session.getWriteRequestQueue(); + synchronized (writeRequestQueue) + { + if (!writeRequestQueue.isEmpty()) + { + ops |= SelectionKey.OP_WRITE; + } + } + + // Now mask the preferred ops with the mask of the current session + int mask = session.getTrafficMask().getInterestOps(); + key.interestOps(ops & mask); + } + } + + /** + * Configures the number of processors employed. + * We first check for a system property "mina.IoProcessors". If this + * property is present and can be interpreted as an integer value greater + * or equal to 1, this value is used as the number of processors. + * Otherwise a default of 1 processor is employed. + * + * @return The nubmer of processors to employ + */ + private static int configureProcessorCount() + { + int processors = DEFAULT_PROCESSORS; + String processorProperty = System.getProperty(PROCESSORS_PROPERTY); + if (processorProperty != null) + { + try + { + processors = Integer.parseInt(processorProperty); + } + catch (NumberFormatException e) + { + ExceptionMonitor.getInstance().exceptionCaught(e); + } + processors = Math.max(processors, 1); + + System.setProperty(PROCESSORS_PROPERTY, String.valueOf(processors)); + } + + return processors; + } + + private static SocketIoProcessor[] createProcessors() + { + SocketIoProcessor[] processors = new SocketIoProcessor[ PROCESSOR_COUNT ]; + for (int i = 0; i < PROCESSOR_COUNT; i ++) + { + processors[i] = new SocketIoProcessor(THREAD_PREFIX + i); + } + return processors; + } + + private class WorkerFlusher implements Runnable + { + private volatile boolean _shutdown = false; + + private volatile boolean _sleep = false; + + private final Object _lock = new Object(); + + public void run() + { + while (!_shutdown) + { + doFlush(); + try + { + sleep(); + } + catch (InterruptedException e) + { + // IGNORE + } + } + _logger.info("Flusher shutting down"); + } + + private void sleep() throws InterruptedException + { + synchronized (_lock) + { + while (_sleep && !_shutdown) + { + _logger.debug("Flusher going to sleep"); + _lock.wait(); + } + _sleep = true; + } + } + + void wakeup() + { + synchronized (_lock) + { + if (_sleep) + { + _logger.debug("Waking up flusher"); + _sleep = false; + _lock.notify(); + } + } + } + + void shutdown() + { + _shutdown = true; + wakeup(); + } + } + + private class Worker extends Thread + { + private WorkerFlusher _flusher; + + public Worker() + { + super(SocketIoProcessor.this.threadName); + _flusher = new WorkerFlusher(); + new Thread(_flusher, SocketIoProcessor.this.threadName + "Flusher").start(); + } + + public void run() + { + for (; ;) + { + try + { + int nKeys = selector.select(1000); + doAddNew(); + doUpdateTrafficMask(); + + if (nKeys > 0) + { + process(selector.selectedKeys()); + } + + //doFlush(); + // in case the flusher has gone to sleep we wake it up + if (flushingSessions.size() > 0) + { + _flusher.wakeup(); + } + doRemove(); + notifyIdleness(); + + if (selector.keys().isEmpty()) + { + synchronized (SocketIoProcessor.this) + { + if (selector.keys().isEmpty() && + newSessions.isEmpty()) + { + worker = null; + _flusher.shutdown(); + try + { + selector.close(); + } + catch (IOException e) + { + ExceptionMonitor.getInstance().exceptionCaught(e); + } + finally + { + selector = null; + } + break; + } + } + } + } + catch (Throwable t) + { + ExceptionMonitor.getInstance().exceptionCaught(t); + + try + { + Thread.sleep(1000); + } + catch (InterruptedException e1) + { + } + } + } + } + } + +} diff --git a/qpid/java/common/src/org/apache/qpid/nio/SocketSessionImpl.java b/qpid/java/common/src/org/apache/qpid/nio/SocketSessionImpl.java new file mode 100644 index 0000000000..f7c74f7a14 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/nio/SocketSessionImpl.java @@ -0,0 +1,404 @@ +/* + * @(#) $Id: SocketSessionImpl.java 385247 2006-03-12 05:06:11Z trustin $ + * + * Copyright 2004 The Apache Software Foundation + * + * Licensed 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.nio; + +import org.apache.mina.common.IoFilter.WriteRequest; +import org.apache.mina.common.*; +import org.apache.mina.common.support.BaseIoSession; +import org.apache.mina.common.support.BaseIoSessionConfig; +import org.apache.mina.transport.socket.nio.SocketSessionConfig; +import org.apache.mina.util.Queue; + +import java.net.SocketAddress; +import java.net.SocketException; +import java.nio.channels.SelectionKey; +import java.nio.channels.SocketChannel; +import java.util.Set; + +/** + * An {@link IoSession} for socket transport (TCP/IP). + * + * @author The Apache Directory Project (dev@directory.apache.org) + * @version $Rev: 385247 $, $Date: 2006-03-12 05:06:11 +0000 (Sun, 12 Mar 2006) $ + */ +class SocketSessionImpl extends BaseIoSession +{ + private final IoService manager; + private final SocketSessionConfig config = new SocketSessionConfigImpl(); + private final SocketIoProcessor ioProcessor; + private final SocketFilterChain filterChain; + private final SocketChannel ch; + private final Queue writeRequestQueue; + private final IoHandler handler; + private final SocketAddress remoteAddress; + private final SocketAddress localAddress; + private final SocketAddress serviceAddress; + private final Set managedSessions; + private SelectionKey key; + private int readBufferSize; + + /** + * Creates a new instance. + */ + public SocketSessionImpl( + IoService manager, Set managedSessions, + IoSessionConfig config, + SocketChannel ch, IoHandler defaultHandler, + SocketAddress serviceAddress ) + { + this.manager = manager; + this.managedSessions = managedSessions; + this.ioProcessor = SocketIoProcessor.getInstance(); + this.filterChain = new SocketFilterChain( this ); + this.ch = ch; + this.writeRequestQueue = new Queue(); + this.handler = defaultHandler; + this.remoteAddress = ch.socket().getRemoteSocketAddress(); + this.localAddress = ch.socket().getLocalSocketAddress(); + this.serviceAddress = serviceAddress; + + // Apply the initial session settings + if( config instanceof SocketSessionConfig ) + { + SocketSessionConfig cfg = ( SocketSessionConfig ) config; + this.config.setKeepAlive( cfg.isKeepAlive() ); + this.config.setOobInline( cfg.isOobInline() ); + this.config.setReceiveBufferSize( cfg.getReceiveBufferSize() ); + this.readBufferSize = cfg.getReceiveBufferSize(); + this.config.setReuseAddress( cfg.isReuseAddress() ); + this.config.setSendBufferSize( cfg.getSendBufferSize() ); + this.config.setSoLinger( cfg.getSoLinger() ); + this.config.setTcpNoDelay( cfg.isTcpNoDelay() ); + + if( this.config.getTrafficClass() != cfg.getTrafficClass() ) + { + this.config.setTrafficClass( cfg.getTrafficClass() ); + } + } + } + + public IoService getService() + { + return manager; + } + + public IoSessionConfig getConfig() + { + return config; + } + + SocketIoProcessor getIoProcessor() + { + return ioProcessor; + } + + public IoFilterChain getFilterChain() + { + return filterChain; + } + + SocketChannel getChannel() + { + return ch; + } + + Set getManagedSessions() + { + return managedSessions; + } + + SelectionKey getSelectionKey() + { + return key; + } + + void setSelectionKey( SelectionKey key ) + { + this.key = key; + } + + public IoHandler getHandler() + { + return handler; + } + + protected void close0() + { + filterChain.filterClose( this ); + } + + Queue getWriteRequestQueue() + { + return writeRequestQueue; + } + + public int getScheduledWriteRequests() + { + synchronized( writeRequestQueue ) + { + return writeRequestQueue.size(); + } + } + + public int getScheduledWriteBytes() + { + synchronized( writeRequestQueue ) + { + return writeRequestQueue.byteSize(); + } + } + + protected void write0( WriteRequest writeRequest ) + { + filterChain.filterWrite( this, writeRequest ); + } + + public TransportType getTransportType() + { + return TransportType.SOCKET; + } + + public SocketAddress getRemoteAddress() + { + return remoteAddress; + } + + public SocketAddress getLocalAddress() + { + return localAddress; + } + + public SocketAddress getServiceAddress() + { + return serviceAddress; + } + + protected void updateTrafficMask() + { + this.ioProcessor.updateTrafficMask( this ); + } + + int getReadBufferSize() + { + return readBufferSize; + } + + private class SocketSessionConfigImpl extends BaseIoSessionConfig implements SocketSessionConfig + { + public boolean isKeepAlive() + { + try + { + return ch.socket().getKeepAlive(); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public void setKeepAlive( boolean on ) + { + try + { + ch.socket().setKeepAlive( on ); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public boolean isOobInline() + { + try + { + return ch.socket().getOOBInline(); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public void setOobInline( boolean on ) + { + try + { + ch.socket().setOOBInline( on ); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public boolean isReuseAddress() + { + try + { + return ch.socket().getReuseAddress(); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public void setReuseAddress( boolean on ) + { + try + { + ch.socket().setReuseAddress( on ); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public int getSoLinger() + { + try + { + return ch.socket().getSoLinger(); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public void setSoLinger( int linger ) + { + try + { + if( linger < 0 ) + { + ch.socket().setSoLinger( false, 0 ); + } + else + { + ch.socket().setSoLinger( true, linger ); + } + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public boolean isTcpNoDelay() + { + try + { + return ch.socket().getTcpNoDelay(); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public void setTcpNoDelay( boolean on ) + { + try + { + ch.socket().setTcpNoDelay( on ); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public int getTrafficClass() + { + try + { + return ch.socket().getTrafficClass(); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public void setTrafficClass( int tc ) + { + try + { + ch.socket().setTrafficClass( tc ); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public int getSendBufferSize() + { + try + { + return ch.socket().getSendBufferSize(); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public void setSendBufferSize( int size ) + { + try + { + ch.socket().setSendBufferSize( size ); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public int getReceiveBufferSize() + { + try + { + return ch.socket().getReceiveBufferSize(); + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + + public void setReceiveBufferSize( int size ) + { + try + { + ch.socket().setReceiveBufferSize( size ); + SocketSessionImpl.this.readBufferSize = size; + } + catch( SocketException e ) + { + throw new RuntimeIOException( e ); + } + } + } +} diff --git a/qpid/java/common/src/org/apache/qpid/pool/Event.java b/qpid/java/common/src/org/apache/qpid/pool/Event.java new file mode 100644 index 0000000000..6bf86ffc2e --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/pool/Event.java @@ -0,0 +1,111 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.pool; + +import org.apache.log4j.Logger; +import org.apache.mina.common.IoFilter; +import org.apache.mina.common.IoSession; +import org.apache.mina.common.IdleStatus; + +/** + * Represents an operation on IoFilter. + */ +enum EventType +{ + OPENED, CLOSED, READ, WRITE, WRITTEN, RECEIVED, SENT, IDLE, EXCEPTION +} + +class Event +{ + private static final Logger _log = Logger.getLogger(Event.class); + + private final EventType type; + private final IoFilter.NextFilter nextFilter; + private final Object data; + + public Event(IoFilter.NextFilter nextFilter, EventType type, Object data) + { + this.type = type; + this.nextFilter = nextFilter; + this.data = data; + if (type == EventType.EXCEPTION) + { + _log.error("Exception event constructed: " + data, (Exception) data); + } + } + + public Object getData() + { + return data; + } + + + public IoFilter.NextFilter getNextFilter() + { + return nextFilter; + } + + + public EventType getType() + { + return type; + } + + void process(IoSession session) + { + if (_log.isDebugEnabled()) + { + _log.debug("Processing " + this); + } + if (type == EventType.RECEIVED) + { + nextFilter.messageReceived(session, data); + //ByteBufferUtil.releaseIfPossible( data ); + } + else if (type == EventType.SENT) + { + nextFilter.messageSent(session, data); + //ByteBufferUtil.releaseIfPossible( data ); + } + else if (type == EventType.EXCEPTION) + { + nextFilter.exceptionCaught(session, (Throwable) data); + } + else if (type == EventType.IDLE) + { + nextFilter.sessionIdle(session, (IdleStatus) data); + } + else if (type == EventType.OPENED) + { + nextFilter.sessionOpened(session); + } + else if (type == EventType.WRITE) + { + nextFilter.filterWrite(session, (IoFilter.WriteRequest) data); + } + else if (type == EventType.CLOSED) + { + nextFilter.sessionClosed(session); + } + } + + public String toString() + { + return "Event: type " + type + ", data: " + data; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/pool/Job.java b/qpid/java/common/src/org/apache/qpid/pool/Job.java new file mode 100644 index 0000000000..45a115bcd3 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/pool/Job.java @@ -0,0 +1,110 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.pool; + +import org.apache.mina.common.IoSession; + +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Holds events for a session that will be processed asynchronously by + * the thread pool in PoolingFilter. + */ +class Job implements Runnable +{ + private final int _maxEvents; + private final IoSession _session; + private final java.util.Queue _eventQueue = new ConcurrentLinkedQueue(); + private final AtomicBoolean _active = new AtomicBoolean(); + private final AtomicInteger _refCount = new AtomicInteger(); + private final JobCompletionHandler _completionHandler; + + Job(IoSession session, JobCompletionHandler completionHandler, int maxEvents) + { + _session = session; + _completionHandler = completionHandler; + _maxEvents = maxEvents; + } + + void acquire() + { + _refCount.incrementAndGet(); + } + + void release() + { + _refCount.decrementAndGet(); + } + + boolean isReferenced() + { + return _refCount.get() > 0; + } + + void add(Event evt) + { + _eventQueue.add(evt); + } + + void processAll() + { + //limit the number of events processed in one run + for (int i = 0; i < _maxEvents; i++) + { + Event e = _eventQueue.poll(); + if (e == null) + { + break; + } + else + { + e.process(_session); + } + } + } + + boolean isComplete() + { + return _eventQueue.peek() == null; + } + + boolean activate() + { + return _active.compareAndSet(false, true); + } + + void deactivate() + { + _active.set(false); + } + + public void run() + { + processAll(); + deactivate(); + _completionHandler.completed(_session, this); + } + + + static interface JobCompletionHandler + { + public void completed(IoSession session, Job job); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/pool/PoolingFilter.java b/qpid/java/common/src/org/apache/qpid/pool/PoolingFilter.java new file mode 100644 index 0000000000..ecb0bd5048 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/pool/PoolingFilter.java @@ -0,0 +1,183 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.pool; + +import org.apache.log4j.Logger; +import org.apache.mina.common.IdleStatus; +import org.apache.mina.common.IoFilterAdapter; +import org.apache.mina.common.IoSession; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionHandler +{ + private static final Logger _logger = Logger.getLogger(PoolingFilter.class); + public static final Set READ_EVENTS = new HashSet(Arrays.asList(EventType.RECEIVED)); + public static final Set WRITE_EVENTS = new HashSet(Arrays.asList(EventType.WRITE)); + + private final ConcurrentMap _jobs = new ConcurrentHashMap(); + private final ReferenceCountingExecutorService _poolReference; + private final Set _asyncTypes; + + private final String _name; + private final int _maxEvents = Integer.getInteger("amqj.server.read_write_pool.max_events", 10); + + public PoolingFilter(ReferenceCountingExecutorService refCountingPool, Set asyncTypes, String name) + { + _poolReference = refCountingPool; + _asyncTypes = asyncTypes; + _name = name; + } + + private void fireEvent(IoSession session, Event event) + { + if (_asyncTypes.contains(event.getType())) + { + Job job = getJobForSession(session); + job.acquire(); //prevents this job being removed from _jobs + job.add(event); + if (job.activate()) + { + _poolReference.getPool().execute(job); + } + } + else + { + event.process(session); + } + } + + private Job getJobForSession(IoSession session) + { + Job job = _jobs.get(session); + return job == null ? createJobForSession(session) : job; + } + + private Job createJobForSession(IoSession session) + { + return addJobForSession(session, new Job(session, this, _maxEvents)); + } + + private Job addJobForSession(IoSession session, Job job) + { + //atomic so ensures all threads agree on the same job + Job existing = _jobs.putIfAbsent(session, job); + return existing == null ? job : existing; + } + + //Job.JobCompletionHandler + public void completed(IoSession session, Job job) + { + if (job.isComplete()) + { + job.release(); + if (!job.isReferenced()) + { + _jobs.remove(session); + } + } + else + { + if (job.activate()) + { + _poolReference.getPool().execute(job); + } + } + } + + //IoFilter methods that are processed by threads on the pool + + public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception + { + fireEvent(session, new Event(nextFilter, EventType.OPENED, null)); + } + + public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception + { + fireEvent(session, new Event(nextFilter, EventType.CLOSED, null)); + } + + public void sessionIdle(NextFilter nextFilter, IoSession session, + IdleStatus status) throws Exception + { + fireEvent(session, new Event(nextFilter, EventType.IDLE, status)); + } + + public void exceptionCaught(NextFilter nextFilter, IoSession session, + Throwable cause) throws Exception + { + fireEvent(session, new Event(nextFilter, EventType.EXCEPTION, cause)); + } + + public void messageReceived(NextFilter nextFilter, IoSession session, + Object message) throws Exception + { + //ByteBufferUtil.acquireIfPossible( message ); + fireEvent(session, new Event(nextFilter, EventType.RECEIVED, message)); + } + + public void messageSent(NextFilter nextFilter, IoSession session, + Object message) throws Exception + { + //ByteBufferUtil.acquireIfPossible( message ); + fireEvent(session, new Event(nextFilter, EventType.SENT, message)); + } + + public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception + { + fireEvent(session, new Event(nextFilter, EventType.WRITE, writeRequest)); + } + + //IoFilter methods that are processed on current thread (NOT on pooled thread) + + public void filterClose(NextFilter nextFilter, IoSession session) throws Exception + { + nextFilter.filterClose(session); + } + + public void sessionCreated(NextFilter nextFilter, IoSession session) + { + nextFilter.sessionCreated(session); + } + + public String toString() + { + return _name; + } + + // LifeCycle methods + + public void init() + { + _logger.info("Init called on PoolingFilter " + toString()); + // called when the filter is initialised in the chain. If the reference count is + // zero this acquire will initialise the pool + _poolReference.acquireExecutorService(); + } + + public void destroy() + { + _logger.info("Destroy called on PoolingFilter " + toString()); + // when the reference count gets to zero we release the executor service + _poolReference.releaseExecutorService(); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/pool/ReadWriteThreadModel.java b/qpid/java/common/src/org/apache/qpid/pool/ReadWriteThreadModel.java new file mode 100644 index 0000000000..5de2bf8d0e --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/pool/ReadWriteThreadModel.java @@ -0,0 +1,37 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.pool; + +import org.apache.mina.common.IoFilterChain; +import org.apache.mina.common.ReferenceCountingIoFilter; +import org.apache.mina.common.ThreadModel; + +public class ReadWriteThreadModel implements ThreadModel +{ + public void buildFilterChain(IoFilterChain chain) throws Exception + { + ReferenceCountingExecutorService executor = ReferenceCountingExecutorService.getInstance(); + PoolingFilter asyncRead = new PoolingFilter(executor, PoolingFilter.READ_EVENTS, + "AsynchronousReadFilter"); + PoolingFilter asyncWrite = new PoolingFilter(executor, PoolingFilter.WRITE_EVENTS, + "AsynchronousWriteFilter"); + + chain.addFirst("AsynchronousReadFilter", new ReferenceCountingIoFilter(asyncRead)); + chain.addLast("AsynchronousWriteFilter", new ReferenceCountingIoFilter(asyncWrite)); + } +} diff --git a/qpid/java/common/src/org/apache/qpid/pool/ReferenceCountingExecutorService.java b/qpid/java/common/src/org/apache/qpid/pool/ReferenceCountingExecutorService.java new file mode 100644 index 0000000000..f048a12b90 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/pool/ReferenceCountingExecutorService.java @@ -0,0 +1,95 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.pool; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * We share the executor service among several PoolingFilters. This class reference counts + * how many filter chains are using the executor service and destroys the service, thus + * freeing up its threads, when the count reaches zero. It recreates the service when + * the count is incremented. + * + * This is particularly important on the client where failing to destroy the executor + * service prevents the JVM from shutting down due to the existence of non-daemon threads. + * + */ +public class ReferenceCountingExecutorService +{ + private static final int MINIMUM_POOL_SIZE = 4; + private static final int NUM_CPUS = Runtime.getRuntime().availableProcessors(); + private static final int DEFAULT_POOL_SIZE = Math.max(NUM_CPUS, MINIMUM_POOL_SIZE); + + /** + * We need to be able to check the current reference count and if necessary + * create the executor service atomically. + */ + private static final ReferenceCountingExecutorService _instance = new ReferenceCountingExecutorService(); + + private final Object _lock = new Object(); + + private ExecutorService _pool; + + private int _refCount = 0; + + private int _poolSize = Integer.getInteger("amqj.read_write_pool_size", DEFAULT_POOL_SIZE); + + public static ReferenceCountingExecutorService getInstance() + { + return _instance; + } + + private ReferenceCountingExecutorService() + { + } + + ExecutorService acquireExecutorService() + { + synchronized (_lock) + { + if (_refCount++ == 0) + { + _pool = Executors.newFixedThreadPool(_poolSize); + } + return _pool; + } + } + + void releaseExecutorService() + { + synchronized (_lock) + { + if (--_refCount == 0) + { + _pool.shutdownNow(); + } + } + } + + /** + * The filters that use the executor service should call this method to get access + * to the service. Note that this method does not alter the reference count. + * + * @return the underlying executor service + */ + public ExecutorService getPool() + { + return _pool; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/protocol/AMQConstant.java b/qpid/java/common/src/org/apache/qpid/protocol/AMQConstant.java new file mode 100644 index 0000000000..0716104688 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/protocol/AMQConstant.java @@ -0,0 +1,105 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.protocol; + +import java.util.Map; +import java.util.HashMap; + +public final class AMQConstant +{ + private int _code; + + private String _name; + + private static Map _codeMap = new HashMap(); + + private AMQConstant(int code, String name, boolean map) + { + _code = code; + _name = name; + if (map) + { + _codeMap.put(new Integer(code), this); + } + } + + public String toString() + { + return _code + ": " + _name; + } + + public int getCode() + { + return _code; + } + + public String getName() + { + return _name; + } + + public static final AMQConstant FRAME_MIN_SIZE = new AMQConstant(4096, "frame min size", true); + + public static final AMQConstant FRAME_END = new AMQConstant(206, "frame end", true); + + public static final AMQConstant REPLY_SUCCESS = new AMQConstant(200, "reply success", true); + + public static final AMQConstant NOT_DELIVERED = new AMQConstant(310, "not delivered", true); + + public static final AMQConstant MESSAGE_TOO_LARGE = new AMQConstant(311, "message too large", true); + + public static final AMQConstant NO_ROUTE = new AMQConstant(312, "no route", true); + + public static final AMQConstant NO_CONSUMERS = new AMQConstant(313, "no consumers", true); + + public static final AMQConstant CONTEXT_IN_USE = new AMQConstant(320, "context in use", true); + + public static final AMQConstant CONTEXT_UNKNOWN = new AMQConstant(321, "context unknown", true); + + public static final AMQConstant INVALID_PATH = new AMQConstant(402, "invalid path", true); + + public static final AMQConstant ACCESS_REFUSED = new AMQConstant(403, "access refused", true); + + public static final AMQConstant NOT_FOUND = new AMQConstant(404, "not found", true); + + public static final AMQConstant FRAME_ERROR = new AMQConstant(501, "frame error", true); + + public static final AMQConstant SYNTAX_ERROR = new AMQConstant(502, "syntax error", true); + + public static final AMQConstant COMMAND_INVALID = new AMQConstant(503, "command invalid", true); + + public static final AMQConstant CHANNEL_ERROR = new AMQConstant(504, "channel error", true); + + public static final AMQConstant RESOURCE_ERROR = new AMQConstant(506, "resource error", true); + + public static final AMQConstant NOT_ALLOWED = new AMQConstant(507, "not allowed", true); + + public static final AMQConstant NOT_IMPLEMENTED = new AMQConstant(540, "not implemented", true); + + public static final AMQConstant INTERNAL_ERROR = new AMQConstant(541, "internal error", true); + + public static AMQConstant getConstant(int code) + { + AMQConstant c = (AMQConstant) _codeMap.get(new Integer(code)); + if (c == null) + { + c = new AMQConstant(code, "unknown code", false); + } + return c; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/ssl/BogusSSLContextFactory.java b/qpid/java/common/src/org/apache/qpid/ssl/BogusSSLContextFactory.java new file mode 100644 index 0000000000..c066fd0370 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/ssl/BogusSSLContextFactory.java @@ -0,0 +1,156 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.ssl; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.io.InputStream; +import java.security.GeneralSecurityException; +import java.security.KeyStore; + +/** + * Factory to create a bogus SSLContext. This means that it is easy to test SSL but this + * cannot be used in a production environment. + *

+ * This is based on the sample that comes with MINA, written by Trustin Lee + */ +public class BogusSSLContextFactory +{ + /** + * Protocol to use. + */ + private static final String PROTOCOL = "TLS"; + + /** + * Bougus Server certificate keystore file name. + */ + private static final String BOGUS_KEYSTORE = "qpid.cert"; + + // NOTE: The keystore was generated using keytool: + // keytool -genkey -alias qpid -keysize 512 -validity 3650 + // -keyalg RSA -dname "CN=amqp.org" -keypass qpidpw + // -storepass qpidpw -keystore qpid.cert + + private static final char[] BOGUS_KEYSTORE_PASSWORD = {'q', 'p', 'i', 'd', 'p', 'w'}; + + private static SSLContext serverInstance = null; + + private static SSLContext clientInstance = null; + + /** + * Get SSLContext singleton. + * + * @return SSLContext + * @throws java.security.GeneralSecurityException + */ + public static SSLContext getInstance(boolean server) + throws GeneralSecurityException + { + SSLContext retInstance; + if (server) + { + // FIXME: looks like double-checking locking + if (serverInstance == null) + { + synchronized (BogusSSLContextFactory.class) + { + if (serverInstance == null) + { + try + { + serverInstance = createBougusServerSSLContext(); + } + catch (Exception ioe) + { + throw new GeneralSecurityException( + "Can't create Server SSLContext:" + ioe); + } + } + } + } + retInstance = serverInstance; + } + else + { + // FIXME: looks like double-checking locking + if (clientInstance == null) + { + synchronized (BogusSSLContextFactory.class) + { + if (clientInstance == null) + { + clientInstance = createBougusClientSSLContext(); + } + } + } + retInstance = clientInstance; + } + return retInstance; + } + + private static SSLContext createBougusServerSSLContext() + throws GeneralSecurityException, IOException + { + // Create keystore + KeyStore ks = KeyStore.getInstance("JKS"); + InputStream in = null; + try + { + in = BogusSSLContextFactory.class.getResourceAsStream(BOGUS_KEYSTORE); + if (in == null) + { + throw new IOException("Unable to load keystore resource: " + BOGUS_KEYSTORE); + } + ks.load(in, BOGUS_KEYSTORE_PASSWORD); + } + finally + { + if (in != null) + { + //noinspection EmptyCatchBlock + try + { + in.close(); + } + catch (IOException ignored) + { + } + } + } + + // Set up key manager factory to use our key store + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(ks, BOGUS_KEYSTORE_PASSWORD); + + // Initialize the SSLContext to work with our key managers. + SSLContext sslContext = SSLContext.getInstance(PROTOCOL); + sslContext.init(kmf.getKeyManagers(), BogusTrustManagerFactory.X509_MANAGERS, null); + + return sslContext; + } + + private static SSLContext createBougusClientSSLContext() + throws GeneralSecurityException + { + SSLContext context = SSLContext.getInstance(PROTOCOL); + context.init(null, BogusTrustManagerFactory.X509_MANAGERS, null); + return context; + } + +} diff --git a/qpid/java/common/src/org/apache/qpid/ssl/BogusTrustManagerFactory.java b/qpid/java/common/src/org/apache/qpid/ssl/BogusTrustManagerFactory.java new file mode 100644 index 0000000000..8a71e3d7c8 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/ssl/BogusTrustManagerFactory.java @@ -0,0 +1,79 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.ssl; + +import javax.net.ssl.ManagerFactoryParameters; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactorySpi; +import javax.net.ssl.X509TrustManager; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +/** + * Bogus trust manager factory. Used to make testing SSL simpler - i.e no need to + * mess about with keystores. + *

+ * This is based on the example that comes with MINA, written by Trustin Lee. + */ +class BogusTrustManagerFactory extends TrustManagerFactorySpi +{ + + static final X509TrustManager X509 = new X509TrustManager() + { + public void checkClientTrusted(X509Certificate[] x509Certificates, + String s) throws CertificateException + { + } + + public void checkServerTrusted(X509Certificate[] x509Certificates, + String s) throws CertificateException + { + } + + public X509Certificate[] getAcceptedIssuers() + { + return new X509Certificate[ 0 ]; + } + }; + + static final TrustManager[] X509_MANAGERS = new TrustManager[]{X509}; + + public BogusTrustManagerFactory() + { + } + + protected TrustManager[] engineGetTrustManagers() + { + return X509_MANAGERS; + } + + protected void engineInit(KeyStore keystore) throws KeyStoreException + { + // noop + } + + protected void engineInit( + ManagerFactoryParameters managerFactoryParameters) + throws InvalidAlgorithmParameterException + { + // noop + } +} diff --git a/qpid/java/common/src/org/apache/qpid/ssl/SSLServerSocketFactory.java b/qpid/java/common/src/org/apache/qpid/ssl/SSLServerSocketFactory.java new file mode 100644 index 0000000000..f2d5396637 --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/ssl/SSLServerSocketFactory.java @@ -0,0 +1,105 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.ssl; + +import javax.net.ServerSocketFactory; +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.security.GeneralSecurityException; + +/** + * Simple Server Socket factory to create sockets with or without SSL enabled. + * If SSL enabled a "bogus" SSL Context is used (suitable for test purposes) + *

+ * This is based on the example that comes with MINA, written by Trustin Lee. + */ +public class SSLServerSocketFactory extends javax.net.ServerSocketFactory +{ + private static boolean sslEnabled = false; + + private static javax.net.ServerSocketFactory sslFactory = null; + + private static ServerSocketFactory factory = null; + + public SSLServerSocketFactory() + { + super(); + } + + public ServerSocket createServerSocket(int port) throws IOException + { + return new ServerSocket(port); + } + + public ServerSocket createServerSocket(int port, int backlog) + throws IOException + { + return new ServerSocket(port, backlog); + } + + public ServerSocket createServerSocket(int port, int backlog, + InetAddress ifAddress) + throws IOException + { + return new ServerSocket(port, backlog, ifAddress); + } + + public static javax.net.ServerSocketFactory getServerSocketFactory() + throws IOException + { + if (isSslEnabled()) + { + if (sslFactory == null) + { + try + { + sslFactory = BogusSSLContextFactory.getInstance(true) + .getServerSocketFactory(); + } + catch (GeneralSecurityException e) + { + IOException ioe = new IOException( + "could not create SSL socket"); + ioe.initCause(e); + throw ioe; + } + } + return sslFactory; + } + else + { + if (factory == null) + { + factory = new SSLServerSocketFactory(); + } + return factory; + } + + } + + public static boolean isSslEnabled() + { + return sslEnabled; + } + + public static void setSslEnabled(boolean newSslEnabled) + { + sslEnabled = newSslEnabled; + } +} diff --git a/qpid/java/common/src/org/apache/qpid/ssl/SSLSocketFactory.java b/qpid/java/common/src/org/apache/qpid/ssl/SSLSocketFactory.java new file mode 100644 index 0000000000..31dccb593e --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/ssl/SSLSocketFactory.java @@ -0,0 +1,135 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.ssl; + +import javax.net.SocketFactory; +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.net.UnknownHostException; +import java.security.GeneralSecurityException; + +/** + * Simple Socket factory to create sockets with or without SSL enabled. + * If SSL enabled a "bogus" SSL Context is used (suitable for test purposes). + *

+ * This is based on an example that comes with MINA, written by Trustin Lee. + */ +public class SSLSocketFactory extends SocketFactory +{ + private static boolean sslEnabled = false; + + private static javax.net.ssl.SSLSocketFactory sslFactory = null; + + private static javax.net.SocketFactory factory = null; + + public SSLSocketFactory() + { + super(); + } + + public Socket createSocket(String arg1, int arg2) throws IOException, + UnknownHostException + { + if (isSslEnabled()) + { + return getSSLFactory().createSocket(arg1, arg2); + } + else + { + return new Socket(arg1, arg2); + } + } + + public Socket createSocket(String arg1, int arg2, InetAddress arg3, + int arg4) throws IOException, + UnknownHostException + { + if (isSslEnabled()) + { + return getSSLFactory().createSocket(arg1, arg2, arg3, arg4); + } + else + { + return new Socket(arg1, arg2, arg3, arg4); + } + } + + public Socket createSocket(InetAddress arg1, int arg2) + throws IOException + { + if (isSslEnabled()) + { + return getSSLFactory().createSocket(arg1, arg2); + } + else + { + return new Socket(arg1, arg2); + } + } + + public Socket createSocket(InetAddress arg1, int arg2, InetAddress arg3, + int arg4) throws IOException + { + if (isSslEnabled()) + { + return getSSLFactory().createSocket(arg1, arg2, arg3, arg4); + } + else + { + return new Socket(arg1, arg2, arg3, arg4); + } + } + + public static javax.net.SocketFactory getSocketFactory() + { + if (factory == null) + { + factory = new SSLSocketFactory(); + } + return factory; + } + + private javax.net.ssl.SSLSocketFactory getSSLFactory() + { + if (sslFactory == null) + { + try + { + sslFactory = BogusSSLContextFactory.getInstance(false) + .getSocketFactory(); + } + catch (GeneralSecurityException e) + { + throw new RuntimeException("could not create SSL socket", e); + } + } + return sslFactory; + } + + public static boolean isSslEnabled() + { + return sslEnabled; + } + + public static void setSslEnabled(boolean newSslEnabled) + { + sslEnabled = newSslEnabled; + } + +} diff --git a/qpid/java/common/src/org/apache/qpid/url/AMQBindingURL.java b/qpid/java/common/src/org/apache/qpid/url/AMQBindingURL.java new file mode 100644 index 0000000000..5ea1a55f2a --- /dev/null +++ b/qpid/java/common/src/org/apache/qpid/url/AMQBindingURL.java @@ -0,0 +1,260 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.url; + +import org.apache.qpid.url.BindingURL; +import org.apache.qpid.url.URLHelper; +import org.apache.qpid.exchange.ExchangeDefaults; + +import java.util.HashMap; +import java.net.URI; +import java.net.URISyntaxException; + +public class AMQBindingURL implements BindingURL +{ + String _url; + String _exchangeClass; + String _exchangeName; + String _destinationName; + String _queueName; + private HashMap _options; + + + public AMQBindingURL(String url) throws URLSyntaxException + { + //format: + // :///[]/[]?

+ * This is based on the sample that comes with MINA, written by Trustin Lee + */ +public class BogusSSLContextFactory +{ + /** + * Protocol to use. + */ + private static final String PROTOCOL = "TLS"; + + /** + * Bougus Server certificate keystore file name. + */ + private static final String BOGUS_KEYSTORE = "qpid.cert"; + + // NOTE: The keystore was generated using keytool: + // keytool -genkey -alias qpid -keysize 512 -validity 3650 + // -keyalg RSA -dname "CN=amqp.org" -keypass qpidpw + // -storepass qpidpw -keystore qpid.cert + + private static final char[] BOGUS_KEYSTORE_PASSWORD = {'q', 'p', 'i', 'd', 'p', 'w'}; + + private static SSLContext serverInstance = null; + + private static SSLContext clientInstance = null; + + /** + * Get SSLContext singleton. + * + * @return SSLContext + * @throws java.security.GeneralSecurityException + */ + public static SSLContext getInstance(boolean server) + throws GeneralSecurityException + { + SSLContext retInstance; + if (server) + { + // FIXME: looks like double-checking locking + if (serverInstance == null) + { + synchronized (BogusSSLContextFactory.class) + { + if (serverInstance == null) + { + try + { + serverInstance = createBougusServerSSLContext(); + } + catch (Exception ioe) + { + throw new GeneralSecurityException( + "Can't create Server SSLContext:" + ioe); + } + } + } + } + retInstance = serverInstance; + } + else + { + // FIXME: looks like double-checking locking + if (clientInstance == null) + { + synchronized (BogusSSLContextFactory.class) + { + if (clientInstance == null) + { + clientInstance = createBougusClientSSLContext(); + } + } + } + retInstance = clientInstance; + } + return retInstance; + } + + private static SSLContext createBougusServerSSLContext() + throws GeneralSecurityException, IOException + { + // Create keystore + KeyStore ks = KeyStore.getInstance("JKS"); + InputStream in = null; + try + { + in = BogusSSLContextFactory.class.getResourceAsStream(BOGUS_KEYSTORE); + if (in == null) + { + throw new IOException("Unable to load keystore resource: " + BOGUS_KEYSTORE); + } + ks.load(in, BOGUS_KEYSTORE_PASSWORD); + } + finally + { + if (in != null) + { + //noinspection EmptyCatchBlock + try + { + in.close(); + } + catch (IOException ignored) + { + } + } + } + + // Set up key manager factory to use our key store + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(ks, BOGUS_KEYSTORE_PASSWORD); + + // Initialize the SSLContext to work with our key managers. + SSLContext sslContext = SSLContext.getInstance(PROTOCOL); + sslContext.init(kmf.getKeyManagers(), BogusTrustManagerFactory.X509_MANAGERS, null); + + return sslContext; + } + + private static SSLContext createBougusClientSSLContext() + throws GeneralSecurityException + { + SSLContext context = SSLContext.getInstance(PROTOCOL); + context.init(null, BogusTrustManagerFactory.X509_MANAGERS, null); + return context; + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/ssl/BogusTrustManagerFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/ssl/BogusTrustManagerFactory.java new file mode 100644 index 0000000000..4fb6f75b8d --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/ssl/BogusTrustManagerFactory.java @@ -0,0 +1,82 @@ +/* + * + * 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.ssl; + +import javax.net.ssl.ManagerFactoryParameters; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactorySpi; +import javax.net.ssl.X509TrustManager; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +/** + * Bogus trust manager factory. Used to make testing SSL simpler - i.e no need to + * mess about with keystores. + *

+ * This is based on the example that comes with MINA, written by Trustin Lee. + */ +class BogusTrustManagerFactory extends TrustManagerFactorySpi +{ + + static final X509TrustManager X509 = new X509TrustManager() + { + public void checkClientTrusted(X509Certificate[] x509Certificates, + String s) throws CertificateException + { + } + + public void checkServerTrusted(X509Certificate[] x509Certificates, + String s) throws CertificateException + { + } + + public X509Certificate[] getAcceptedIssuers() + { + return new X509Certificate[ 0 ]; + } + }; + + static final TrustManager[] X509_MANAGERS = new TrustManager[]{X509}; + + public BogusTrustManagerFactory() + { + } + + protected TrustManager[] engineGetTrustManagers() + { + return X509_MANAGERS; + } + + protected void engineInit(KeyStore keystore) throws KeyStoreException + { + // noop + } + + protected void engineInit( + ManagerFactoryParameters managerFactoryParameters) + throws InvalidAlgorithmParameterException + { + // noop + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLServerSocketFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLServerSocketFactory.java new file mode 100644 index 0000000000..90b3589752 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLServerSocketFactory.java @@ -0,0 +1,108 @@ +/* + * + * 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.ssl; + +import javax.net.ServerSocketFactory; +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.security.GeneralSecurityException; + +/** + * Simple Server Socket factory to create sockets with or without SSL enabled. + * If SSL enabled a "bogus" SSL Context is used (suitable for test purposes) + *

+ * This is based on the example that comes with MINA, written by Trustin Lee. + */ +public class SSLServerSocketFactory extends javax.net.ServerSocketFactory +{ + private static boolean sslEnabled = false; + + private static javax.net.ServerSocketFactory sslFactory = null; + + private static ServerSocketFactory factory = null; + + public SSLServerSocketFactory() + { + super(); + } + + public ServerSocket createServerSocket(int port) throws IOException + { + return new ServerSocket(port); + } + + public ServerSocket createServerSocket(int port, int backlog) + throws IOException + { + return new ServerSocket(port, backlog); + } + + public ServerSocket createServerSocket(int port, int backlog, + InetAddress ifAddress) + throws IOException + { + return new ServerSocket(port, backlog, ifAddress); + } + + public static javax.net.ServerSocketFactory getServerSocketFactory() + throws IOException + { + if (isSslEnabled()) + { + if (sslFactory == null) + { + try + { + sslFactory = BogusSSLContextFactory.getInstance(true) + .getServerSocketFactory(); + } + catch (GeneralSecurityException e) + { + IOException ioe = new IOException( + "could not create SSL socket"); + ioe.initCause(e); + throw ioe; + } + } + return sslFactory; + } + else + { + if (factory == null) + { + factory = new SSLServerSocketFactory(); + } + return factory; + } + + } + + public static boolean isSslEnabled() + { + return sslEnabled; + } + + public static void setSslEnabled(boolean newSslEnabled) + { + sslEnabled = newSslEnabled; + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLSocketFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLSocketFactory.java new file mode 100644 index 0000000000..ef9820f067 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLSocketFactory.java @@ -0,0 +1,138 @@ +/* + * + * 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.ssl; + +import javax.net.SocketFactory; +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.net.UnknownHostException; +import java.security.GeneralSecurityException; + +/** + * Simple Socket factory to create sockets with or without SSL enabled. + * If SSL enabled a "bogus" SSL Context is used (suitable for test purposes). + *

+ * This is based on an example that comes with MINA, written by Trustin Lee. + */ +public class SSLSocketFactory extends SocketFactory +{ + private static boolean sslEnabled = false; + + private static javax.net.ssl.SSLSocketFactory sslFactory = null; + + private static javax.net.SocketFactory factory = null; + + public SSLSocketFactory() + { + super(); + } + + public Socket createSocket(String arg1, int arg2) throws IOException, + UnknownHostException + { + if (isSslEnabled()) + { + return getSSLFactory().createSocket(arg1, arg2); + } + else + { + return new Socket(arg1, arg2); + } + } + + public Socket createSocket(String arg1, int arg2, InetAddress arg3, + int arg4) throws IOException, + UnknownHostException + { + if (isSslEnabled()) + { + return getSSLFactory().createSocket(arg1, arg2, arg3, arg4); + } + else + { + return new Socket(arg1, arg2, arg3, arg4); + } + } + + public Socket createSocket(InetAddress arg1, int arg2) + throws IOException + { + if (isSslEnabled()) + { + return getSSLFactory().createSocket(arg1, arg2); + } + else + { + return new Socket(arg1, arg2); + } + } + + public Socket createSocket(InetAddress arg1, int arg2, InetAddress arg3, + int arg4) throws IOException + { + if (isSslEnabled()) + { + return getSSLFactory().createSocket(arg1, arg2, arg3, arg4); + } + else + { + return new Socket(arg1, arg2, arg3, arg4); + } + } + + public static javax.net.SocketFactory getSocketFactory() + { + if (factory == null) + { + factory = new SSLSocketFactory(); + } + return factory; + } + + private javax.net.ssl.SSLSocketFactory getSSLFactory() + { + if (sslFactory == null) + { + try + { + sslFactory = BogusSSLContextFactory.getInstance(false) + .getSocketFactory(); + } + catch (GeneralSecurityException e) + { + throw new RuntimeException("could not create SSL socket", e); + } + } + return sslFactory; + } + + public static boolean isSslEnabled() + { + return sslEnabled; + } + + public static void setSslEnabled(boolean newSslEnabled) + { + sslEnabled = newSslEnabled; + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java b/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java new file mode 100644 index 0000000000..b6a0bd500a --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java @@ -0,0 +1,263 @@ +/* + * + * 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.url; + +import org.apache.qpid.url.BindingURL; +import org.apache.qpid.url.URLHelper; +import org.apache.qpid.exchange.ExchangeDefaults; + +import java.util.HashMap; +import java.net.URI; +import java.net.URISyntaxException; + +public class AMQBindingURL implements BindingURL +{ + String _url; + String _exchangeClass; + String _exchangeName; + String _destinationName; + String _queueName; + private HashMap _options; + + + public AMQBindingURL(String url) throws URLSyntaxException + { + //format: + // :///[]/[]?

- * This is based on the sample that comes with MINA, written by Trustin Lee - */ -public class BogusSSLContextFactory -{ - /** - * Protocol to use. - */ - private static final String PROTOCOL = "TLS"; - - /** - * Bougus Server certificate keystore file name. - */ - private static final String BOGUS_KEYSTORE = "qpid.cert"; - - // NOTE: The keystore was generated using keytool: - // keytool -genkey -alias qpid -keysize 512 -validity 3650 - // -keyalg RSA -dname "CN=amqp.org" -keypass qpidpw - // -storepass qpidpw -keystore qpid.cert - - private static final char[] BOGUS_KEYSTORE_PASSWORD = {'q', 'p', 'i', 'd', 'p', 'w'}; - - private static SSLContext serverInstance = null; - - private static SSLContext clientInstance = null; - - /** - * Get SSLContext singleton. - * - * @return SSLContext - * @throws java.security.GeneralSecurityException - */ - public static SSLContext getInstance(boolean server) - throws GeneralSecurityException - { - SSLContext retInstance; - if (server) - { - // FIXME: looks like double-checking locking - if (serverInstance == null) - { - synchronized (BogusSSLContextFactory.class) - { - if (serverInstance == null) - { - try - { - serverInstance = createBougusServerSSLContext(); - } - catch (Exception ioe) - { - throw new GeneralSecurityException( - "Can't create Server SSLContext:" + ioe); - } - } - } - } - retInstance = serverInstance; - } - else - { - // FIXME: looks like double-checking locking - if (clientInstance == null) - { - synchronized (BogusSSLContextFactory.class) - { - if (clientInstance == null) - { - clientInstance = createBougusClientSSLContext(); - } - } - } - retInstance = clientInstance; - } - return retInstance; - } - - private static SSLContext createBougusServerSSLContext() - throws GeneralSecurityException, IOException - { - // Create keystore - KeyStore ks = KeyStore.getInstance("JKS"); - InputStream in = null; - try - { - in = BogusSSLContextFactory.class.getResourceAsStream(BOGUS_KEYSTORE); - if (in == null) - { - throw new IOException("Unable to load keystore resource: " + BOGUS_KEYSTORE); - } - ks.load(in, BOGUS_KEYSTORE_PASSWORD); - } - finally - { - if (in != null) - { - //noinspection EmptyCatchBlock - try - { - in.close(); - } - catch (IOException ignored) - { - } - } - } - - // Set up key manager factory to use our key store - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, BOGUS_KEYSTORE_PASSWORD); - - // Initialize the SSLContext to work with our key managers. - SSLContext sslContext = SSLContext.getInstance(PROTOCOL); - sslContext.init(kmf.getKeyManagers(), BogusTrustManagerFactory.X509_MANAGERS, null); - - return sslContext; - } - - private static SSLContext createBougusClientSSLContext() - throws GeneralSecurityException - { - SSLContext context = SSLContext.getInstance(PROTOCOL); - context.init(null, BogusTrustManagerFactory.X509_MANAGERS, null); - return context; - } - -} diff --git a/qpid/java/common/src/org/apache/qpid/ssl/BogusTrustManagerFactory.java b/qpid/java/common/src/org/apache/qpid/ssl/BogusTrustManagerFactory.java deleted file mode 100644 index 4fb6f75b8d..0000000000 --- a/qpid/java/common/src/org/apache/qpid/ssl/BogusTrustManagerFactory.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * 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.ssl; - -import javax.net.ssl.ManagerFactoryParameters; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactorySpi; -import javax.net.ssl.X509TrustManager; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -/** - * Bogus trust manager factory. Used to make testing SSL simpler - i.e no need to - * mess about with keystores. - *

- * This is based on the example that comes with MINA, written by Trustin Lee. - */ -class BogusTrustManagerFactory extends TrustManagerFactorySpi -{ - - static final X509TrustManager X509 = new X509TrustManager() - { - public void checkClientTrusted(X509Certificate[] x509Certificates, - String s) throws CertificateException - { - } - - public void checkServerTrusted(X509Certificate[] x509Certificates, - String s) throws CertificateException - { - } - - public X509Certificate[] getAcceptedIssuers() - { - return new X509Certificate[ 0 ]; - } - }; - - static final TrustManager[] X509_MANAGERS = new TrustManager[]{X509}; - - public BogusTrustManagerFactory() - { - } - - protected TrustManager[] engineGetTrustManagers() - { - return X509_MANAGERS; - } - - protected void engineInit(KeyStore keystore) throws KeyStoreException - { - // noop - } - - protected void engineInit( - ManagerFactoryParameters managerFactoryParameters) - throws InvalidAlgorithmParameterException - { - // noop - } -} diff --git a/qpid/java/common/src/org/apache/qpid/ssl/SSLServerSocketFactory.java b/qpid/java/common/src/org/apache/qpid/ssl/SSLServerSocketFactory.java deleted file mode 100644 index 90b3589752..0000000000 --- a/qpid/java/common/src/org/apache/qpid/ssl/SSLServerSocketFactory.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * - * 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.ssl; - -import javax.net.ServerSocketFactory; -import java.io.IOException; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.security.GeneralSecurityException; - -/** - * Simple Server Socket factory to create sockets with or without SSL enabled. - * If SSL enabled a "bogus" SSL Context is used (suitable for test purposes) - *

- * This is based on the example that comes with MINA, written by Trustin Lee. - */ -public class SSLServerSocketFactory extends javax.net.ServerSocketFactory -{ - private static boolean sslEnabled = false; - - private static javax.net.ServerSocketFactory sslFactory = null; - - private static ServerSocketFactory factory = null; - - public SSLServerSocketFactory() - { - super(); - } - - public ServerSocket createServerSocket(int port) throws IOException - { - return new ServerSocket(port); - } - - public ServerSocket createServerSocket(int port, int backlog) - throws IOException - { - return new ServerSocket(port, backlog); - } - - public ServerSocket createServerSocket(int port, int backlog, - InetAddress ifAddress) - throws IOException - { - return new ServerSocket(port, backlog, ifAddress); - } - - public static javax.net.ServerSocketFactory getServerSocketFactory() - throws IOException - { - if (isSslEnabled()) - { - if (sslFactory == null) - { - try - { - sslFactory = BogusSSLContextFactory.getInstance(true) - .getServerSocketFactory(); - } - catch (GeneralSecurityException e) - { - IOException ioe = new IOException( - "could not create SSL socket"); - ioe.initCause(e); - throw ioe; - } - } - return sslFactory; - } - else - { - if (factory == null) - { - factory = new SSLServerSocketFactory(); - } - return factory; - } - - } - - public static boolean isSslEnabled() - { - return sslEnabled; - } - - public static void setSslEnabled(boolean newSslEnabled) - { - sslEnabled = newSslEnabled; - } -} diff --git a/qpid/java/common/src/org/apache/qpid/ssl/SSLSocketFactory.java b/qpid/java/common/src/org/apache/qpid/ssl/SSLSocketFactory.java deleted file mode 100644 index ef9820f067..0000000000 --- a/qpid/java/common/src/org/apache/qpid/ssl/SSLSocketFactory.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * - * 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.ssl; - -import javax.net.SocketFactory; -import java.io.IOException; -import java.net.InetAddress; -import java.net.Socket; -import java.net.UnknownHostException; -import java.security.GeneralSecurityException; - -/** - * Simple Socket factory to create sockets with or without SSL enabled. - * If SSL enabled a "bogus" SSL Context is used (suitable for test purposes). - *

- * This is based on an example that comes with MINA, written by Trustin Lee. - */ -public class SSLSocketFactory extends SocketFactory -{ - private static boolean sslEnabled = false; - - private static javax.net.ssl.SSLSocketFactory sslFactory = null; - - private static javax.net.SocketFactory factory = null; - - public SSLSocketFactory() - { - super(); - } - - public Socket createSocket(String arg1, int arg2) throws IOException, - UnknownHostException - { - if (isSslEnabled()) - { - return getSSLFactory().createSocket(arg1, arg2); - } - else - { - return new Socket(arg1, arg2); - } - } - - public Socket createSocket(String arg1, int arg2, InetAddress arg3, - int arg4) throws IOException, - UnknownHostException - { - if (isSslEnabled()) - { - return getSSLFactory().createSocket(arg1, arg2, arg3, arg4); - } - else - { - return new Socket(arg1, arg2, arg3, arg4); - } - } - - public Socket createSocket(InetAddress arg1, int arg2) - throws IOException - { - if (isSslEnabled()) - { - return getSSLFactory().createSocket(arg1, arg2); - } - else - { - return new Socket(arg1, arg2); - } - } - - public Socket createSocket(InetAddress arg1, int arg2, InetAddress arg3, - int arg4) throws IOException - { - if (isSslEnabled()) - { - return getSSLFactory().createSocket(arg1, arg2, arg3, arg4); - } - else - { - return new Socket(arg1, arg2, arg3, arg4); - } - } - - public static javax.net.SocketFactory getSocketFactory() - { - if (factory == null) - { - factory = new SSLSocketFactory(); - } - return factory; - } - - private javax.net.ssl.SSLSocketFactory getSSLFactory() - { - if (sslFactory == null) - { - try - { - sslFactory = BogusSSLContextFactory.getInstance(false) - .getSocketFactory(); - } - catch (GeneralSecurityException e) - { - throw new RuntimeException("could not create SSL socket", e); - } - } - return sslFactory; - } - - public static boolean isSslEnabled() - { - return sslEnabled; - } - - public static void setSslEnabled(boolean newSslEnabled) - { - sslEnabled = newSslEnabled; - } - -} diff --git a/qpid/java/common/src/org/apache/qpid/url/AMQBindingURL.java b/qpid/java/common/src/org/apache/qpid/url/AMQBindingURL.java deleted file mode 100644 index b6a0bd500a..0000000000 --- a/qpid/java/common/src/org/apache/qpid/url/AMQBindingURL.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * - * 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.url; - -import org.apache.qpid.url.BindingURL; -import org.apache.qpid.url.URLHelper; -import org.apache.qpid.exchange.ExchangeDefaults; - -import java.util.HashMap; -import java.net.URI; -import java.net.URISyntaxException; - -public class AMQBindingURL implements BindingURL -{ - String _url; - String _exchangeClass; - String _exchangeName; - String _destinationName; - String _queueName; - private HashMap _options; - - - public AMQBindingURL(String url) throws URLSyntaxException - { - //format: - // :///[]/[]?

  • channel id
  • + *
  • protocol method
  • + * to listeners. This means that listeners do not need to be stateful. + * + * In the StateAwareMethodListener, other useful objects such as the protocol session + * are made available. + * + */ +public class AMQMethodEvent +{ + private final M _method; + + private final int _channelId; + + public AMQMethodEvent(int channelId, M method) + { + _channelId = channelId; + _method = method; + } + + public M getMethod() + { + return _method; + } + + public int getChannelId() + { + return _channelId; + } + + public String toString() + { + StringBuilder buf = new StringBuilder("Method event: "); + buf.append("\nChannel id: ").append(_channelId); + buf.append("\nMethod: ").append(_method); + return buf.toString(); + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQProtocolWriter.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQProtocolWriter.java new file mode 100644 index 0000000000..bc06fc3e6f --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQProtocolWriter.java @@ -0,0 +1,32 @@ +/* + * + * 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.protocol; + +import org.apache.qpid.framing.AMQDataBlock; + +public interface AMQProtocolWriter +{ + /** + * Write a datablock, encoding where necessary (e.g. into a sequence of bytes) + * @param frame the frame to be encoded and written + */ + public void writeFrame(AMQDataBlock frame); +} -- cgit v1.2.1 From 9225300532f0cbe1cf82ad8d97b752cbef344a03 Mon Sep 17 00:00:00 2001 From: Kim van der Riet Date: Fri, 12 Jan 2007 22:02:11 +0000 Subject: Created common AMQMethodListener class, allowing the Request and Response managers to use a common interface to dispatch events to both the client and servers. Refactoring of bothe the client and broker AMQStateManagers and AMQProtocolSession classes was performed. The refactoring has run aground in the clustering, however, and this still needs to be resolved. As the cluster tests are currently disabled (by whom, I'm not sure), this does not disrupt the overall test result. JIRAs will be opened for this issue. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@495754 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/qpid/protocol/AMQMethodListener.java | 49 ++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java new file mode 100644 index 0000000000..f77b5084f3 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java @@ -0,0 +1,49 @@ +/* + * + * 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.protocol; + +import org.apache.qpid.framing.AMQMethodBody; + +/** + * Interface that allows classes to register for interest in protocol method frames. + * + */ +public interface AMQMethodListener +{ + /** + * Invoked when a method frame has been received + * @param evt the event that contains the method and channel + * @param protocolSession the protocol session associated with the event + * @return true if the handler has processed the method frame, false otherwise. Note + * that this does not prohibit the method event being delivered to subsequent listeners + * but can be used to determine if nobody has dealt with an incoming method frame. + * @throws AMQException if an error has occurred. This exception will be delivered + * to all registered listeners using the error() method (see below) allowing them to + * perform cleanup if necessary. + */ + boolean methodReceived(AMQMethodEvent evt) throws Exception; + + /** + * Callback when an error has occurred. Allows listeners to clean up. + * @param e + */ + void error(Exception e); +} -- cgit v1.2.1 From 1a2327b98e6d5b2a65a12b70a9abc3f5ceb0f113 Mon Sep 17 00:00:00 2001 From: Bhupendra Bhusman Bhardwaj Date: Mon, 15 Jan 2007 16:10:59 +0000 Subject: QPID-295 git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@496384 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/qpid/framing/BasicContentHeaderProperties.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java index 7c881c5a78..b891c914ec 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java @@ -638,7 +638,18 @@ public class BasicContentHeaderProperties implements ContentHeaderProperties public String toString() { - return "reply-to = " + _replyTo + " propertyFlags = " + _propertyFlags; + return "reply-to = " + _replyTo + + ",propertyFlags = " + _propertyFlags + + ",ApplicationID = " + _appId + + ",ClusterID = " + _clusterId + + ",UserId = " + _userId + + ",JMSMessageID = " + _messageId + + ",JMSCorrelationID = " + _correlationId + + ",JMSDeliveryMode = " + _deliveryMode + + ",JMSExpiration = " + _expiration + + ",JMSPriority = " + _priority + + ",JMSTimestamp = " + _timestamp + + ",JMSType = " + _type; } // MapMessage Interface -- cgit v1.2.1 From 46699fb0886132cb6d87c43fd18610ec9c9d2060 Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Tue, 16 Jan 2007 08:58:58 +0000 Subject: QPID-245 Field table now uses short strings only for interop, pending full proposal approval from AMQP git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@496626 13f79535-47bb-0310-9956-ffa450edef68 --- .../src/main/java/org/apache/qpid/framing/FieldTable.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java index 147601b9f9..a6c21399a7 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java @@ -364,7 +364,7 @@ public class FieldTable public Object setByte(String string, byte b) { return setByte(new AMQShortString(string), b); - } + } public Object setByte(AMQShortString string, byte b) { @@ -453,7 +453,9 @@ public class FieldTable public Object setString(AMQShortString string, String value) { - checkPropertyName(string); + // temporary for interop until field table types are standardised + return setAsciiString(string, value); + /*checkPropertyName(string); if (value == null) { return setProperty(string, AMQType.VOID.asTypedValue(null)); @@ -469,7 +471,7 @@ public class FieldTable // { // return setProperty(string, AMQType.ASCII_STRING.asTypedValue(value)); // } - } + } */ } @@ -648,7 +650,7 @@ public class FieldTable } } - + // ************************* Byte Buffer Processing public void writeToBuffer(ByteBuffer buffer) @@ -823,7 +825,7 @@ public class FieldTable public void clear() { initMapIfNecessary(); - _encodedForm = null; + _encodedForm = null; _properties.clear(); _encodedSize = 0; } @@ -914,7 +916,7 @@ public class FieldTable _properties.put(key,value); - + } while (buffer.remaining() > expectedRemaining); -- cgit v1.2.1 From 63eb4cdfe3b52c315caf4a50ad7a012d38b900e0 Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Tue, 16 Jan 2007 09:31:44 +0000 Subject: QPID-245 Field table now uses long str type for ascii string - temporary interop hack. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@496637 13f79535-47bb-0310-9956-ffa450edef68 --- .../common/src/main/java/org/apache/qpid/framing/FieldTable.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java index a6c21399a7..118de0fbbc 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java @@ -278,7 +278,8 @@ public class FieldTable { AMQTypedValue value = getProperty(string); if ((value != null) && ((value.getType() == AMQType.WIDE_STRING) || - (value.getType() == AMQType.ASCII_STRING))) + (value.getType() == AMQType.ASCII_STRING || + (value.getType() == AMQType.LONG_STRING)))) { return (String) value.getValue(); } @@ -446,7 +447,7 @@ public class FieldTable } else { - return setProperty(string, AMQType.ASCII_STRING.asTypedValue(value)); + return setProperty(string, AMQType.LONG_STRING.asTypedValue(value)); } } -- cgit v1.2.1 From f5032290250d66a61925de1aebd29eac051f364e Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Tue, 16 Jan 2007 11:14:29 +0000 Subject: QPID-245 Field table now uses long str type for binary type - temporary interop hack. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@496662 13f79535-47bb-0310-9956-ffa450edef68 --- .../common/src/main/java/org/apache/qpid/framing/FieldTable.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java index 118de0fbbc..db3a5851ab 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java @@ -321,7 +321,7 @@ public class FieldTable public byte[] getBytes(AMQShortString string) { AMQTypedValue value = getProperty(string); - if (value != null && (value.getType() == AMQType.BINARY)) + if (value != null && (value.getType() == AMQType.BINARY || value.getType() == AMQType.LONG_STRING)) { return (byte[]) value.getValue(); } @@ -497,7 +497,9 @@ public class FieldTable public Object setBytes(AMQShortString string, byte[] bytes) { checkPropertyName(string); - return setProperty(string, AMQType.BINARY.asTypedValue(bytes)); + // HACK for interop + //return setProperty(string, AMQType.BINARY.asTypedValue(bytes)); + return setProperty(string, AMQType.LONG_STRING.asTypedValue(bytes)); } public Object setBytes(String string, byte[] bytes, int start, int length) -- cgit v1.2.1 From 1442b77dee6de581babed7d4b4040b6fd609d777 Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Tue, 16 Jan 2007 17:29:24 +0000 Subject: QPID-245 reverted interop changes for the sake of JMS compliance. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@496785 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/framing/FieldTable.java | 25 +++++++++------------- 1 file changed, 10 insertions(+), 15 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java index db3a5851ab..147601b9f9 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java @@ -278,8 +278,7 @@ public class FieldTable { AMQTypedValue value = getProperty(string); if ((value != null) && ((value.getType() == AMQType.WIDE_STRING) || - (value.getType() == AMQType.ASCII_STRING || - (value.getType() == AMQType.LONG_STRING)))) + (value.getType() == AMQType.ASCII_STRING))) { return (String) value.getValue(); } @@ -321,7 +320,7 @@ public class FieldTable public byte[] getBytes(AMQShortString string) { AMQTypedValue value = getProperty(string); - if (value != null && (value.getType() == AMQType.BINARY || value.getType() == AMQType.LONG_STRING)) + if (value != null && (value.getType() == AMQType.BINARY)) { return (byte[]) value.getValue(); } @@ -365,7 +364,7 @@ public class FieldTable public Object setByte(String string, byte b) { return setByte(new AMQShortString(string), b); - } + } public Object setByte(AMQShortString string, byte b) { @@ -447,16 +446,14 @@ public class FieldTable } else { - return setProperty(string, AMQType.LONG_STRING.asTypedValue(value)); + return setProperty(string, AMQType.ASCII_STRING.asTypedValue(value)); } } public Object setString(AMQShortString string, String value) { - // temporary for interop until field table types are standardised - return setAsciiString(string, value); - /*checkPropertyName(string); + checkPropertyName(string); if (value == null) { return setProperty(string, AMQType.VOID.asTypedValue(null)); @@ -472,7 +469,7 @@ public class FieldTable // { // return setProperty(string, AMQType.ASCII_STRING.asTypedValue(value)); // } - } */ + } } @@ -497,9 +494,7 @@ public class FieldTable public Object setBytes(AMQShortString string, byte[] bytes) { checkPropertyName(string); - // HACK for interop - //return setProperty(string, AMQType.BINARY.asTypedValue(bytes)); - return setProperty(string, AMQType.LONG_STRING.asTypedValue(bytes)); + return setProperty(string, AMQType.BINARY.asTypedValue(bytes)); } public Object setBytes(String string, byte[] bytes, int start, int length) @@ -653,7 +648,7 @@ public class FieldTable } } - + // ************************* Byte Buffer Processing public void writeToBuffer(ByteBuffer buffer) @@ -828,7 +823,7 @@ public class FieldTable public void clear() { initMapIfNecessary(); - _encodedForm = null; + _encodedForm = null; _properties.clear(); _encodedSize = 0; } @@ -919,7 +914,7 @@ public class FieldTable _properties.put(key,value); - + } while (buffer.remaining() > expectedRemaining); -- cgit v1.2.1 From b4bfefbc739f4738ab63dc8e4596ba7ddd41aa43 Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Tue, 16 Jan 2007 19:38:51 +0000 Subject: Fix to broken build due to missing file. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@496833 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/qpid/util/concurrent/BooleanLatch.java | 42 ++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java new file mode 100644 index 0000000000..70a5f2dc5e --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java @@ -0,0 +1,42 @@ +/* + * + * Copyright (c) 2006 The Apache Software Foundation + * + * Licensed 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.util.concurrent; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * @author Apache Software Foundation + */ +public class BooleanLatch extends CountDownLatch +{ + public BooleanLatch() + { + super(1); + } + + public void signal() + { + countDown(); + } + + public void await(long nanos) throws InterruptedException + { + await(nanos, TimeUnit.NANOSECONDS); + } +} -- cgit v1.2.1 From db41968325bc24b6d91656afdd36b49c9e5ecda7 Mon Sep 17 00:00:00 2001 From: Gordon Sim Date: Thu, 18 Jan 2007 08:41:51 +0000 Subject: * uses LONG_STRING in place of WIDE_STRING for properties set through FieldTable.setString() as these appear to all be equivalent (apart from the type code) * uses setString instead of setAsciiString in creation of the connection.start-ok frames client properties * uses 4 bytes for the size of the BINARY value type as per the spec posted on the wiki git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@497352 13f79535-47bb-0310-9956-ffa450edef68 --- .../common/src/main/java/org/apache/qpid/framing/AMQType.java | 6 +++--- .../src/main/java/org/apache/qpid/framing/EncodingUtils.java | 2 +- .../src/main/java/org/apache/qpid/framing/FieldTable.java | 11 +---------- .../java/org/apache/qpid/framing/PropertyFieldTableTest.java | 7 +++---- 4 files changed, 8 insertions(+), 18 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQType.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQType.java index 23c1929205..5175eace1e 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQType.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQType.java @@ -230,7 +230,7 @@ public enum AMQType { public int getEncodingSize(Object value) { - return 1 + (value == null ? 0 : ((byte[]) value).length); + return EncodingUtils.encodedLongstrLength((byte[]) value); } @@ -250,12 +250,12 @@ public enum AMQType public void writeValueImpl(Object value, ByteBuffer buffer) { - EncodingUtils.writeBytes(buffer, (byte[]) value); + EncodingUtils.writeLongstr(buffer, (byte[]) value); } public Object readValueFromBuffer(ByteBuffer buffer) { - return EncodingUtils.readBytes(buffer); + return EncodingUtils.readLongstr(buffer); } }, diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java index c4d568ba88..339f83588d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java @@ -747,7 +747,7 @@ public class EncodingUtils } } - public static byte[] readLongstr(ByteBuffer buffer) throws AMQFrameDecodingException + public static byte[] readLongstr(ByteBuffer buffer) { long length = buffer.getUnsignedInt(); if (length == 0) diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java index 147601b9f9..1a72910536 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java @@ -448,7 +448,6 @@ public class FieldTable { return setProperty(string, AMQType.ASCII_STRING.asTypedValue(value)); } - } public Object setString(AMQShortString string, String value) @@ -460,15 +459,7 @@ public class FieldTable } else { - //FIXME: determine string encoding and set either WIDE or ASCII string -// if () - { - return setProperty(string, AMQType.WIDE_STRING.asTypedValue(value)); - } -// else -// { -// return setProperty(string, AMQType.ASCII_STRING.asTypedValue(value)); -// } + return setProperty(string, AMQType.LONG_STRING.asTypedValue(value)); } } diff --git a/qpid/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java b/qpid/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java index e0692594c7..6160dc1843 100644 --- a/qpid/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java +++ b/qpid/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java @@ -528,8 +528,7 @@ public class PropertyFieldTableTest extends TestCase table.setString("string", "hello"); table.setString("null-string", null); - - final ByteBuffer buffer = ByteBuffer.allocate((int) table.getEncodedSize()); // FIXME XXX: Is cast a problem? + final ByteBuffer buffer = ByteBuffer.allocate((int) table.getEncodedSize() + 4); // FIXME XXX: Is cast a problem? table.writeToBuffer(buffer); @@ -579,7 +578,7 @@ public class PropertyFieldTableTest extends TestCase byte[] _bytes = {99, 98, 97, 96, 95}; result.setBytes("bytes", _bytes); - size += 1 + EncodingUtils.encodedShortStringLength("bytes") + 1 + EncodingUtils.encodedByteLength() * _bytes.length; + size += 1 + EncodingUtils.encodedShortStringLength("bytes") + 4 + _bytes.length; Assert.assertEquals(size, result.getEncodedSize()); result.setChar("char", (char) 'c'); @@ -621,7 +620,7 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals(size, result.getEncodedSize()); result.setObject("object-bytes", _bytes); - size += 1 + EncodingUtils.encodedShortStringLength("object-bytes") + 1 + EncodingUtils.encodedByteLength() * _bytes.length; + size += 1 + EncodingUtils.encodedShortStringLength("object-bytes") + 4 + _bytes.length; Assert.assertEquals(size, result.getEncodedSize()); result.setObject("object-char", 'c'); -- cgit v1.2.1 From d3afeb37f22fc356d5cda3861a85c8f949a9c051 Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Fri, 19 Jan 2007 10:35:21 +0000 Subject: QPID-275 : Patch supplied by Rob Godfrey - Add support for get / purge / qos size / default exchanges and some other small fixes highlighted by the python tests git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@497770 13f79535-47bb-0310-9956-ffa450edef68 --- .../main/java/org/apache/qpid/AMQConnectionException.java | 4 ++++ .../main/java/org/apache/qpid/framing/AMQMethodBody.java | 14 ++++++++++++++ 2 files changed, 18 insertions(+) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java index 477123a4ec..c6a874bcf3 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java @@ -32,6 +32,7 @@ public class AMQConnectionException extends AMQException /* AMQP version for which exception ocurred */ private final byte major; private final byte minor; + boolean _closeConnetion; public AMQConnectionException(int errorCode, String msg, int classId, int methodId, byte major, byte minor, Throwable t) { @@ -51,9 +52,12 @@ public class AMQConnectionException extends AMQException this.minor = minor; } + + public AMQFrame getCloseFrame(int channel) { return ConnectionCloseBody.createAMQFrame(channel, major, minor, _classId, _methodId, getErrorCode(), new AMQShortString(getMessage())); } + } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java index 5ccc900b2c..cd178a6197 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java @@ -22,6 +22,7 @@ package org.apache.qpid.framing; import org.apache.mina.common.ByteBuffer; import org.apache.qpid.AMQChannelException; +import org.apache.qpid.AMQConnectionException; public abstract class AMQMethodBody extends AMQBody { @@ -101,4 +102,17 @@ public abstract class AMQMethodBody extends AMQBody { return new AMQChannelException(code, message, getClazz(), getMethod(), major, minor, cause); } + + public AMQConnectionException getConnectionException(int code, String message) + { + return new AMQConnectionException(code, message, getClazz(), getMethod(), major, minor); + } + + + + public AMQConnectionException getConnectionException(int code, String message, Throwable cause) + { + return new AMQConnectionException(code, message, getClazz(), getMethod(), major, minor, cause); + } + } -- cgit v1.2.1 From 96686cd26249fc0c81a59441c7eca9467e15873b Mon Sep 17 00:00:00 2001 From: Martin Ritchie Date: Mon, 22 Jan 2007 15:05:58 +0000 Subject: QPID-310 Propagated JMS Exception to client. QPID-308 Configurable timeout on blockForFrame. Timeouts added but need to be configurable. QPID-311 Dispatcher Thread is not thread safe. Added the missing Synchronized code and renamed vars to make it more readable git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@498637 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/AMQTimeoutException.java | 29 ++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java new file mode 100644 index 0000000000..6af681f479 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java @@ -0,0 +1,29 @@ +/* + * 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; + +public class AMQTimeoutException extends AMQException +{ + public AMQTimeoutException(String message) + { + super(message); + } +} -- cgit v1.2.1 From 9068179bbf1ca717621bc993e66ecfcafbb3d959 Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Wed, 24 Jan 2007 15:41:48 +0000 Subject: QPID-50 : Patch supplied by Rob Godfrey - Virtual Host implementation git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@499446 13f79535-47bb-0310-9956-ffa450edef68 --- .../src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java | 6 ++++++ .../java/org/apache/qpid/framing/BasicContentHeaderProperties.java | 7 +++++++ 2 files changed, 13 insertions(+) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java b/qpid/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java index 57159f3802..172f1b1790 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java @@ -39,4 +39,10 @@ public class ExchangeDefaults public final static AMQShortString FANOUT_EXCHANGE_NAME = new AMQShortString("amq.fanout"); public final static AMQShortString FANOUT_EXCHANGE_CLASS = new AMQShortString("fanout"); + + + public final static AMQShortString SYSTEM_MANAGEMENT_EXCHANGE_NAME = new AMQShortString("qpid.sysmgmt"); + + public final static AMQShortString SYSTEM_MANAGEMENT_CLASS = new AMQShortString("sysmmgmt"); + } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java index b891c914ec..ed6ab63ded 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java @@ -531,6 +531,13 @@ public class BasicContentHeaderProperties implements ContentHeaderProperties return _replyTo == null ? null : _replyTo.toString(); } + public AMQShortString getReplyToAsShortString() + { + decodeIfNecessary(); + return _replyTo; + } + + public void setReplyTo(String replyTo) { setReplyTo(replyTo == null ? null : new AMQShortString(replyTo)); -- cgit v1.2.1 From 9cc7fadd313161a851b6e72498f822867fea1841 Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Wed, 24 Jan 2007 20:50:47 +0000 Subject: QPID-317 : Patch supplied by Rob Godfrey - Remove dependency on JMS from common / broker. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@499563 13f79535-47bb-0310-9956-ffa450edef68 --- .../qpid/framing/BasicContentHeaderProperties.java | 473 --------------------- 1 file changed, 473 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java index ed6ab63ded..1045b02868 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java @@ -22,11 +22,7 @@ package org.apache.qpid.framing; import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; -import org.apache.qpid.AMQPInvalidClassException; -import javax.jms.JMSException; -import javax.jms.MessageFormatException; -import java.util.Enumeration; public class BasicContentHeaderProperties implements ContentHeaderProperties { @@ -659,474 +655,5 @@ public class BasicContentHeaderProperties implements ContentHeaderProperties ",JMSType = " + _type; } - // MapMessage Interface - public boolean getBoolean(String string) throws JMSException - { - Boolean b = getHeaders().getBoolean(string); - - if (b == null) - { - if (getHeaders().containsKey(string)) - { - Object str = getHeaders().getObject(string); - - if (str == null || !(str instanceof String)) - { - throw new MessageFormatException("getBoolean can't use " + string + " item."); - } - else - { - return Boolean.valueOf((String) str); - } - } - else - { - b = Boolean.valueOf(null); - } - } - - return b; - } - - public boolean getBoolean(AMQShortString string) throws JMSException - { - Boolean b = getHeaders().getBoolean(string); - - if (b == null) - { - if (getHeaders().containsKey(string)) - { - Object str = getHeaders().getObject(string); - - if (str == null || !(str instanceof String)) - { - throw new MessageFormatException("getBoolean can't use " + string + " item."); - } - else - { - return Boolean.valueOf((String) str); - } - } - else - { - b = Boolean.valueOf(null); - } - } - - return b; - } - - public char getCharacter(String string) throws JMSException - { - Character c = getHeaders().getCharacter(string); - - if (c == null) - { - if (getHeaders().isNullStringValue(string)) - { - throw new NullPointerException("Cannot convert null char"); - } - else - { - throw new MessageFormatException("getChar can't use " + string + " item."); - } - } - else - { - return (char) c; - } - } - - public byte[] getBytes(String string) throws JMSException - { - return getBytes(new AMQShortString(string)); - } - - public byte[] getBytes(AMQShortString string) throws JMSException - { - byte[] bs = getHeaders().getBytes(string); - - if (bs == null) - { - throw new MessageFormatException("getBytes can't use " + string + " item."); - } - else - { - return bs; - } - } - - public byte getByte(String string) throws JMSException - { - Byte b = getHeaders().getByte(string); - if (b == null) - { - if (getHeaders().containsKey(string)) - { - Object str = getHeaders().getObject(string); - - if (str == null || !(str instanceof String)) - { - throw new MessageFormatException("getByte can't use " + string + " item."); - } - else - { - return Byte.valueOf((String) str); - } - } - else - { - b = Byte.valueOf(null); - } - } - - return b; - } - - public short getShort(String string) throws JMSException - { - Short s = getHeaders().getShort(string); - - if (s == null) - { - s = Short.valueOf(getByte(string)); - } - - return s; - } - - public int getInteger(String string) throws JMSException - { - Integer i = getHeaders().getInteger(string); - - if (i == null) - { - i = Integer.valueOf(getShort(string)); - } - - return i; - } - - public long getLong(String string) throws JMSException - { - Long l = getHeaders().getLong(string); - - if (l == null) - { - l = Long.valueOf(getInteger(string)); - } - - return l; - } - - public float getFloat(String string) throws JMSException - { - Float f = getHeaders().getFloat(string); - - if (f == null) - { - if (getHeaders().containsKey(string)) - { - Object str = getHeaders().getObject(string); - - if (str == null || !(str instanceof String)) - { - throw new MessageFormatException("getFloat can't use " + string + " item."); - } - else - { - return Float.valueOf((String) str); - } - } - else - { - f = Float.valueOf(null); - } - - } - - return f; - } - - public double getDouble(String string) throws JMSException - { - Double d = getHeaders().getDouble(string); - - if (d == null) - { - d = Double.valueOf(getFloat(string)); - } - - return d; - } - - public String getString(String string) throws JMSException - { - String s = getHeaders().getString(string); - - if (s == null) - { - if (getHeaders().containsKey(string)) - { - Object o = getHeaders().getObject(string); - if (o instanceof byte[]) - { - throw new MessageFormatException("getObject couldn't find " + string + " item."); - } - else - { - if (o == null) - { - return null; - } - else - { - s = String.valueOf(o); - } - } - } - } - - return s; - } - - public Object getObject(String string) throws JMSException - { - return getHeaders().getObject(string); - } - - public void setBoolean(AMQShortString string, boolean b) throws JMSException - { - checkPropertyName(string); - getHeaders().setBoolean(string, b); - } - - public void setBoolean(String string, boolean b) throws JMSException - { - checkPropertyName(string); - getHeaders().setBoolean(string, b); - } - - public void setChar(String string, char c) throws JMSException - { - checkPropertyName(string); - getHeaders().setChar(string, c); - } - - public Object setBytes(AMQShortString string, byte[] bytes) - { - return getHeaders().setBytes(string, bytes); - } - - public Object setBytes(String string, byte[] bytes) - { - return getHeaders().setBytes(string, bytes); - } - - public Object setBytes(String string, byte[] bytes, int start, int length) - { - return getHeaders().setBytes(string, bytes, start, length); - } - - public void setByte(String string, byte b) throws JMSException - { - checkPropertyName(string); - getHeaders().setByte(string, b); - } - - public void setShort(String string, short i) throws JMSException - { - checkPropertyName(string); - getHeaders().setShort(string, i); - } - - public void setInteger(String string, int i) throws JMSException - { - checkPropertyName(string); - getHeaders().setInteger(string, i); - } - - public void setLong(String string, long l) throws JMSException - { - checkPropertyName(string); - getHeaders().setLong(string, l); - } - - public void setFloat(String string, float v) throws JMSException - { - checkPropertyName(string); - getHeaders().setFloat(string, v); - } - - public void setDouble(String string, double v) throws JMSException - { - checkPropertyName(string); - getHeaders().setDouble(string, v); - } - - public void setString(String string, String string1) throws JMSException - { - checkPropertyName(string); - getHeaders().setString(string, string1); - } - - public void setString(AMQShortString string, String string1) throws JMSException - { - checkPropertyName(string); - getHeaders().setString(string, string1); - } - - public void setObject(String string, Object object) throws JMSException - { - checkPropertyName(string); - try - { - getHeaders().setObject(string, object); - } - catch (AMQPInvalidClassException aice) - { - throw new MessageFormatException("Only primatives are allowed object is:" + object.getClass()); - } - } - public boolean itemExists(String string) throws JMSException - { - return getHeaders().containsKey(string); - } - - public Enumeration getPropertyNames() - { - return getHeaders().getPropertyNames(); - } - - public void clear() - { - getHeaders().clear(); - } - - public boolean propertyExists(AMQShortString propertyName) - { - return getHeaders().propertyExists(propertyName); - } - - public boolean propertyExists(String propertyName) - { - return getHeaders().propertyExists(propertyName); - } - - public Object put(Object key, Object value) - { - return getHeaders().setObject(key.toString(), value); - } - - public Object remove(AMQShortString propertyName) - { - return getHeaders().remove(propertyName); - } - - public Object remove(String propertyName) - { - return getHeaders().remove(propertyName); - } - - public boolean isEmpty() - { - return getHeaders().isEmpty(); - } - - public void writeToBuffer(ByteBuffer data) - { - getHeaders().writeToBuffer(data); - } - - public Enumeration getMapNames() - { - return getPropertyNames(); - } - - protected static void checkPropertyName(CharSequence propertyName) - { - if (propertyName == null) - { - throw new IllegalArgumentException("Property name must not be null"); - } - else if (propertyName.length() == 0) - { - throw new IllegalArgumentException("Property name must not be the empty string"); - } - - checkIdentiferFormat(propertyName); - } - - protected static void checkIdentiferFormat(CharSequence propertyName) - { -// JMS requirements 3.5.1 Property Names -// Identifiers: -// - An identifier is an unlimited-length character sequence that must begin -// with a Java identifier start character; all following characters must be Java -// identifier part characters. An identifier start character is any character for -// which the method Character.isJavaIdentifierStart returns true. This includes -// '_' and '$'. An identifier part character is any character for which the -// method Character.isJavaIdentifierPart returns true. -// - Identifiers cannot be the names NULL, TRUE, or FALSE. -// – Identifiers cannot be NOT, AND, OR, BETWEEN, LIKE, IN, IS, or -// ESCAPE. -// – Identifiers are either header field references or property references. The -// type of a property value in a message selector corresponds to the type -// used to set the property. If a property that does not exist in a message is -// referenced, its value is NULL. The semantics of evaluating NULL values -// in a selector are described in Section 3.8.1.2, “Null Values.” -// – The conversions that apply to the get methods for properties do not -// apply when a property is used in a message selector expression. For -// example, suppose you set a property as a string value, as in the -// following: -// myMessage.setStringProperty("NumberOfOrders", "2"); -// The following expression in a message selector would evaluate to false, -// because a string cannot be used in an arithmetic expression: -// "NumberOfOrders > 1" -// – Identifiers are case sensitive. -// – Message header field references are restricted to JMSDeliveryMode, -// JMSPriority, JMSMessageID, JMSTimestamp, JMSCorrelationID, and -// JMSType. JMSMessageID, JMSCorrelationID, and JMSType values may be -// null and if so are treated as a NULL value. - - if (Boolean.getBoolean("strict-jms")) - { - // JMS start character - if (!(Character.isJavaIdentifierStart(propertyName.charAt(0)))) - { - throw new IllegalArgumentException("Identifier '" + propertyName + "' does not start with a valid JMS identifier start character"); - } - - // JMS part character - int length = propertyName.length(); - for (int c = 1; c < length; c++) - { - if (!(Character.isJavaIdentifierPart(propertyName.charAt(c)))) - { - throw new IllegalArgumentException("Identifier '" + propertyName + "' contains an invalid JMS identifier character"); - } - } - - - - - // JMS invalid names - if ((propertyName.equals("NULL") - || propertyName.equals("TRUE") - || propertyName.equals("FALSE") - || propertyName.equals("NOT") - || propertyName.equals("AND") - || propertyName.equals("OR") - || propertyName.equals("BETWEEN") - || propertyName.equals("LIKE") - || propertyName.equals("IN") - || propertyName.equals("IS") - || propertyName.equals("ESCAPE"))) - { - throw new IllegalArgumentException("Identifier '" + propertyName + "' is not allowed in JMS"); - } - } - - } } -- cgit v1.2.1 From 82e12b97f9dae4e2fc7fd16c07f611a1b62d8c72 Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Mon, 29 Jan 2007 10:59:33 +0000 Subject: QPID-320 : Patch supplied by Rob Godfrey - Improve performance by remembering protocol version git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@501003 13f79535-47bb-0310-9956-ffa450edef68 --- .../main/java/org/apache/qpid/framing/AMQBody.java | 2 +- .../apache/qpid/framing/AMQDataBlockDecoder.java | 69 +++++----- .../apache/qpid/framing/AMQDataBlockEncoder.java | 9 +- .../java/org/apache/qpid/framing/AMQFrame.java | 55 ++++---- .../org/apache/qpid/framing/AMQMethodBody.java | 2 +- .../apache/qpid/framing/AMQMethodBodyFactory.java | 21 +-- .../qpid/framing/AMQMethodBodyInstanceFactory.java | 1 + .../org/apache/qpid/framing/AMQShortString.java | 16 +-- .../java/org/apache/qpid/framing/ContentBody.java | 6 +- .../org/apache/qpid/framing/ContentHeaderBody.java | 12 +- .../org/apache/qpid/framing/HeartbeatBody.java | 2 +- .../qpid/framing/VersionSpecificRegistry.java | 141 +++++++++++++++++++++ .../protocol/AMQVersionAwareProtocolSession.java | 29 +++++ .../apache/qpid/protocol/ProtocolVersionAware.java | 28 ++++ 14 files changed, 283 insertions(+), 110 deletions(-) create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java index 36287d2923..ebeea8d2b4 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java @@ -24,7 +24,7 @@ import org.apache.mina.common.ByteBuffer; public abstract class AMQBody { - protected abstract byte getFrameType(); + public abstract byte getFrameType(); /** * Get the size of the body diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java index 552c8e599e..e426651588 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java @@ -24,25 +24,29 @@ import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; +import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; import java.util.HashMap; import java.util.Map; public class AMQDataBlockDecoder { - Logger _logger = Logger.getLogger(AMQDataBlockDecoder.class); + private static final String SESSION_METHOD_BODY_FACTORY = "QPID_SESSION_METHOD_BODY_FACTORY"; - private final Map _supportedBodies = new HashMap(); + private static final BodyFactory[] _bodiesSupported = new BodyFactory[Byte.MAX_VALUE]; - private final static BodyFactory[] _bodiesSupported = new BodyFactory[Byte.MAX_VALUE]; static { - _bodiesSupported[AMQMethodBody.TYPE] = AMQMethodBodyFactory.getInstance(); _bodiesSupported[ContentHeaderBody.TYPE] = ContentHeaderBodyFactory.getInstance(); _bodiesSupported[ContentBody.TYPE] = ContentBodyFactory.getInstance(); _bodiesSupported[HeartbeatBody.TYPE] = new HeartbeatBodyFactory(); } + + Logger _logger = Logger.getLogger(AMQDataBlockDecoder.class); + + + public AMQDataBlockDecoder() { } @@ -55,52 +59,57 @@ public class AMQDataBlockDecoder { return false; } - - final byte type = in.get(); - final int channel = in.getUnsignedShort(); + in.skip(1 + 2); final long bodySize = in.getUnsignedInt(); - // bodySize can be zero - if (type <= 0 || channel < 0 || bodySize < 0) - { - throw new AMQFrameDecodingException("Undecodable frame: type = " + type + " channel = " + channel + - " bodySize = " + bodySize); - } + return (remainingAfterAttributes >= bodySize); } - private boolean isSupportedFrameType(byte frameType) + + protected Object createAndPopulateFrame(IoSession session, ByteBuffer in) + throws AMQFrameDecodingException, AMQProtocolVersionException { - final boolean result = _bodiesSupported[frameType] != null; + final byte type = in.get(); + + BodyFactory bodyFactory; + if(type == AMQMethodBody.TYPE) + { + bodyFactory = (BodyFactory) session.getAttribute(SESSION_METHOD_BODY_FACTORY); + if(bodyFactory == null) + { + AMQVersionAwareProtocolSession protocolSession = (AMQVersionAwareProtocolSession) session.getAttachment(); + bodyFactory = new AMQMethodBodyFactory(protocolSession); + session.setAttribute(SESSION_METHOD_BODY_FACTORY, bodyFactory); + + } - if (!result) + } + else { - _logger.warn("AMQDataBlockDecoder does not handle frame type " + frameType); + bodyFactory = _bodiesSupported[type]; } - return result; - } - protected Object createAndPopulateFrame(ByteBuffer in) - throws AMQFrameDecodingException, AMQProtocolVersionException - { - final byte type = in.get(); - BodyFactory bodyFactory = _bodiesSupported[type]; - if (!isSupportedFrameType(type)) + + + if(bodyFactory == null) { throw new AMQFrameDecodingException("Unsupported frame type: " + type); } + final int channel = in.getUnsignedShort(); final long bodySize = in.getUnsignedInt(); - /* - if (bodyFactory == null) + // bodySize can be zero + if (channel < 0 || bodySize < 0) { - throw new AMQFrameDecodingException("Unsupported body type: " + type); + throw new AMQFrameDecodingException("Undecodable frame: type = " + type + " channel = " + channel + + " bodySize = " + bodySize); } - */ + AMQFrame frame = new AMQFrame(in, channel, bodySize, bodyFactory); @@ -115,6 +124,6 @@ public class AMQDataBlockDecoder public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { - out.write(createAndPopulateFrame(in)); + out.write(createAndPopulateFrame(session, in)); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java index 3446563d35..478cdeb406 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java @@ -28,17 +28,16 @@ import org.apache.mina.filter.codec.demux.MessageEncoder; import java.util.HashSet; import java.util.Set; +import java.util.Collections; -public class AMQDataBlockEncoder implements MessageEncoder +public final class AMQDataBlockEncoder implements MessageEncoder { - Logger _logger = Logger.getLogger(AMQDataBlockEncoder.class); + private static final Logger _logger = Logger.getLogger(AMQDataBlockEncoder.class); - private Set _messageTypes; + private final Set _messageTypes = Collections.singleton(EncodableAMQDataBlock.class); public AMQDataBlockEncoder() { - _messageTypes = new HashSet(); - _messageTypes.add(EncodableAMQDataBlock.class); } public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java index 9e98d9792b..11f505fd4b 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java @@ -24,59 +24,52 @@ import org.apache.mina.common.ByteBuffer; public class AMQFrame extends AMQDataBlock implements EncodableAMQDataBlock { - public int channel; + private final int _channel; - public AMQBody bodyFrame; + private final AMQBody _bodyFrame; - public AMQFrame() - { - } - public AMQFrame(int channel, AMQBody bodyFrame) + + public AMQFrame(final int channel, final AMQBody bodyFrame) { - this.channel = channel; - this.bodyFrame = bodyFrame; + _channel = channel; + _bodyFrame = bodyFrame; } - public AMQFrame(ByteBuffer in, int channel, long bodySize, BodyFactory bodyFactory) throws AMQFrameDecodingException + public AMQFrame(final ByteBuffer in, final int channel, final long bodySize, final BodyFactory bodyFactory) throws AMQFrameDecodingException { - this.channel = channel; - this.bodyFrame = bodyFactory.createBody(in,bodySize); + this._channel = channel; + this._bodyFrame = bodyFactory.createBody(in,bodySize); } public long getSize() { - return 1 + 2 + 4 + bodyFrame.getSize() + 1; + return 1 + 2 + 4 + _bodyFrame.getSize() + 1; } public void writePayload(ByteBuffer buffer) { - buffer.put(bodyFrame.getFrameType()); - // TODO: how does channel get populated - EncodingUtils.writeUnsignedShort(buffer, channel); - EncodingUtils.writeUnsignedInteger(buffer, bodyFrame.getSize()); - bodyFrame.writePayload(buffer); + buffer.put(_bodyFrame.getFrameType()); + EncodingUtils.writeUnsignedShort(buffer, _channel); + EncodingUtils.writeUnsignedInteger(buffer, _bodyFrame.getSize()); + _bodyFrame.writePayload(buffer); buffer.put((byte) 0xCE); } - /** - * - * @param buffer - * @param channel unsigned short - * @param bodySize unsigned integer - * @param bodyFactory - * @throws AMQFrameDecodingException - */ - public void populateFromBuffer(ByteBuffer buffer, int channel, long bodySize, BodyFactory bodyFactory) - throws AMQFrameDecodingException, AMQProtocolVersionException + public final int getChannel() + { + return _channel; + } + + public final AMQBody getBodyFrame() { - this.channel = channel; - bodyFrame = bodyFactory.createBody(buffer, bodySize); - + return _bodyFrame; } + + public String toString() { - return "Frame channelId: " + channel + ", bodyFrame: " + String.valueOf(bodyFrame); + return "Frame channelId: " + _channel + ", bodyFrame: " + String.valueOf(_bodyFrame); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java index cd178a6197..3fa5b150ab 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java @@ -57,7 +57,7 @@ public abstract class AMQMethodBody extends AMQBody protected abstract void writeMethodPayload(ByteBuffer buffer); - protected byte getFrameType() + public byte getFrameType() { return TYPE; } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java index 95b461b6dc..5293c00379 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java @@ -22,30 +22,21 @@ package org.apache.qpid.framing; import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; +import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; public class AMQMethodBodyFactory implements BodyFactory { private static final Logger _log = Logger.getLogger(AMQMethodBodyFactory.class); + + private final AMQVersionAwareProtocolSession _protocolSession; - private static final AMQMethodBodyFactory _instance = new AMQMethodBodyFactory(); - - public static AMQMethodBodyFactory getInstance() - { - return _instance; - } - - private AMQMethodBodyFactory() + public AMQMethodBodyFactory(AMQVersionAwareProtocolSession protocolSession) { - _log.debug("Creating method body factory"); + _protocolSession = protocolSession; } public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException { - // AMQP version change: MethodBodyDecoderRegistry is obsolete, since all the XML - // segments generated together are now handled by MainRegistry. The Cluster class, - // if generated together with amqp.xml is a part of MainRegistry. - // TODO: Connect with version acquired from ProtocolInitiation class. - return MainRegistry.get((short)in.getUnsignedShort(), (short)in.getUnsignedShort(), - (byte)8, (byte)0, in, bodySize); + return _protocolSession.getRegistry().get((short)in.getUnsignedShort(), (short)in.getUnsignedShort(), in, bodySize); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java index c0a12a9aad..cfbc9d1828 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java @@ -6,4 +6,5 @@ import org.apache.mina.common.ByteBuffer; public abstract interface AMQMethodBodyInstanceFactory { public AMQMethodBody newInstance(byte major, byte minor, ByteBuffer buffer, long size) throws AMQFrameDecodingException; + public AMQMethodBody newInstance(byte major, byte minor, int clazzID, int methodID, ByteBuffer buffer, long size) throws AMQFrameDecodingException; } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java index f536d73469..47d349a675 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java @@ -260,24 +260,14 @@ public final class AMQShortString implements CharSequence final AMQShortString otherString = (AMQShortString) o; - if(otherString.length() != length()) - { - return false; - } if((_hashCode != 0) && (otherString._hashCode != 0) && (_hashCode != otherString._hashCode)) { return false; } - final int size = length(); - for(int i = 0; i < size; i++) - { - if(_data.get(i) != otherString._data.get(i)) - { - return false; - } - } - return true; + return _data.equals(otherString._data); + + } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java index baeecaa17a..c35fc0a6c4 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java @@ -49,7 +49,7 @@ public class ContentBody extends AMQBody this.payload = payload; } - protected byte getFrameType() + public byte getFrameType() { return TYPE; } @@ -98,9 +98,7 @@ public class ContentBody extends AMQBody public static AMQFrame createAMQFrame(int channelId, ContentBody body) { - final AMQFrame frame = new AMQFrame(); - frame.channel = channelId; - frame.bodyFrame = body; + final AMQFrame frame = new AMQFrame(channelId, body); return frame; } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java index 45280bdae3..02631a5f88 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java @@ -65,7 +65,7 @@ public class ContentHeaderBody extends AMQBody this.bodySize = bodySize; } - protected byte getFrameType() + public byte getFrameType() { return TYPE; } @@ -113,17 +113,11 @@ public class ContentHeaderBody extends AMQBody public static AMQFrame createAMQFrame(int channelId, int classId, int weight, BasicContentHeaderProperties properties, long bodySize) { - final AMQFrame frame = new AMQFrame(); - frame.channel = channelId; - frame.bodyFrame = new ContentHeaderBody(classId, weight, properties, bodySize); - return frame; + return new AMQFrame(channelId, new ContentHeaderBody(classId, weight, properties, bodySize)); } public static AMQFrame createAMQFrame(int channelId, ContentHeaderBody body) { - final AMQFrame frame = new AMQFrame(); - frame.channel = channelId; - frame.bodyFrame = body; - return frame; + return new AMQFrame(channelId, body); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java index ca03f29047..7246c4a1cf 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java @@ -41,7 +41,7 @@ public class HeartbeatBody extends AMQBody } } - protected byte getFrameType() + public byte getFrameType() { return TYPE; } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java new file mode 100644 index 0000000000..9bc8232d61 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java @@ -0,0 +1,141 @@ +/* + * + * 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.framing; + +import org.apache.mina.common.ByteBuffer; +import org.apache.log4j.Logger; + +public class VersionSpecificRegistry +{ + private static final Logger _log = Logger.getLogger(VersionSpecificRegistry.class); + + + private final byte _protocolMajorVersion; + private final byte _protocolMinorVersion; + + private static final int DEFAULT_MAX_CLASS_ID = 200; + private static final int DEFAULT_MAX_METHOD_ID = 50; + + private AMQMethodBodyInstanceFactory[][] _registry = new AMQMethodBodyInstanceFactory[DEFAULT_MAX_CLASS_ID][]; + + public VersionSpecificRegistry(byte major, byte minor) + { + _protocolMajorVersion = major; + _protocolMinorVersion = minor; + } + + public byte getProtocolMajorVersion() + { + return _protocolMajorVersion; + } + + public byte getProtocolMinorVersion() + { + return _protocolMinorVersion; + } + + public AMQMethodBodyInstanceFactory getMethodBody(final short classID, final short methodID) + { + try + { + return _registry[classID][methodID]; + } + catch (IndexOutOfBoundsException e) + { + return null; + } + catch (NullPointerException e) + { + return null; + } + } + + public void registerMethod(final short classID, final short methodID, final AMQMethodBodyInstanceFactory instanceFactory) + { + if(_registry.length <= classID) + { + AMQMethodBodyInstanceFactory[][] oldRegistry = _registry; + _registry = new AMQMethodBodyInstanceFactory[classID+1][]; + System.arraycopy(oldRegistry, 0, _registry, 0, oldRegistry.length); + } + + if(_registry[classID] == null) + { + _registry[classID] = new AMQMethodBodyInstanceFactory[methodID > DEFAULT_MAX_METHOD_ID ? methodID + 1 : DEFAULT_MAX_METHOD_ID + 1]; + } + else if(_registry[classID].length <= methodID) + { + AMQMethodBodyInstanceFactory[] oldMethods = _registry[classID]; + _registry[classID] = new AMQMethodBodyInstanceFactory[methodID+1]; + System.arraycopy(oldMethods,0,_registry[classID],0,oldMethods.length); + } + + _registry[classID][methodID] = instanceFactory; + + } + + + public AMQMethodBody get(short classID, short methodID, ByteBuffer in, long size) + throws AMQFrameDecodingException + { + AMQMethodBodyInstanceFactory bodyFactory; + try + { + bodyFactory = _registry[classID][methodID]; + } + catch(NullPointerException e) + { + throw new AMQFrameDecodingException(_log, + "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion + + " (while trying to decode class " + classID + " method " + methodID + "."); + } + catch(IndexOutOfBoundsException e) + { + if(classID >= _registry.length) + { + throw new AMQFrameDecodingException(_log, + "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion + + " (while trying to decode class " + classID + " method " + methodID + "."); + + } + else + { + throw new AMQFrameDecodingException(_log, + "Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion + + " (while trying to decode class " + classID + " method " + methodID + "."); + + } + } + + + if (bodyFactory == null) + { + throw new AMQFrameDecodingException(_log, + "Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion + + " (while trying to decode class " + classID + " method " + methodID + "."); + } + + + return bodyFactory.newInstance(_protocolMajorVersion, _protocolMinorVersion, classID, methodID, in, size); + + + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java new file mode 100644 index 0000000000..a2d3de2f9e --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java @@ -0,0 +1,29 @@ +/* + * + * 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.protocol; + +import org.apache.qpid.framing.AMQDataBlock; +import org.apache.qpid.framing.VersionSpecificRegistry; + +public interface AMQVersionAwareProtocolSession extends AMQProtocolWriter, ProtocolVersionAware +{ + public VersionSpecificRegistry getRegistry(); +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java new file mode 100644 index 0000000000..64db953bc2 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java @@ -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. + * + */ +package org.apache.qpid.protocol; + +public interface ProtocolVersionAware +{ + public byte getProtocolMinorVersion(); + + public byte getProtocolMajorVersion(); +} -- cgit v1.2.1 From f7ca6dd49e6f5de6e445549ee2f1a942a6456f0c Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Mon, 29 Jan 2007 16:37:13 +0000 Subject: QPID-327 : Patch supplied by Rob Godfrey - [race condition] PoolingFilter : Possible race condition when completing a Job git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@501096 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/framing/AMQTypedValue.java | 5 +++ .../apache/qpid/framing/ProtocolInitiation.java | 10 ++++++ .../src/main/java/org/apache/qpid/pool/Job.java | 34 +++++++++--------- .../java/org/apache/qpid/pool/PoolingFilter.java | 40 +++++++++++++++------- .../org/apache/qpid/pool/ReadWriteThreadModel.java | 36 ++++++++++++++++--- .../org/apache/qpid/pool/PoolingFilterTest.java | 13 +++++-- .../java/org/apache/qpid/session/TestSession.java | 20 ++++++----- 7 files changed, 113 insertions(+), 45 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java index b29c23c2a2..e7175e7973 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java @@ -51,4 +51,9 @@ public class AMQTypedValue AMQType type = AMQTypeMap.getType(buffer.get()); return new AMQTypedValue(type, buffer); } + + public String toString() + { + return "["+getType()+": "+getValue()+"]"; + } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java index f2d1a70cdc..697a0f4249 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java @@ -164,4 +164,14 @@ public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQData protocolMajor + "." + protocolMinor + " not found in protocol version list."); } } + + public String toString() + { + StringBuffer buffer = new StringBuffer(new String(header)); + buffer.append(Integer.toHexString(protocolClass)); + buffer.append(Integer.toHexString(protocolInstance)); + buffer.append(Integer.toHexString(protocolMajor)); + buffer.append(Integer.toHexString(protocolMinor)); + return buffer.toString(); + } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java index b9673cd48f..9b3bcfa008 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java @@ -30,13 +30,13 @@ import java.util.concurrent.atomic.AtomicInteger; * Holds events for a session that will be processed asynchronously by * the thread pool in PoolingFilter. */ -class Job implements Runnable +public class Job implements Runnable { private final int _maxEvents; private final IoSession _session; private final java.util.Queue _eventQueue = new ConcurrentLinkedQueue(); private final AtomicBoolean _active = new AtomicBoolean(); - private final AtomicInteger _refCount = new AtomicInteger(); + //private final AtomicInteger _refCount = new AtomicInteger(); private final JobCompletionHandler _completionHandler; Job(IoSession session, JobCompletionHandler completionHandler, int maxEvents) @@ -45,21 +45,21 @@ class Job implements Runnable _completionHandler = completionHandler; _maxEvents = maxEvents; } - - void acquire() - { - _refCount.incrementAndGet(); - } - - void release() - { - _refCount.decrementAndGet(); - } - - boolean isReferenced() - { - return _refCount.get() > 0; - } +// +// void acquire() +// { +// _refCount.incrementAndGet(); +// } +// +// void release() +// { +// _refCount.decrementAndGet(); +// } +// +// boolean isReferenced() +// { +// return _refCount.get() > 0; +// } void add(Event evt) { diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java index c0026c1f36..073f1cdfa3 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java @@ -48,7 +48,7 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH void fireAsynchEvent(IoSession session, Event event) { Job job = getJobForSession(session); - job.acquire(); //prevents this job being removed from _jobs + // job.acquire(); //prevents this job being removed from _jobs job.add(event); //Additional checks on pool to check that it hasn't shutdown. @@ -60,10 +60,25 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH } + public void createNewJobForSession(IoSession session) + { + Job job = new Job(session, this, _maxEvents); + session.setAttribute(_name, job); + } + private Job getJobForSession(IoSession session) { - Job job = _jobs.get(session); - return job == null ? createJobForSession(session) : job; + return (Job) session.getAttribute(_name); + +/* if(job == null) + { + System.err.println("Error in " + _name); + Thread.dumpStack(); + } + + + job = _jobs.get(session); + return job == null ? createJobForSession(session) : job;*/ } private Job createJobForSession(IoSession session) @@ -81,15 +96,16 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH //Job.JobCompletionHandler public void completed(IoSession session, Job job) { - if (job.isComplete()) - { - job.release(); - if (!job.isReferenced()) - { - _jobs.remove(session); - } - } - else +// if (job.isComplete()) +// { +// job.release(); +// if (!job.isReferenced()) +// { +// _jobs.remove(session); +// } +// } +// else + if(!job.isComplete()) { // ritchiem : 2006-12-13 Do we need to perform the additional checks here? // Can the pool be shutdown at this point? diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java index 84b72bb0dc..c2f7f7ac48 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java @@ -26,12 +26,38 @@ import org.apache.mina.common.ThreadModel; public class ReadWriteThreadModel implements ThreadModel { + + private static final ReadWriteThreadModel _instance = new ReadWriteThreadModel(); + + private final PoolingFilter _asynchronousReadFilter; + private final PoolingFilter _asynchronousWriteFilter; + + private ReadWriteThreadModel() + { + final ReferenceCountingExecutorService executor = ReferenceCountingExecutorService.getInstance(); + _asynchronousReadFilter = PoolingFilter.createAynschReadPoolingFilter(executor, "AsynchronousReadFilter"); + _asynchronousWriteFilter = PoolingFilter.createAynschWritePoolingFilter(executor, "AsynchronousWriteFilter"); + } + + public PoolingFilter getAsynchronousReadFilter() + { + return _asynchronousReadFilter; + } + + public PoolingFilter getAsynchronousWriteFilter() + { + return _asynchronousWriteFilter; + } + public void buildFilterChain(IoFilterChain chain) throws Exception { - ReferenceCountingExecutorService executor = ReferenceCountingExecutorService.getInstance(); - PoolingFilter asyncRead = PoolingFilter.createAynschReadPoolingFilter(executor, "AsynchronousReadFilter"); - PoolingFilter asyncWrite = PoolingFilter.createAynschWritePoolingFilter(executor, "AsynchronousWriteFilter"); - chain.addFirst("AsynchronousReadFilter", new ReferenceCountingIoFilter(asyncRead)); - chain.addLast("AsynchronousWriteFilter", new ReferenceCountingIoFilter(asyncWrite)); + + chain.addFirst("AsynchronousReadFilter", new ReferenceCountingIoFilter(_asynchronousReadFilter)); + chain.addLast("AsynchronousWriteFilter", new ReferenceCountingIoFilter(_asynchronousWriteFilter)); + } + + public static ReadWriteThreadModel getInstance() + { + return _instance; } } diff --git a/qpid/java/common/src/test/java/org/apache/qpid/pool/PoolingFilterTest.java b/qpid/java/common/src/test/java/org/apache/qpid/pool/PoolingFilterTest.java index 9a5208662b..6383d52298 100644 --- a/qpid/java/common/src/test/java/org/apache/qpid/pool/PoolingFilterTest.java +++ b/qpid/java/common/src/test/java/org/apache/qpid/pool/PoolingFilterTest.java @@ -36,25 +36,32 @@ public class PoolingFilterTest extends TestCase public void setUp() { + //Create Pool _executorService = ReferenceCountingExecutorService.getInstance(); _executorService.acquireExecutorService(); - _pool = PoolingFilter.createAynschWritePoolingFilter(_executorService, + _pool = PoolingFilter.createAynschWritePoolingFilter(_executorService, "AsynchronousWriteFilter"); } public void testRejectedExecution() throws Exception { - _pool.filterWrite(new NoOpFilter(), new TestSession(), new IoFilter.WriteRequest("Message")); + + TestSession testSession = new TestSession(); + _pool.createNewJobForSession(testSession); + _pool.filterWrite(new NoOpFilter(), testSession, new IoFilter.WriteRequest("Message")); //Shutdown the pool _executorService.getPool().shutdownNow(); try { + + testSession = new TestSession(); + _pool.createNewJobForSession(testSession); //prior to fix for QPID-172 this would throw RejectedExecutionException - _pool.filterWrite(null, new TestSession(), null); + _pool.filterWrite(null, testSession, null); } catch (RejectedExecutionException rje) { diff --git a/qpid/java/common/src/test/java/org/apache/qpid/session/TestSession.java b/qpid/java/common/src/test/java/org/apache/qpid/session/TestSession.java index f10d55e9d0..aafc91b03b 100644 --- a/qpid/java/common/src/test/java/org/apache/qpid/session/TestSession.java +++ b/qpid/java/common/src/test/java/org/apache/qpid/session/TestSession.java @@ -24,9 +24,13 @@ import org.apache.mina.common.*; import java.net.SocketAddress; import java.util.Set; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ConcurrentHashMap; public class TestSession implements IoSession { + private final ConcurrentMap attributes = new ConcurrentHashMap(); + public TestSession() { } @@ -68,42 +72,42 @@ public class TestSession implements IoSession public Object getAttachment() { - return null; //TODO + return getAttribute(""); } public Object setAttachment(Object attachment) { - return null; //TODO + return setAttribute("",attachment); } public Object getAttribute(String key) { - return null; //TODO + return attributes.get(key); } public Object setAttribute(String key, Object value) { - return null; //TODO + return attributes.put(key,value); } public Object setAttribute(String key) { - return null; //TODO + return attributes.put(key, Boolean.TRUE); } public Object removeAttribute(String key) { - return null; //TODO + return attributes.remove(key); } public boolean containsAttribute(String key) { - return false; //TODO + return attributes.containsKey(key); } public Set getAttributeKeys() { - return null; //TODO + return attributes.keySet(); } public TransportType getTransportType() -- cgit v1.2.1 From cefb36a9533344d9f4e2524a8caec643ee41206a Mon Sep 17 00:00:00 2001 From: Martin Ritchie Date: Wed, 31 Jan 2007 17:43:45 +0000 Subject: Unused so removing git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@501920 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/qpid/util/concurrent/BooleanLatch.java | 42 ---------------------- 1 file changed, 42 deletions(-) delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java deleted file mode 100644 index 70a5f2dc5e..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * - * Copyright (c) 2006 The Apache Software Foundation - * - * Licensed 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.util.concurrent; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * @author Apache Software Foundation - */ -public class BooleanLatch extends CountDownLatch -{ - public BooleanLatch() - { - super(1); - } - - public void signal() - { - countDown(); - } - - public void await(long nanos) throws InterruptedException - { - await(nanos, TimeUnit.NANOSECONDS); - } -} -- cgit v1.2.1 From 74efb78118ccbac87face808290e2ff1e1d40f1a Mon Sep 17 00:00:00 2001 From: Bhupendra Bhusman Bhardwaj Date: Wed, 7 Feb 2007 11:27:15 +0000 Subject: QPID-170 Management feature added - moving messages from one Queue to another git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@504507 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java b/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java index c2d758611d..c4d7683a02 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java @@ -55,4 +55,16 @@ public class ConcurrentLinkedQueueAtomicSize extends ConcurrentLinkedQueue return e; } + + @Override + public boolean remove(Object o) + { + if (super.remove(o)) + { + _size.decrementAndGet(); + return true; + } + + return false; + } } -- cgit v1.2.1 From 77283ca00b07025b91eb5155ed4db165a9742a28 Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Sun, 11 Feb 2007 11:29:10 +0000 Subject: QPID-358 : Field table encoding: types i and I are the wrong way round git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@505892 13f79535-47bb-0310-9956-ffa450edef68 --- qpid/java/common/src/main/java/org/apache/qpid/framing/AMQType.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQType.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQType.java index 5175eace1e..80739e1aee 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQType.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQType.java @@ -60,7 +60,7 @@ public enum AMQType }, - INTEGER('I') + INTEGER('i') { public int getEncodingSize(Object value) @@ -478,7 +478,7 @@ public enum AMQType } }, - INT('i') + INT('I') { public int getEncodingSize(Object value) { -- cgit v1.2.1 From f7caf0b19020c0e6116620ea77423d753b8f9fe5 Mon Sep 17 00:00:00 2001 From: Martin Ritchie Date: Wed, 14 Feb 2007 15:40:47 +0000 Subject: Applied QPID-6 SSL Options patch from Kevin Smith git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@507584 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/qpid/ssl/BogusSSLContextFactory.java | 159 --------------------- .../apache/qpid/ssl/BogusTrustManagerFactory.java | 82 ----------- .../org/apache/qpid/ssl/SSLContextFactory.java | 157 ++++++++++++++++++++ .../apache/qpid/ssl/SSLServerSocketFactory.java | 108 -------------- .../java/org/apache/qpid/ssl/SSLSocketFactory.java | 138 ------------------ 5 files changed, 157 insertions(+), 487 deletions(-) delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/ssl/BogusSSLContextFactory.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/ssl/BogusTrustManagerFactory.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLContextFactory.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLServerSocketFactory.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLSocketFactory.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/ssl/BogusSSLContextFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/ssl/BogusSSLContextFactory.java deleted file mode 100644 index fee02c9d93..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/ssl/BogusSSLContextFactory.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * - * 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.ssl; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; -import java.security.KeyStore; - -/** - * Factory to create a bogus SSLContext. This means that it is easy to test SSL but this - * cannot be used in a production environment. - *

    - * This is based on the sample that comes with MINA, written by Trustin Lee - */ -public class BogusSSLContextFactory -{ - /** - * Protocol to use. - */ - private static final String PROTOCOL = "TLS"; - - /** - * Bougus Server certificate keystore file name. - */ - private static final String BOGUS_KEYSTORE = "qpid.cert"; - - // NOTE: The keystore was generated using keytool: - // keytool -genkey -alias qpid -keysize 512 -validity 3650 - // -keyalg RSA -dname "CN=amqp.org" -keypass qpidpw - // -storepass qpidpw -keystore qpid.cert - - private static final char[] BOGUS_KEYSTORE_PASSWORD = {'q', 'p', 'i', 'd', 'p', 'w'}; - - private static SSLContext serverInstance = null; - - private static SSLContext clientInstance = null; - - /** - * Get SSLContext singleton. - * - * @return SSLContext - * @throws java.security.GeneralSecurityException - */ - public static SSLContext getInstance(boolean server) - throws GeneralSecurityException - { - SSLContext retInstance; - if (server) - { - // FIXME: looks like double-checking locking - if (serverInstance == null) - { - synchronized (BogusSSLContextFactory.class) - { - if (serverInstance == null) - { - try - { - serverInstance = createBougusServerSSLContext(); - } - catch (Exception ioe) - { - throw new GeneralSecurityException( - "Can't create Server SSLContext:" + ioe); - } - } - } - } - retInstance = serverInstance; - } - else - { - // FIXME: looks like double-checking locking - if (clientInstance == null) - { - synchronized (BogusSSLContextFactory.class) - { - if (clientInstance == null) - { - clientInstance = createBougusClientSSLContext(); - } - } - } - retInstance = clientInstance; - } - return retInstance; - } - - private static SSLContext createBougusServerSSLContext() - throws GeneralSecurityException, IOException - { - // Create keystore - KeyStore ks = KeyStore.getInstance("JKS"); - InputStream in = null; - try - { - in = BogusSSLContextFactory.class.getResourceAsStream(BOGUS_KEYSTORE); - if (in == null) - { - throw new IOException("Unable to load keystore resource: " + BOGUS_KEYSTORE); - } - ks.load(in, BOGUS_KEYSTORE_PASSWORD); - } - finally - { - if (in != null) - { - //noinspection EmptyCatchBlock - try - { - in.close(); - } - catch (IOException ignored) - { - } - } - } - - // Set up key manager factory to use our key store - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, BOGUS_KEYSTORE_PASSWORD); - - // Initialize the SSLContext to work with our key managers. - SSLContext sslContext = SSLContext.getInstance(PROTOCOL); - sslContext.init(kmf.getKeyManagers(), BogusTrustManagerFactory.X509_MANAGERS, null); - - return sslContext; - } - - private static SSLContext createBougusClientSSLContext() - throws GeneralSecurityException - { - SSLContext context = SSLContext.getInstance(PROTOCOL); - context.init(null, BogusTrustManagerFactory.X509_MANAGERS, null); - return context; - } - -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/ssl/BogusTrustManagerFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/ssl/BogusTrustManagerFactory.java deleted file mode 100644 index 4fb6f75b8d..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/ssl/BogusTrustManagerFactory.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * - * 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.ssl; - -import javax.net.ssl.ManagerFactoryParameters; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactorySpi; -import javax.net.ssl.X509TrustManager; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -/** - * Bogus trust manager factory. Used to make testing SSL simpler - i.e no need to - * mess about with keystores. - *

    - * This is based on the example that comes with MINA, written by Trustin Lee. - */ -class BogusTrustManagerFactory extends TrustManagerFactorySpi -{ - - static final X509TrustManager X509 = new X509TrustManager() - { - public void checkClientTrusted(X509Certificate[] x509Certificates, - String s) throws CertificateException - { - } - - public void checkServerTrusted(X509Certificate[] x509Certificates, - String s) throws CertificateException - { - } - - public X509Certificate[] getAcceptedIssuers() - { - return new X509Certificate[ 0 ]; - } - }; - - static final TrustManager[] X509_MANAGERS = new TrustManager[]{X509}; - - public BogusTrustManagerFactory() - { - } - - protected TrustManager[] engineGetTrustManagers() - { - return X509_MANAGERS; - } - - protected void engineInit(KeyStore keystore) throws KeyStoreException - { - // noop - } - - protected void engineInit( - ManagerFactoryParameters managerFactoryParameters) - throws InvalidAlgorithmParameterException - { - // noop - } -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLContextFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLContextFactory.java new file mode 100644 index 0000000000..950279fff1 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLContextFactory.java @@ -0,0 +1,157 @@ +/* + * + * 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.ssl; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.GeneralSecurityException; +import java.security.KeyStore; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +/** + * Factory used to create SSLContexts. SSL needs to be configured + * before this will work. + * + */ +public class SSLContextFactory { + + /** + * Path to the Java keystore file + */ + private String _keystorePath; + + /** + * Password for the keystore + */ + private String _keystorePassword; + + /** + * Cert type to use + */ + private String _certType; + + /** + * Create a factory instance + * @param keystorePath path to the Java keystore file + * @param keystorePassword password for the Java keystore + * @param certType certificate type + */ + public SSLContextFactory(String keystorePath, String keystorePassword, + String certType) + { + _keystorePath = keystorePath; + _keystorePassword = keystorePassword; + if (_keystorePassword.equals("none")) + { + _keystorePassword = null; + } + _certType = certType; + if (keystorePath == null) { + throw new IllegalArgumentException("Keystore path must be specified"); + } + if (certType == null) { + throw new IllegalArgumentException("Cert type must be specified"); + } + } + + /** + * Builds a SSLContext appropriate for use with a server + * @return SSLContext + * @throws GeneralSecurityException + * @throws IOException + */ + public SSLContext buildServerContext() throws GeneralSecurityException, IOException + { + // Create keystore + KeyStore ks = getInitializedKeyStore(); + + // Set up key manager factory to use our key store + KeyManagerFactory kmf = KeyManagerFactory.getInstance(_certType); + kmf.init(ks, _keystorePassword.toCharArray()); + + // Initialize the SSLContext to work with our key managers. + SSLContext sslContext = SSLContext.getInstance("TLS"); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(_certType); + tmf.init(ks); + sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + + return sslContext; + } + + /** + * Creates a SSLContext factory appropriate for use with a client + * @return SSLContext + * @throws GeneralSecurityException + * @throws IOException + */ + public SSLContext buildClientContext() throws GeneralSecurityException, IOException + { + KeyStore ks = getInitializedKeyStore(); + TrustManagerFactory tmf = TrustManagerFactory.getInstance(_certType); + tmf.init(ks); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, tmf.getTrustManagers(), null); + return context; + } + + private KeyStore getInitializedKeyStore() throws GeneralSecurityException, IOException + { + KeyStore ks = KeyStore.getInstance("JKS"); + InputStream in = null; + try + { + File f = new File(_keystorePath); + if (f.exists()) + { + in = new FileInputStream(f); + } + else + { + in = Thread.currentThread().getContextClassLoader().getResourceAsStream(_keystorePath); + } + if (in == null) + { + throw new IOException("Unable to load keystore resource: " + _keystorePath); + } + ks.load(in, _keystorePassword.toCharArray()); + } + finally + { + if (in != null) + { + //noinspection EmptyCatchBlock + try + { + in.close(); + } + catch (IOException ignored) + { + } + } + } + return ks; + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLServerSocketFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLServerSocketFactory.java deleted file mode 100644 index 90b3589752..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLServerSocketFactory.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * - * 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.ssl; - -import javax.net.ServerSocketFactory; -import java.io.IOException; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.security.GeneralSecurityException; - -/** - * Simple Server Socket factory to create sockets with or without SSL enabled. - * If SSL enabled a "bogus" SSL Context is used (suitable for test purposes) - *

    - * This is based on the example that comes with MINA, written by Trustin Lee. - */ -public class SSLServerSocketFactory extends javax.net.ServerSocketFactory -{ - private static boolean sslEnabled = false; - - private static javax.net.ServerSocketFactory sslFactory = null; - - private static ServerSocketFactory factory = null; - - public SSLServerSocketFactory() - { - super(); - } - - public ServerSocket createServerSocket(int port) throws IOException - { - return new ServerSocket(port); - } - - public ServerSocket createServerSocket(int port, int backlog) - throws IOException - { - return new ServerSocket(port, backlog); - } - - public ServerSocket createServerSocket(int port, int backlog, - InetAddress ifAddress) - throws IOException - { - return new ServerSocket(port, backlog, ifAddress); - } - - public static javax.net.ServerSocketFactory getServerSocketFactory() - throws IOException - { - if (isSslEnabled()) - { - if (sslFactory == null) - { - try - { - sslFactory = BogusSSLContextFactory.getInstance(true) - .getServerSocketFactory(); - } - catch (GeneralSecurityException e) - { - IOException ioe = new IOException( - "could not create SSL socket"); - ioe.initCause(e); - throw ioe; - } - } - return sslFactory; - } - else - { - if (factory == null) - { - factory = new SSLServerSocketFactory(); - } - return factory; - } - - } - - public static boolean isSslEnabled() - { - return sslEnabled; - } - - public static void setSslEnabled(boolean newSslEnabled) - { - sslEnabled = newSslEnabled; - } -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLSocketFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLSocketFactory.java deleted file mode 100644 index ef9820f067..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/ssl/SSLSocketFactory.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * - * 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.ssl; - -import javax.net.SocketFactory; -import java.io.IOException; -import java.net.InetAddress; -import java.net.Socket; -import java.net.UnknownHostException; -import java.security.GeneralSecurityException; - -/** - * Simple Socket factory to create sockets with or without SSL enabled. - * If SSL enabled a "bogus" SSL Context is used (suitable for test purposes). - *

    - * This is based on an example that comes with MINA, written by Trustin Lee. - */ -public class SSLSocketFactory extends SocketFactory -{ - private static boolean sslEnabled = false; - - private static javax.net.ssl.SSLSocketFactory sslFactory = null; - - private static javax.net.SocketFactory factory = null; - - public SSLSocketFactory() - { - super(); - } - - public Socket createSocket(String arg1, int arg2) throws IOException, - UnknownHostException - { - if (isSslEnabled()) - { - return getSSLFactory().createSocket(arg1, arg2); - } - else - { - return new Socket(arg1, arg2); - } - } - - public Socket createSocket(String arg1, int arg2, InetAddress arg3, - int arg4) throws IOException, - UnknownHostException - { - if (isSslEnabled()) - { - return getSSLFactory().createSocket(arg1, arg2, arg3, arg4); - } - else - { - return new Socket(arg1, arg2, arg3, arg4); - } - } - - public Socket createSocket(InetAddress arg1, int arg2) - throws IOException - { - if (isSslEnabled()) - { - return getSSLFactory().createSocket(arg1, arg2); - } - else - { - return new Socket(arg1, arg2); - } - } - - public Socket createSocket(InetAddress arg1, int arg2, InetAddress arg3, - int arg4) throws IOException - { - if (isSslEnabled()) - { - return getSSLFactory().createSocket(arg1, arg2, arg3, arg4); - } - else - { - return new Socket(arg1, arg2, arg3, arg4); - } - } - - public static javax.net.SocketFactory getSocketFactory() - { - if (factory == null) - { - factory = new SSLSocketFactory(); - } - return factory; - } - - private javax.net.ssl.SSLSocketFactory getSSLFactory() - { - if (sslFactory == null) - { - try - { - sslFactory = BogusSSLContextFactory.getInstance(false) - .getSocketFactory(); - } - catch (GeneralSecurityException e) - { - throw new RuntimeException("could not create SSL socket", e); - } - } - return sslFactory; - } - - public static boolean isSslEnabled() - { - return sslEnabled; - } - - public static void setSslEnabled(boolean newSslEnabled) - { - sslEnabled = newSslEnabled; - } - -} -- cgit v1.2.1 From 763fe9005de09a9983ccc903f323f3d4953d044c Mon Sep 17 00:00:00 2001 From: Martin Ritchie Date: Wed, 14 Feb 2007 16:06:18 +0000 Subject: Applied QPID-162 patches from Kevin Smith git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@507595 13f79535-47bb-0310-9956-ffa450edef68 --- .../src/main/java/org/apache/qpid/AMQChannelException.java | 2 +- .../src/main/java/org/apache/qpid/codec/AMQEncoder.java | 2 +- .../src/main/java/org/apache/qpid/common/QpidProperties.java | 8 ++++---- .../main/java/org/apache/qpid/configuration/Configured.java | 2 +- .../org/apache/qpid/configuration/PropertyException.java | 2 +- .../java/org/apache/qpid/framing/AMQDataBlockDecoder.java | 3 --- .../java/org/apache/qpid/framing/AMQDataBlockEncoder.java | 7 +++---- .../main/java/org/apache/qpid/framing/AMQShortString.java | 4 +--- .../src/main/java/org/apache/qpid/framing/AMQTypeMap.java | 2 +- .../src/main/java/org/apache/qpid/framing/EncodingUtils.java | 4 ++-- .../src/main/java/org/apache/qpid/framing/FieldTable.java | 10 ++++++++-- .../org/apache/qpid/framing/VersionSpecificRegistry.java | 2 +- .../common/src/main/java/org/apache/qpid/pool/Event.java | 2 -- qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java | 5 ++--- .../src/main/java/org/apache/qpid/pool/PoolingFilter.java | 8 ++++---- .../main/java/org/apache/qpid/pool/ReadWriteThreadModel.java | 2 +- .../src/main/java/org/apache/qpid/protocol/AMQConstant.java | 6 +++--- .../java/org/apache/qpid/protocol/AMQMethodListener.java | 1 + .../apache/qpid/protocol/AMQVersionAwareProtocolSession.java | 1 - .../src/main/java/org/apache/qpid/url/AMQBindingURL.java | 12 +++++------- 20 files changed, 40 insertions(+), 45 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java index 9255590afb..d1750ebbb5 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java @@ -20,9 +20,9 @@ */ package org.apache.qpid; -import org.apache.qpid.framing.ChannelCloseBody; import org.apache.qpid.framing.AMQFrame; import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.ChannelCloseBody; public class AMQChannelException extends AMQException { diff --git a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQEncoder.java b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQEncoder.java index ad252aec35..fdb2e60c62 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQEncoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQEncoder.java @@ -20,9 +20,9 @@ */ package org.apache.qpid.codec; +import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderOutput; -import org.apache.mina.common.IoSession; import org.apache.qpid.framing.AMQDataBlockEncoder; public class AMQEncoder implements ProtocolEncoder diff --git a/qpid/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java index f4f764db1b..80377ffdf5 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java @@ -20,12 +20,12 @@ */ package org.apache.qpid.common; -import org.apache.log4j.Logger; - -import java.util.Properties; -import java.util.Map; import java.io.IOException; import java.io.InputStream; +import java.util.Map; +import java.util.Properties; + +import org.apache.log4j.Logger; public class QpidProperties { diff --git a/qpid/java/common/src/main/java/org/apache/qpid/configuration/Configured.java b/qpid/java/common/src/main/java/org/apache/qpid/configuration/Configured.java index 2160dd6295..7d2e7d3a5d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/configuration/Configured.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/configuration/Configured.java @@ -20,9 +20,9 @@ */ package org.apache.qpid.configuration; +import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** diff --git a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java index 12eebbf2b0..67af0b0b74 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java @@ -20,8 +20,8 @@ */ package org.apache.qpid.configuration; -import org.apache.qpid.AMQException; import org.apache.log4j.Logger; +import org.apache.qpid.AMQException; /** * Indicates an error parsing a property expansion. diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java index e426651588..43f888c029 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java @@ -26,9 +26,6 @@ import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; -import java.util.HashMap; -import java.util.Map; - public class AMQDataBlockDecoder { private static final String SESSION_METHOD_BODY_FACTORY = "QPID_SESSION_METHOD_BODY_FACTORY"; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java index 478cdeb406..aedea6dd89 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java @@ -20,16 +20,15 @@ */ package org.apache.qpid.framing; +import java.util.Collections; +import java.util.Set; + import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; -import java.util.HashSet; -import java.util.Set; -import java.util.Collections; - public final class AMQDataBlockEncoder implements MessageEncoder { private static final Logger _logger = Logger.getLogger(AMQDataBlockEncoder.class); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java index 47d349a675..f51296dafc 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java @@ -1,9 +1,7 @@ package org.apache.qpid.framing; -import org.apache.mina.common.ByteBuffer; import org.apache.log4j.Logger; - -import java.util.Arrays; +import org.apache.mina.common.ByteBuffer; /** * A short string is a representation of an AMQ Short String diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQTypeMap.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQTypeMap.java index 5ac7f8827b..1419dd75b1 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQTypeMap.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQTypeMap.java @@ -20,8 +20,8 @@ */ package org.apache.qpid.framing; -import java.util.Map; import java.util.HashMap; +import java.util.Map; public class AMQTypeMap { diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java index 339f83588d..4e3768e4d4 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java @@ -20,11 +20,11 @@ */ package org.apache.qpid.framing; +import java.nio.charset.Charset; + import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; -import java.nio.charset.Charset; - public class EncodingUtils { private static final Logger _logger = Logger.getLogger(EncodingUtils.class); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java index 1a72910536..246e5ebc90 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java @@ -20,12 +20,18 @@ */ package org.apache.qpid.framing; +import java.util.Collections; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; import org.apache.qpid.AMQPInvalidClassException; -import java.util.*; - //extends FieldTable public class FieldTable { diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java index 9bc8232d61..1df62c7b1b 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java @@ -20,8 +20,8 @@ */ package org.apache.qpid.framing; -import org.apache.mina.common.ByteBuffer; import org.apache.log4j.Logger; +import org.apache.mina.common.ByteBuffer; public class VersionSpecificRegistry { diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/Event.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/Event.java index 43ff8f6a19..09890a103d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/Event.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/Event.java @@ -20,10 +20,8 @@ */ package org.apache.qpid.pool; -import org.apache.log4j.Logger; import org.apache.mina.common.IoFilter; import org.apache.mina.common.IoSession; -import org.apache.mina.common.IdleStatus; abstract public class Event diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java index 9b3bcfa008..1dafdaf4fd 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java @@ -20,11 +20,10 @@ */ package org.apache.qpid.pool; -import org.apache.mina.common.IoSession; - import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.mina.common.IoSession; /** * Holds events for a session that will be processed asynchronously by diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java index 073f1cdfa3..8126ca4bc8 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java @@ -20,15 +20,14 @@ */ package org.apache.qpid.pool; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + import org.apache.log4j.Logger; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoSession; -import java.util.EnumSet; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionHandler { private static final Logger _logger = Logger.getLogger(PoolingFilter.class); @@ -240,3 +239,4 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH } + diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java index c2f7f7ac48..278a569715 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java @@ -21,8 +21,8 @@ package org.apache.qpid.pool; import org.apache.mina.common.IoFilterChain; -import org.apache.mina.filter.ReferenceCountingIoFilter; import org.apache.mina.common.ThreadModel; +import org.apache.mina.filter.ReferenceCountingIoFilter; public class ReadWriteThreadModel implements ThreadModel { diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java index 523a24f278..a4d90e9ee3 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java @@ -20,10 +20,10 @@ */ package org.apache.qpid.protocol; -import org.apache.qpid.framing.AMQShortString; - -import java.util.Map; import java.util.HashMap; +import java.util.Map; + +import org.apache.qpid.framing.AMQShortString; public final class AMQConstant { diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java index f77b5084f3..85bbe50b11 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java @@ -20,6 +20,7 @@ */ package org.apache.qpid.protocol; +import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQMethodBody; /** diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java index a2d3de2f9e..b57c26e496 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java @@ -20,7 +20,6 @@ */ package org.apache.qpid.protocol; -import org.apache.qpid.framing.AMQDataBlock; import org.apache.qpid.framing.VersionSpecificRegistry; public interface AMQVersionAwareProtocolSession extends AMQProtocolWriter, ProtocolVersionAware diff --git a/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java b/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java index 11e6652bd7..04d152acf5 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java @@ -20,14 +20,12 @@ */ package org.apache.qpid.url; -import org.apache.qpid.url.BindingURL; -import org.apache.qpid.url.URLHelper; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; - -import java.util.HashMap; import java.net.URI; import java.net.URISyntaxException; +import java.util.HashMap; + +import org.apache.qpid.exchange.ExchangeDefaults; +import org.apache.qpid.framing.AMQShortString; public class AMQBindingURL implements BindingURL { @@ -281,4 +279,4 @@ public class AMQBindingURL implements BindingURL } -} \ No newline at end of file +} -- cgit v1.2.1 From 55235ce6194939a8bc9cb50df1732e97e20303ba Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Thu, 15 Feb 2007 23:23:48 +0000 Subject: QPID-366 : Reference counting not being decremented correctly and other persistence issues git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@508235 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/url/AMQBindingURL.java | 53 ++++++++++++++-------- .../main/java/org/apache/qpid/url/BindingURL.java | 12 ----- .../main/java/org/apache/qpid/url/URLHelper.java | 12 ++--- 3 files changed, 41 insertions(+), 36 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java b/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java index 04d152acf5..2ee4ce21cb 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java @@ -26,9 +26,12 @@ import java.util.HashMap; import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.framing.AMQShortString; +import org.apache.log4j.Logger; public class AMQBindingURL implements BindingURL { + private static final Logger _logger = Logger.getLogger(AMQBindingURL.class); + String _url; AMQShortString _exchangeClass; AMQShortString _exchangeName; @@ -41,7 +44,7 @@ public class AMQBindingURL implements BindingURL { //format: // :///[]/[]?

    + *
    CRC Card
    Responsibilities Collaborations + *
    Read a text file as a string. + *
    Open a file or default resource as an input stream. + *
    + */ +public class FileUtils +{ + /** + * Reads a text file as a string. + * + * @param filename The name of the file. + * + * @return The contents of the file. + */ + public static String readFileAsString(String filename) + { + BufferedInputStream is = null; + + try + { + is = new BufferedInputStream(new FileInputStream(filename)); + } + catch (FileNotFoundException e) + { + throw new RuntimeException(e); + } + + return readStreamAsString(is); + } + + /** + * Reads a text file as a string. + * + * @param file The file. + * + * @return The contents of the file. + */ + public static String readFileAsString(File file) + { + BufferedInputStream is = null; + + try + { + is = new BufferedInputStream(new FileInputStream(file)); + } + catch (FileNotFoundException e) + { + throw new RuntimeException(e); + } + + return readStreamAsString(is); + } + + /** + * Reads the contents of a reader, one line at a time until the end of stream is encountered, and returns all + * together as a string. + * + * @param is The reader. + * + * @return The contents of the reader. + */ + private static String readStreamAsString(BufferedInputStream is) + { + try + { + byte[] data = new byte[4096]; + + StringBuffer inBuffer = new StringBuffer(); + + String line; + int read; + + while ((read = is.read(data)) != -1) + { + String s = new String(data, 0, read); + inBuffer.append(s); + } + + return inBuffer.toString(); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + } + + /** + * Either opens the specified filename as an input stream, or uses the default resource loaded using the + * specified class loader, if opening the file fails or no file name is specified. + * + * @param filename The name of the file to open. + * @param defaultResource The name of the default resource on the classpath if the file cannot be opened. + * @param cl The classloader to load the default resource with. + * + * @return An input stream for the file or resource, or null if one could not be opened. + */ + public static InputStream openFileOrDefaultResource(String filename, String defaultResource, ClassLoader cl) + { + InputStream is = null; + + // Flag to indicate whether the default resource should be used. By default this is true, so that the default + // is used when opening the file fails. + boolean useDefault = true; + + // Try to open the file if one was specified. + if (filename != null) + { + try + { + is = new BufferedInputStream(new FileInputStream(new File(filename))); + + // Clear the default flag because the file was succesfully opened. + useDefault = false; + } + catch (FileNotFoundException e) + { + // Ignore this exception, the default will be used instead. + } + } + + // Load the default resource if a file was not specified, or if opening the file failed. + if (useDefault) + { + is = cl.getResourceAsStream(defaultResource); + } + + return is; + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java new file mode 100644 index 0000000000..faeb9d7167 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java @@ -0,0 +1,73 @@ +/* + * + * 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.util; + +/** + * Contains pretty printing convenienve methods for producing formatted logging output, mostly for debugging purposes. + * + *

    + *
    CRC Card
    Responsibilities Collaborations + *
    + */ +public class PrettyPrintingUtils +{ + /** + * Pretty prints an array of ints as a string. + * + * @param array The array to pretty print. + * + * @return The pretty printed string. + */ + public static String printArray(int[] array) + { + String result = "["; + for (int i = 0; i < array.length; i++) + { + result += array[i]; + result += (i < (array.length - 1)) ? ", " : ""; + } + + result += "]"; + + return result; + } + + /** + * Pretty prints an array of strings as a string. + * + * @param array The array to pretty print. + * + * @return The pretty printed string. + */ + public static String printArray(String[] array) + { + String result = "["; + for (int i = 0; i < array.length; i++) + { + result += array[i]; + result += (i < (array.length - 1)) ? ", " : ""; + } + + result += "]"; + + return result; + } +} -- cgit v1.2.1 From 38ec33821fd6e1c01e32a398607ec3faae4f1226 Mon Sep 17 00:00:00 2001 From: Martin Ritchie Date: Fri, 23 Feb 2007 10:20:44 +0000 Subject: QPID-346 Message loss after rollback QPID-348 Problems of prefetching messages QPID-355 Closing a consumer does not ensure messages delivery will stop for that subscription BROKER AMQChannel - updated requeue to either resend via the Delivery Manager not directly via msg.writedeliver. BasicRejectMethodHandler - initial place holder. TxRollbackHandler - Added comment AMQMessage - added ability to record who has taken the message so that it can be resent to that subscriber on resend/requeue. AMQQueue - added the queue reference to the Subscription creation ConcurrentSelectorDeliveryManager - Added methods to correctly monitor the size of queue messages. Including messages on the resend queue of a Subscriber. Additional locking to ensure that messages are not sent to the subscriber after Closure. QPID-355 DeliveryManager - adjusted deliver call to allow delivery to the head of the queue. Subscription - changes to allow selction of queue(resend or predelivery) methods to add to resend and getSendLock to ensure that sending to the Subscription is allowed. SubscriptionFactory - changes to allow the AMQQueue to be passed to the Subscription. SubscriptionImpl - implementation of the interfaces. Local storage of messages to be resent and requeuing of the messages during closure. SubscriptionSet - changes to retrieve the actual stored Subscription when performing removeSubscriber. So we have access to the the resend queue. AMQStateManager - Added BasicRejectMethodHandler TransactionalContext - Added option to deliver the messages to the front of the queue. LocalTransactionalContext - cleared the _postComitDeliveryList on rollback. Added option to deliver the messages to the front of the queue. NonTransactionalContext - Added option to deliver the messages to the front of the queue. DeliverMessageOperation.java DELELTED AS NOT USED. CLIENT AMQSession - added ability to get the pervious state of the dispatcher when settting Stopped, fixed the channel suspension problems on broker so uncommented clean up code in rollback and recover. BasicMessageConsumer - updated the rollback so that it sends reject messages to server. AbstractJMSMessage - whitespace + added extra message properties to the toString() AMQProtocolHandler - whitespace + extra debug output TransactedTest - updated expect to prevent NPEs also added extra logging to help understand what is going on. CLUSTER ClusteredQueue - AMQQueue changes for message deliveryFirst. RemoteSubscriptionImpl - Implementation of Subscription SYSTESTS AbstractHeadersExchangeTestBase - AMQQueue changes for message deliveryFirst. AMQQueueMBeanTest - changes for message deliveryFirst. ConcurrencyTest - changes for message deliveryFirst. DeliveryManagerTest - changes for message deliveryFirst. SubscriptionTestHelper - Implementation of Subscription WhiteSpace only UnacknowledgedMessageMapImpl.java git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@510897 13f79535-47bb-0310-9956-ffa450edef68 --- .../ConcurrentLinkedMessageQueueAtomicSize.java | 197 +++++++++++++++++++++ .../java/org/apache/qpid/util/MessageQueue.java | 30 ++++ 2 files changed, 227 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/MessageQueue.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java b/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java new file mode 100644 index 0000000000..cdf686b4cb --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.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.util; + +import org.apache.log4j.Logger; + +import java.util.Queue; +import java.util.Collection; +import java.util.Iterator; +import java.util.concurrent.atomic.AtomicInteger; + +public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQueueAtomicSize implements MessageQueue +{ + private static final Logger _logger = Logger.getLogger(ConcurrentLinkedMessageQueueAtomicSize.class); + + protected Queue _messageHead = new ConcurrentLinkedQueueAtomicSize(); + + protected AtomicInteger _messageHeadSize = new AtomicInteger(0); + + @Override + public int size() + { + return super.size() + _messageHeadSize.get(); + } + + @Override + public E poll() + { + if (_messageHead.isEmpty()) + { + return super.poll(); + } + else + { + _logger.debug("Providing item from message head"); + + E e = _messageHead.poll(); + + if (e != null) + { + _messageHeadSize.decrementAndGet(); + } + + return e; + } + } + + @Override + public boolean remove(Object o) + { + + if (_messageHead.isEmpty()) + { + return super.remove(o); + } + else + { + if (_messageHead.remove(o)) + { + _messageHeadSize.decrementAndGet(); + return true; + } + + return super.remove(o); + } + } + + @Override + public boolean removeAll(Collection c) + { + if (_messageHead.isEmpty()) + { + return super.removeAll(c); + } + else + { + //fixme this is super.removeAll but iterator here doesn't work + // we need to be able to correctly decrement _messageHeadSize +// boolean modified = false; +// Iterator e = iterator(); +// while (e.hasNext()) +// { +// if (c.contains(e.next())) +// { +// e.remove(); +// modified = true; +// _size.decrementAndGet(); +// } +// } +// return modified; + + throw new RuntimeException("Not implemented"); + } + } + + + @Override + public boolean isEmpty() + { + return (_messageHead.isEmpty() && super.isEmpty()); + } + + @Override + public void clear() + { + super.clear(); + _messageHead.clear(); + } + + @Override + public boolean contains(Object o) + { + return _messageHead.contains(o) || super.contains(o); + } + + @Override + public boolean containsAll(Collection o) + { + return _messageHead.containsAll(o) || super.containsAll(o); + } + + @Override + public E element() + { + if (_messageHead.isEmpty()) + { + return super.element(); + } + else + { + return _messageHead.element(); + } + } + + @Override + public E peek() + { + if (_messageHead.isEmpty()) + { + return super.peek(); + } + else + { + _logger.debug("Providing item from message head"); + return _messageHead.peek(); + } + + } + + @Override + public Iterator iterator() + { + throw new RuntimeException("Not Implemented"); + + } + + @Override + public boolean retainAll(Collection c) + { + throw new RuntimeException("Not Implemented"); + } + + @Override + public Object[] toArray() + { + throw new RuntimeException("Not Implemented"); + } + + public boolean pushHead(E o) + { + _logger.debug("Adding item to head of queue"); + if (_messageHead.offer(o)) + { + _messageHeadSize.incrementAndGet(); + return true; + } + return false; + } +} \ No newline at end of file diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/MessageQueue.java b/qpid/java/common/src/main/java/org/apache/qpid/util/MessageQueue.java new file mode 100644 index 0000000000..9cf3319374 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/MessageQueue.java @@ -0,0 +1,30 @@ +/* + * 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.util; + +import java.util.Queue; + +public interface MessageQueue extends Queue +{ + + boolean pushHead(E o); + +} -- cgit v1.2.1 From 2e9743ac06fc05609155769bf04f4fa442d848c2 Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Sun, 25 Feb 2007 01:08:57 +0000 Subject: QPID-391 : Broker Refactoring - initial tidy... add some mechanisms for multi version git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@511389 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/framing/AMQMethodBody.java | 6 +- .../qpid/framing/BasicContentHeaderProperties.java | 125 ++++++++++++++--- .../framing/CommonContentHeaderProperties.java | 65 +++++++++ .../java/org/apache/qpid/framing/FieldTable.java | 68 ++++++++- .../apache/qpid/framing/ProtocolInitiation.java | 155 ++++++++++++--------- .../framing/BasicContentHeaderPropertiesTest.java | 20 ++- 6 files changed, 330 insertions(+), 109 deletions(-) create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java index 111d9a8f20..f2e91083ca 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java @@ -86,9 +86,9 @@ public abstract class AMQMethodBody extends AMQBody public String toString() { - StringBuffer buf = new StringBuffer(getClass().toString()); - buf.append(" Class: ").append(getClazz()); - buf.append(" Method: ").append(getMethod()); + StringBuffer buf = new StringBuffer(getClass().getName()); + buf.append("[ Class: ").append(getClazz()); + buf.append(" Method: ").append(getMethod()).append(']'); return buf.toString(); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java index 1045b02868..8b784fa3f7 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java @@ -24,7 +24,7 @@ import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; -public class BasicContentHeaderProperties implements ContentHeaderProperties +public class BasicContentHeaderProperties implements CommonContentHeaderProperties { private static final Logger _logger = Logger.getLogger(BasicContentHeaderProperties.class); @@ -421,14 +421,14 @@ public class BasicContentHeaderProperties implements ContentHeaderProperties } } - public AMQShortString getContentTypeShortString() + public AMQShortString getContentType() { decodeContentTypeIfNecessary(); return _contentType; } - public String getContentType() + public String getContentTypeAsString() { decodeContentTypeIfNecessary(); return _contentType == null ? null : _contentType.toString(); @@ -444,15 +444,19 @@ public class BasicContentHeaderProperties implements ContentHeaderProperties public void setContentType(String contentType) { - clearEncodedForm(); - _propertyFlags |= (1 << 15); - _contentType = contentType == null ? null : new AMQShortString(contentType); + setContentType(contentType == null ? null : new AMQShortString(contentType)); + } + + public String getEncodingAsString() + { + + return getEncoding() == null ? null : getEncoding().toString(); } - public String getEncoding() + public AMQShortString getEncoding() { decodeIfNecessary(); - return _encoding == null ? null : _encoding.toString(); + return _encoding; } public void setEncoding(String encoding) @@ -462,6 +466,14 @@ public class BasicContentHeaderProperties implements ContentHeaderProperties _encoding = encoding == null ? null : new AMQShortString(encoding); } + public void setEncoding(AMQShortString encoding) + { + clearEncodedForm(); + _propertyFlags |= (1 << 14); + _encoding = encoding; + } + + public FieldTable getHeaders() { decodeHeadersIfNecessary(); @@ -508,26 +520,37 @@ public class BasicContentHeaderProperties implements ContentHeaderProperties _priority = priority; } - public String getCorrelationId() + public AMQShortString getCorrelationId() + { + decodeIfNecessary(); + return _correlationId; + } + + public String getCorrelationIdAsString() { decodeIfNecessary(); return _correlationId == null ? null : _correlationId.toString(); } public void setCorrelationId(String correlationId) + { + setCorrelationId(correlationId == null ? null : new AMQShortString(correlationId)); + } + + public void setCorrelationId(AMQShortString correlationId) { clearEncodedForm(); _propertyFlags |= (1 << 10); - _correlationId = correlationId == null ? null : new AMQShortString(correlationId); + _correlationId = correlationId; } - public String getReplyTo() + public String getReplyToAsString() { decodeIfNecessary(); return _replyTo == null ? null : _replyTo.toString(); } - public AMQShortString getReplyToAsShortString() + public AMQShortString getReplyTo() { decodeIfNecessary(); return _replyTo; @@ -561,7 +584,13 @@ public class BasicContentHeaderProperties implements ContentHeaderProperties } - public String getMessageId() + public AMQShortString getMessageId() + { + decodeIfNecessary(); + return _messageId; + } + + public String getMessageIdAsString() { decodeIfNecessary(); return _messageId == null ? null : _messageId.toString(); @@ -574,6 +603,14 @@ public class BasicContentHeaderProperties implements ContentHeaderProperties _messageId = messageId == null ? null : new AMQShortString(messageId); } + public void setMessageId(AMQShortString messageId) + { + clearEncodedForm(); + _propertyFlags |= (1 << 7); + _messageId = messageId; + } + + public long getTimestamp() { decodeIfNecessary(); @@ -587,56 +624,102 @@ public class BasicContentHeaderProperties implements ContentHeaderProperties _timestamp = timestamp; } - public String getType() + public String getTypeAsString() { decodeIfNecessary(); return _type == null ? null : _type.toString(); } + + public AMQShortString getType() + { + decodeIfNecessary(); + return _type; + } + + public void setType(String type) + { + setType(type == null ? null : new AMQShortString(type)); + } + + public void setType(AMQShortString type) { clearEncodedForm(); _propertyFlags |= (1 << 5); - _type = type == null ? null : new AMQShortString(type); + _type = type; } - public String getUserId() + public String getUserIdAsString() { decodeIfNecessary(); return _userId == null ? null : _userId.toString(); } + public AMQShortString getUserId() + { + decodeIfNecessary(); + return _userId; + } + public void setUserId(String userId) + { + setUserId(userId == null ? null : new AMQShortString(userId)); + } + + public void setUserId(AMQShortString userId) { clearEncodedForm(); _propertyFlags |= (1 << 4); - _userId = userId == null ? null : new AMQShortString(userId); + _userId = userId; } - public String getAppId() + public String getAppIdAsString() { decodeIfNecessary(); return _appId == null ? null : _appId.toString(); } + public AMQShortString getAppId() + { + decodeIfNecessary(); + return _appId; + } + public void setAppId(String appId) + { + setAppId(appId == null ? null : new AMQShortString(appId)); + } + + public void setAppId(AMQShortString appId) { clearEncodedForm(); _propertyFlags |= (1 << 3); - _appId = appId == null ? null : new AMQShortString(appId); + _appId = appId; } - public String getClusterId() + public String getClusterIdAsString() { decodeIfNecessary(); return _clusterId == null ? null : _clusterId.toString(); } + public AMQShortString getClusterId() + { + decodeIfNecessary(); + return _clusterId; + } + public void setClusterId(String clusterId) + { + setClusterId(clusterId == null ? null : new AMQShortString(clusterId)); + } + + public void setClusterId(AMQShortString clusterId) { clearEncodedForm(); _propertyFlags |= (1 << 2); - _clusterId = clusterId == null ? null : new AMQShortString(clusterId); + _clusterId = clusterId; } public String toString() diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java new file mode 100644 index 0000000000..1641cbf4e8 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java @@ -0,0 +1,65 @@ +package org.apache.qpid.framing; + +import org.apache.mina.common.ByteBuffer; + +import org.apache.log4j.Logger; + +public interface CommonContentHeaderProperties extends ContentHeaderProperties +{ + + AMQShortString getContentType(); + + void setContentType(AMQShortString contentType); + + FieldTable getHeaders(); + + void setHeaders(FieldTable headers); + + byte getDeliveryMode(); + + void setDeliveryMode(byte deliveryMode); + + byte getPriority(); + + void setPriority(byte priority); + + AMQShortString getCorrelationId(); + + void setCorrelationId(AMQShortString correlationId); + + AMQShortString getReplyTo(); + + void setReplyTo(AMQShortString replyTo); + + long getExpiration(); + + void setExpiration(long expiration); + + AMQShortString getMessageId(); + + void setMessageId(AMQShortString messageId); + + long getTimestamp(); + + void setTimestamp(long timestamp); + + AMQShortString getType(); + + void setType(AMQShortString type); + + AMQShortString getUserId(); + + void setUserId(AMQShortString userId); + + AMQShortString getAppId(); + + void setAppId(AMQShortString appId); + + AMQShortString getClusterId(); + + void setClusterId(AMQShortString clusterId); + + AMQShortString getEncoding(); + + void setEncoding(AMQShortString encoding); +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java index 246e5ebc90..a7544c5747 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java @@ -41,10 +41,14 @@ public class FieldTable private LinkedHashMap _properties; private long _encodedSize; private static final int INITIAL_HASHMAP_CAPACITY = 16; + private static final int INITIAL_ENCODED_FORM_SIZE = 256; public FieldTable() { super(); +// _encodedForm = ByteBuffer.allocate(INITIAL_ENCODED_FORM_SIZE); +// _encodedForm.setAutoExpand(true); +// _encodedForm.limit(0); } /** @@ -109,11 +113,28 @@ public class FieldTable private AMQTypedValue setProperty(AMQShortString key, AMQTypedValue val) { initMapIfNecessary(); - _encodedForm = null; - if(val == null) + if(_properties.containsKey(key)) + { + _encodedForm = null; + + if(val == null) + { + return removeKey(key); + } + } + else if(_encodedForm != null && val != null) + { + EncodingUtils.writeShortStringBytes(_encodedForm, key); + val.writeToBuffer(_encodedForm); + + } + else if (val == null) { - return removeKey(key); + return null; } + + + AMQTypedValue oldVal = _properties.put(key,val); if(oldVal != null) { @@ -134,7 +155,7 @@ public class FieldTable { if(_properties == null) { - if(_encodedForm == null) + if(_encodedForm == null || _encodedSize == 0) { _properties = new LinkedHashMap(); } @@ -655,6 +676,7 @@ public class FieldTable if (trace) { _logger.trace("FieldTable::writeToBuffer: Writing encoded length of " + getEncodedSize() + "..."); + _logger.trace(_properties); } EncodingUtils.writeUnsignedInteger(buffer, getEncodedSize()); @@ -701,6 +723,7 @@ public class FieldTable public void addAll(FieldTable fieldTable) { initMapIfNecessary(); + _encodedForm = null; _properties.putAll(fieldTable._properties); recalculateEncodedSize(); } @@ -836,7 +859,13 @@ public class FieldTable if(_encodedForm != null) { - buffer.put(_encodedForm); + + if(_encodedForm.position() != 0) + { + _encodedForm.flip(); + } +// _encodedForm.limit((int)getEncodedSize()); + buffer.put(_encodedForm); } else if(_properties != null) { @@ -924,4 +953,33 @@ public class FieldTable } } + public int hashCode() + { + initMapIfNecessary(); + return _properties.hashCode(); + } + + + public boolean equals(Object o) + { + if(o == this) + { + return true; + } + if(o == null) + { + return false; + } + if(!(o instanceof FieldTable)) + { + return false; + } + + initMapIfNecessary(); + + FieldTable f = (FieldTable) o; + f.initMapIfNecessary(); + + return _properties.equals(f._properties); + } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java index 697a0f4249..8b40fe72eb 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java @@ -25,25 +25,50 @@ import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.qpid.AMQException; +import java.io.UnsupportedEncodingException; + public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQDataBlock { - public char[] header = new char[]{'A','M','Q','P'}; + // TODO: generate these constants automatically from the xml protocol spec file + public static final byte[] AMQP_HEADER = new byte[]{(byte)'A',(byte)'M',(byte)'Q',(byte)'P'}; - private static byte CURRENT_PROTOCOL_CLASS = 1; - private static final int CURRENT_PROTOCOL_INSTANCE = 1; + private static final byte CURRENT_PROTOCOL_CLASS = 1; + private static final byte TCP_PROTOCOL_INSTANCE = 1; + + public final byte[] _protocolHeader; + public final byte _protocolClass; + public final byte _protocolInstance; + public final byte _protocolMajor; + public final byte _protocolMinor; - public byte protocolClass = CURRENT_PROTOCOL_CLASS; - public byte protocolInstance = CURRENT_PROTOCOL_INSTANCE; - public byte protocolMajor; - public byte protocolMinor; // public ProtocolInitiation() {} - public ProtocolInitiation(byte major, byte minor) + public ProtocolInitiation(byte[] protocolHeader, byte protocolClass, byte protocolInstance, byte protocolMajor, byte protocolMinor) + { + _protocolHeader = protocolHeader; + _protocolClass = protocolClass; + _protocolInstance = protocolInstance; + _protocolMajor = protocolMajor; + _protocolMinor = protocolMinor; + } + + public ProtocolInitiation(ProtocolVersion pv) { - protocolMajor = major; - protocolMinor = minor; + this(AMQP_HEADER, CURRENT_PROTOCOL_CLASS, TCP_PROTOCOL_INSTANCE, pv.getMajorVersion(), pv.getMinorVersion()); + } + + + public ProtocolInitiation(ByteBuffer in) + { + _protocolHeader = new byte[4]; + in.get(_protocolHeader); + + _protocolClass = in.get(); + _protocolInstance = in.get(); + _protocolMajor = in.get(); + _protocolMinor = in.get(); } public long getSize() @@ -53,19 +78,12 @@ public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQData public void writePayload(ByteBuffer buffer) { - for (int i = 0; i < header.length; i++) - { - buffer.put((byte) header[i]); - } - buffer.put(protocolClass); - buffer.put(protocolInstance); - buffer.put(protocolMajor); - buffer.put(protocolMinor); - } - public void populateFromBuffer(ByteBuffer buffer) throws AMQException - { - throw new AMQException("Method not implemented"); + buffer.put(_protocolHeader); + buffer.put(_protocolClass); + buffer.put(_protocolInstance); + buffer.put(_protocolMajor); + buffer.put(_protocolMinor); } public boolean equals(Object o) @@ -76,36 +94,36 @@ public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQData } ProtocolInitiation pi = (ProtocolInitiation) o; - if (pi.header == null) + if (pi._protocolHeader == null) { return false; } - if (header.length != pi.header.length) + if (_protocolHeader.length != pi._protocolHeader.length) { return false; } - for (int i = 0; i < header.length; i++) + for (int i = 0; i < _protocolHeader.length; i++) { - if (header[i] != pi.header[i]) + if (_protocolHeader[i] != pi._protocolHeader[i]) { return false; } } - return (protocolClass == pi.protocolClass && - protocolInstance == pi.protocolInstance && - protocolMajor == pi.protocolMajor && - protocolMinor == pi.protocolMinor); + return (_protocolClass == pi._protocolClass && + _protocolInstance == pi._protocolInstance && + _protocolMajor == pi._protocolMajor && + _protocolMinor == pi._protocolMinor); } public static class Decoder //implements MessageDecoder { /** * - * @param session - * @param in + * @param session the session + * @param in input buffer * @return true if we have enough data to decode the PI frame fully, false if more * data is required */ @@ -115,63 +133,62 @@ public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQData } public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) - throws Exception { - byte[] theHeader = new byte[4]; - in.get(theHeader); - ProtocolInitiation pi = new ProtocolInitiation((byte)0, (byte)0); - pi.header = new char[]{(char) theHeader[0],(char) theHeader[CURRENT_PROTOCOL_INSTANCE],(char) theHeader[2], (char) theHeader[3]}; - String stringHeader = new String(pi.header); - if (!"AMQP".equals(stringHeader)) - { - throw new AMQProtocolHeaderException("Invalid protocol header - read " + stringHeader); - } - pi.protocolClass = in.get(); - pi.protocolInstance = in.get(); - pi.protocolMajor = in.get(); - pi.protocolMinor = in.get(); + ProtocolInitiation pi = new ProtocolInitiation(in); out.write(pi); } } - public void checkVersion(ProtocolVersionList pvl) throws AMQException + public void checkVersion() throws AMQException { - if (protocolClass != CURRENT_PROTOCOL_CLASS) - { - throw new AMQProtocolClassException("Protocol class " + CURRENT_PROTOCOL_CLASS + " was expected; received " + - protocolClass); - } - if (protocolInstance != CURRENT_PROTOCOL_INSTANCE) + + if(_protocolHeader.length != 4) { - throw new AMQProtocolInstanceException("Protocol instance " + CURRENT_PROTOCOL_INSTANCE + " was expected; received " + - protocolInstance); + throw new AMQProtocolHeaderException("Protocol header should have exactly four octets"); } - - /* Look through list of available protocol versions */ - boolean found = false; - for (int i=0; i Date: Wed, 28 Feb 2007 11:05:20 +0000 Subject: (Patch submitted by Rupert Smith). java_iop.diff This adds some interop tests (which are just copies of the existing topic tests) in a new integrationtests module. The java 1.4. client build has been updated to be able to run these tests. They succesfully talk to each other and the .net code. This is intended to be a starting point of a more in depth interop test as per the spec, but does not implement what is in the draft spec yet. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@512699 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/util/CommandLineParser.java | 659 +++++++++++++++++++++ .../apache/qpid/util/CommandLineParserTest.java | 524 ++++++++++++++++ 2 files changed, 1183 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java create mode 100644 qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java b/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java new file mode 100644 index 0000000000..6173780aa7 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java @@ -0,0 +1,659 @@ +/* + * + * 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.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.regex.*; + +/** + * CommandLineParser provides a utility for specifying the format of a command line and parsing command lines to ensure + * that they fit their specified format. A command line is made up of flags and options, both may be refered to as + * options. A flag is an option that does not take an argument (specifying it means it has the value 'true' and not + * specifying it means it has the value 'false'). Options must take arguments but they can be set up with defaults so + * that they take a default value when not set. Options may be mandatory in wich case it is an error not to specify + * them on the command line. Flags are never mandatory because they are implicitly set to false when not specified. + * + *

    Some examples command line are: + * + *

      + *
    • This one has two options that expect arguments: + *
      + * cruisecontrol -configfile cruisecontrol.xml -port 9000
      + * 
      + *
    • This has one no-arg flag and two 'free' arguments: + *
      + * zip -r project.zip project/*
      + * 
      + *
    • This one concatenates multiple flags into a single block with only one '-': + *
      + * jar -tvf mytar.tar
      + * 
      + * + *

      The parsing rules are: + * + *

        + *
      1. Flags may be combined after a single '-' because they never take arguments. Normally such flags are single letter + * flags but this is only a convention and not enforced. Flags of more than one letter are usually specified on their own. + *
      2. Options expecting arguments must always be on their own. + *
      3. The argument to an option may be seperated from it by whitespace or appended directly onto the option. + *
      4. The argument to an option may never begin with a '-' character. + *
      5. All other arguments not beginning with a '-' character are free arguments that do not belong to any option. + *
      6. The second or later of a set of duplicate or repeated flags are ignored. + *
      7. Options are matched up to the shortest matching option. This is because of the possibility of having no space + * between an option and its argument. This rules out the possibility of using two options where one is an opening + * substring of the other. For example, the options "foo" and "foobar" cannot be used on the same command line because + * it is not possible to distinguish the argument "-foobar" from being the "foobar" option or the "foo" option with + * the "bar" argument. + *
      + * + *

      By default, unknown options are simply ignored if specified on the command line. This behaviour may be changed + * so that the parser reports all unknowns as errors by using the {@link #setErrorsOnUnknowns} method. + * + *

      + *
      CRC Card
      Responsibilities Collaborations + *
      Accept a command line specification. + *
      Parse a command line into properties, validating it against its specification. + *
      Report all errors between a command line and its specification. + *
      Provide a formatted usage string for a command line. + *
      Provide a formatted options in force string for a command line. + *
      Allow errors on unknowns behaviour to be turned on or off. + *
      + * + * @author Rupert Smith + */ +public class CommandLineParser +{ + /** Holds a mapping from command line option names to detailed information about those options. */ + private Map optionMap = new HashMap(); + + /** Holds a list of parsing errors. */ + private List parsingErrors = new ArrayList(); + + /** Holds the regular expression matcher to match command line options with. */ + private Matcher optionMatcher = null; + + /** Holds the parsed command line properties after parsing. */ + private Properties parsedProperties = null; + + /** Flag used to indicate that errors should be created for unknown options. False by default. */ + private boolean errorsOnUnknowns = false; + + /** + * Creates a command line options parser from a command line specification. This is passed to this constructor + * as an array of arrays of strings. Each array of strings specifies the command line for a single option. A static + * array may therefore easily be used to configure the command line parser in a single method call with an easily + * readable format. + * + *

      Each array of strings must be 2, 3, 4 or 5 elements long. If any of the last three elements are missing they + * are assumed to be null. The elements specify the following parameters: + *

        + *
      1. The name of the option without the leading '-'. For example, "file". To specify the format of the 'free' + * arguments use the option names "1", "2", ... and so on. + *
      2. The option comment. A line of text describing the usage of the option. For example, "The file to be processed." + *
      3. The options argument. This is a very short description of the argument to the option, often a single word + * or a reminder as to the arguments format. When this element is null the option is a flag and does not + * accept any arguments. For example, "filename" or "(unix | windows)" or null. The actual text specified + * is only used to print in the usage message to remind the user of the usage of the option. + *
      4. The mandatory flag. When set to "true" an option must always be specified. Any other value, including null, + * means that the option is mandatory. Flags are always mandatory (see class javadoc for explanation of why) so + * this is ignored for flags. + *
      5. A regular expression describing the format that the argument must take. Ignored if null. + *
      + *

      An example call to this constructor is: + * + *

      +     * CommandLineParser commandLine = new CommandLineParser(
      +     *     new String[][] {{"file", "The file to be processed. ", "filename", "true"},
      +     *                     {"dir", "Directory to store results in. Current dir used if not set.", "out dir"},
      +     *                     {"os", "Operating system EOL format to use.", "(windows | unix)", null, "windows\|unix"},
      +     *                     {"v", "Verbose mode. Prints information about the processing as it goes."},
      +     *                     {"1", "The processing command to run.", "command", "true", "add\|remove\|list"}});
      +     * 
      + * + * @param config The configuration as an array of arrays of strings. + */ + public CommandLineParser(String[][] config) + { + // Loop through all the command line option specifications creating details for each in the options map. + for (int i = 0; i < config.length; i++) + { + String[] nextOptionSpec = config[i]; + + addOption(nextOptionSpec[0], nextOptionSpec[1], (nextOptionSpec.length > 2) ? nextOptionSpec[2] : null, + (nextOptionSpec.length > 3) ? ("true".equals(nextOptionSpec[3]) ? true : false) : false, + (nextOptionSpec.length > 4) ? nextOptionSpec[4] : null); + } + } + + /** + * Lists all the parsing errors from the most recent parsing in a string. + * + * @return All the parsing errors from the most recent parsing. + */ + public String getErrors() + { + // Return the empty string if there are no errors. + if (parsingErrors.isEmpty()) + { + return ""; + } + + // Concatenate all the parsing errors together. + String result = ""; + + for (String s : parsingErrors) + { + result += s; + } + + return result; + } + + /** + * Lists the properties set from the most recent parsing or an empty string if no parsing has been done yet. + * + * @return The properties set from the most recent parsing or an empty string if no parsing has been done yet. + */ + public String getOptionsInForce() + { + // Check if there are no properties to report and return and empty string if so. + if (parsedProperties == null) + { + return ""; + } + + // List all the properties. + String result = "Options in force:\n"; + + for (Map.Entry property : parsedProperties.entrySet()) + { + result += property.getKey() + " = " + property.getValue() + "\n"; + } + + return result; + } + + /** + * Generates a usage string consisting of the name of each option and each options argument description and + * comment. + * + * @return A usage string for all the options. + */ + public String getUsage() + { + String result = "Options:\n"; + + // Print usage on each of the command line options. + for (CommandLineOption optionInfo : optionMap.values()) + { + result += optionInfo.option + " " + ((optionInfo.argument != null) ? (optionInfo.argument + " ") : "") + + optionInfo.comment + "\n"; + } + + return result; + } + + /** + * Control the behaviour of the errors on unkowns reporting. When turned on this reports all unkowns options + * as errors. When turned off, all unknowns are simply ignored. + * + * @param errors The setting of the errors on unkown flag. True to turn it on. + */ + public void setErrorsOnUnknowns(boolean errors) + { + errorsOnUnknowns = errors; + } + + /** + * Parses a set of command line arguments into a set of properties, keyed by the argument flag. The free arguments + * are keyed by integers as strings starting at "1" and then "2", ... and so on. + * + *

      See the class level comment for a description of the parsing rules. + * + * @param args The command line arguments. + * + * @return The arguments as a set of properties. + * + * @throws IllegalArgumentException If the command line cannot be parsed against its specification. If this exception + * is thrown a call to {@link #getErrors} will provide a diagnostic of the command + * line errors. + */ + public Properties parseCommandLine(String[] args) throws IllegalArgumentException + { + Properties options = new Properties(); + + // Used to keep count of the current 'free' argument. + int free = 1; + + // Used to indicate that the most recently parsed option is expecting arguments. + boolean expectingArgs = false; + + // The option that is expecting arguments from the next element of the command line. + String optionExpectingArgs = null; + + // Used to indicate that the most recently parsed option is a duplicate and should be ignored. + boolean ignore = false; + + // Create the regular expression matcher for the command line options. + String regexp = "^("; + int optionsAdded = 0; + + for (Iterator i = optionMap.keySet().iterator(); i.hasNext();) + { + String nextOption = i.next(); + + // Check that the option is not a free argument definition. + boolean notFree = false; + + try + { + Integer.parseInt(nextOption); + } + catch (NumberFormatException e) + { + notFree = true; + } + + // Add the option to the regular expression matcher if it is not a free argument definition. + if (notFree) + { + regexp += nextOption + (i.hasNext() ? "|" : ""); + optionsAdded++; + } + } + + // There has to be more that one option in the regular expression or else the compiler complains that the close + // cannot be nullable if the '?' token is used to make the matched option string optional. + regexp += ")" + ((optionsAdded > 0) ? "?" : "") + "(.*)"; + Pattern pattern = Pattern.compile(regexp); + + // Loop through all the command line arguments. + for (int i = 0; i < args.length; i++) + { + // Check if the next command line argument begins with a '-' character and is therefore the start of + // an option. + if (args[i].startsWith("-")) + { + // Extract the value of the option without the leading '-'. + String arg = args[i].substring(1); + + // Match up to the longest matching option. + optionMatcher = pattern.matcher(arg); + optionMatcher.matches(); + + String matchedOption = optionMatcher.group(1); + + // Match any argument directly appended onto the longest matching option. + String matchedArg = optionMatcher.group(2); + + // Check that a known option was matched. + if ((matchedOption != null) && !"".equals(matchedOption)) + { + // Get the command line option information for the matched option. + CommandLineOption optionInfo = optionMap.get(matchedOption); + + // Check if this option is expecting arguments. + if (optionInfo.expectsArgs) + { + // The option is expecting arguments so swallow the next command line argument as an + // argument to this option. + expectingArgs = true; + optionExpectingArgs = matchedOption; + + // In the mean time set this options argument to the empty string in case no argument is ever + // supplied. + // options.put(matchedOption, ""); + } + + // Check if the option was matched on its own and is a flag in which case set that flag. + if ("".equals(matchedArg) && !optionInfo.expectsArgs) + { + options.put(matchedOption, "true"); + } + // The option was matched as a substring with its argument appended to it or is a flag that is + // condensed together with other flags. + else if (!"".equals(matchedArg)) + { + // Check if the option is a flag and therefore is allowed to be condensed together + // with other flags. + if (!optionInfo.expectsArgs) + { + // Set the first matched flag. + options.put(matchedOption, "true"); + + // Repeat the longest matching process on the remainder but ensure that the remainder + // consists only of flags as only flags may be condensed together in this fashion. + do + { + // Match the remainder against the options. + optionMatcher = pattern.matcher(matchedArg); + optionMatcher.matches(); + + matchedOption = optionMatcher.group(1); + matchedArg = optionMatcher.group(2); + + // Check that an option was matched. + if (matchedOption != null) + { + // Get the command line option information for the next matched option. + optionInfo = optionMap.get(matchedOption); + + // Ensure that the next option is a flag or raise an error if not. + if (optionInfo.expectsArgs == true) + { + parsingErrors.add("Option " + matchedOption + " cannot be combined with flags.\n"); + } + + options.put(matchedOption, "true"); + } + // The remainder could not be matched against a flag it is either an unknown flag + // or an illegal argument to a flag. + else + { + parsingErrors.add("Illegal argument to a flag in the option " + arg + "\n"); + + break; + } + } + // Continue until the remainder of the argument has all been matched with flags. + while (!"".equals(matchedArg)); + } + // The option is expecting an argument, so store the unmatched portion against it + // as its argument. + else + { + // Check the arguments format is correct against any specified format. + checkArgumentFormat(optionInfo, matchedArg); + + // Store the argument against its option (regardless of its format). + options.put(matchedOption, matchedArg); + + // The argument to this flag has already been supplied to it. Do not swallow the + // next command line argument as an argument to this flag. + expectingArgs = false; + } + } + } + else // No matching option was found. + { + // Add this to the list of parsing errors if errors on unkowns is being used. + if (errorsOnUnknowns) + { + parsingErrors.add("Option " + matchedOption + " is not a recognized option.\n"); + } + } + } + // The command line argument did not being with a '-' so it is an argument to the previous flag or it + // is a free argument. + else + { + // Check if a previous flag is expecting to swallow this next argument as its argument. + if (expectingArgs) + { + // Get the option info for the option waiting for arguments. + CommandLineOption optionInfo = optionMap.get(optionExpectingArgs); + + // Check the arguments format is correct against any specified format. + checkArgumentFormat(optionInfo, args[i]); + + // Store the argument against its option (regardless of its format). + options.put(optionExpectingArgs, args[i]); + + // Clear the expecting args flag now that the argument has been swallowed. + expectingArgs = false; + optionExpectingArgs = null; + } + // This command line option is not an argument to any option. Add it to the set of 'free' options. + else + { + // Get the option info for the free option, if there is any. + CommandLineOption optionInfo = optionMap.get(Integer.toString(free)); + + if (optionInfo != null) + { + // Check the arguments format is correct against any specified format. + checkArgumentFormat(optionInfo, args[i]); + } + + // Add to the list of free options. + options.put(Integer.toString(free), args[i]); + + // Move on to the next free argument. + free++; + } + } + } + + // Scan through all the specified options to check that all mandatory options have been set and that all flags + // that were not set are set to false in the set of properties. + for (CommandLineOption optionInfo : optionMap.values()) + { + // Check if this is a flag. + if (!optionInfo.expectsArgs) + { + // Check if the flag is not set in the properties and set it to false if so. + if (!options.containsKey(optionInfo.option)) + { + options.put(optionInfo.option, "false"); + } + } + // Check if this is a mandatory option and was not set. + else if (optionInfo.mandatory && !options.containsKey(optionInfo.option)) + { + // Create an error for the missing option. + parsingErrors.add("Option " + optionInfo.option + " is mandatory but not was not specified.\n"); + } + } + + // Check if there were any errors. + if (!parsingErrors.isEmpty()) + { + // Throw an illegal argument exception to signify that there were parsing errors. + throw new IllegalArgumentException(); + } + + // Convert any name/value pairs in the free arguments into properties in the parsed options. + options = takeFreeArgsAsProperties(options, 1); + + parsedProperties = options; + + return options; + } + + /** + * If a command line has been parsed, calling this method sets all of its parsed options as system properties. + */ + public void addCommandLineToSysProperties() + { + if (parsedProperties != null) + { + for (Object propKey : parsedProperties.keySet()) + { + String name = (String) propKey; + String value = parsedProperties.getProperty(name); + + System.setProperty(name, value); + } + } + } + + /** + * Resets this command line parser after it has been used to parse a command line. This method will only need + * to be called to use this parser a second time which is not likely seeing as a command line is usually only + * specified once. However, it is exposed as a public method for the rare case where this may be done. + * + *

      Cleans the internal state of this parser, removing all stored errors and information about the options in + * force. + */ + public void reset() + { + parsingErrors = new ArrayList(); + parsedProperties = null; + } + + /** + * Adds the option to list of available command line options. + * + * @param option The option to add as an available command line option. + * @param comment A comment for the option. + * @param argument The text that appears after the option in the usage string. + * @param mandatory When true, indicates that this option is mandatory. + * @param formatRegexp The format that the argument must take, defined as a regular expression. + */ + protected void addOption(String option, String comment, String argument, boolean mandatory, String formatRegexp) + { + // Check if usage text has been set in which case this option is expecting arguments. + boolean expectsArgs = ((argument == null) || argument.equals("")) ? false : true; + + // Add the option to the map of command line options. + CommandLineOption opt = new CommandLineOption(option, expectsArgs, comment, argument, mandatory, formatRegexp); + optionMap.put(option, opt); + } + + /** + * Converts the free arguments into property declarations. After parsing the command line the free arguments + * are numbered from 1, such that the parsed properties contain values for the keys "1", "2", ... This method + * converts any free arguments declared using the 'name=value' syntax into properties with key 'name', value + * 'value'. + * + *

      For example the comand line: + *

      +     * ... debug=true
      +     * 
      + * + *

      After parsing has properties: + *

      [[1, debug=true]]
      + * + *

      After applying this method the properties are: + *

      [[1, debug=true], [debug, true]]
      + * + * @param properties The parsed command line properties. + * @param from The free argument index to convert to properties from. + * + * @return The parsed command line properties, with free argument name value pairs too. + */ + private Properties takeFreeArgsAsProperties(Properties properties, int from) + { + for (int i = from; true; i++) + { + String nextFreeArg = properties.getProperty(Integer.toString(i)); + + // Terminate the loop once all free arguments have been consumed. + if (nextFreeArg == null) + { + break; + } + + // Split it on the =, strip any whitespace and set it as a system property. + String[] nameValuePair = nextFreeArg.split("="); + + if (nameValuePair.length == 2) + { + properties.setProperty(nameValuePair[0], nameValuePair[1]); + } + } + + return properties; + } + + /** + * Checks the format of an argument to an option against its specified regular expression format if one has + * been set. Any errors are added to the list of parsing errors. + * + * @param optionInfo The command line option information for the option which is havings its argument checked. + * @param matchedArg The string argument to the option. + */ + private void checkArgumentFormat(CommandLineOption optionInfo, String matchedArg) + { + // Check if this option enforces a format for its argument. + if (optionInfo.argumentFormatRegexp != null) + { + Pattern pattern = Pattern.compile(optionInfo.argumentFormatRegexp); + Matcher argumentMatcher = pattern.matcher(matchedArg); + + // Check if the argument does not meet its required format. + if (!argumentMatcher.matches()) + { + // Create an error for this badly formed argument. + parsingErrors.add("The argument to option " + optionInfo.option + " does not meet its required format.\n"); + } + } + } + + /** + * Holds information about a command line options. This includes what its name is, whether or not it is a flag, + * whether or not it is mandatory, what its user comment is, what its argument reminder text is and what its + * regular expression format is. + * + *

      + *
      CRC Card
      Responsibilities Collaborations + *
      Hold details of a command line option. + *
      + * + * @author Rupert Smith + */ + protected class CommandLineOption + { + /** Holds the text for the flag to match this argument with. */ + public String option = null; + + /** Holds a string describing how to use this command line argument. */ + public String argument = null; + + /** Flag that determines whether or not this command line argument can take arguments. */ + public boolean expectsArgs = false; + + /** Holds a short comment describing what this command line argument is for. */ + public String comment = null; + + /** Flag that determines whether or not this is an mandatory command line argument. */ + public boolean mandatory = false; + + /** A regular expression describing what format the argument to this option muist have. */ + public String argumentFormatRegexp = null; + + /** + * Create a command line option object that holds specific information about a command line option. + * + * @param option The text that matches the option. + * @param expectsArgs Whether or not the option expects arguments. It is a flag if this is false. + * @param comment A comment explaining how to use this option. + * @param argument A short reminder of the format of the argument to this option/ + * @param mandatory Set to true if this option is mandatory. + * @param formatRegexp The regular expression that the argument to this option must meet to be valid. + */ + public CommandLineOption(String option, boolean expectsArgs, String comment, String argument, boolean mandatory, + String formatRegexp) + { + this.option = option; + this.expectsArgs = expectsArgs; + this.comment = comment; + this.argument = argument; + this.mandatory = mandatory; + this.argumentFormatRegexp = formatRegexp; + } + } +} diff --git a/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java b/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java new file mode 100644 index 0000000000..085a724399 --- /dev/null +++ b/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java @@ -0,0 +1,524 @@ +/* Copyright Rupert Smith, 2005 to 2006, all rights reserved. */ +package org.apache.qpid.util; + +import java.util.Properties; + +import junit.framework.*; + +import org.apache.log4j.*; + +/** + * Unit tests the {@link CommandLineParser} class. + * + *

      + *
      CRC Card
      Responsibilities Collaborations + *
      Check that parsing a single flag works ok. + *
      Check that parsing multiple flags condensed together works ok. + *
      Check that parsing an option with a space between it and its argument works ok. + *
      Check that parsing an option with no space between it and its argument works ok. + *
      Check that parsing an option with specific argument format works ok. + *
      Check that parsing an option with specific argument format fails on bad argument. + *
      Check that parsing a flag condensed together with an option fails. + *
      Check that parsing a free argument works ok. + *
      Check that parsing a free argument with specific format works ok. + *
      Check that parsing a free argument with specific format fails on bad argument. + *
      Check that parsing a mandatory option works ok. + *
      Check that parsing a mandatory free argument works ok. + *
      Check that parsing a mandatory option fails when no option is set. + *
      Check that parsing a mandatory free argument fails when no argument is specified. + *
      Check that parsing an unknown option works when unknowns not errors. + *
      Check that parsing an unknown flag fails when unknowns are to be reported as errors. + *
      Check that parsing an unknown option fails when unknowns are to be reported as errors. + *
      Check that get errors returns a string on errors. + *
      Check that get errors returns an empty string on no errors. + *
      Check that get usage returns a string. + *
      Check that get options in force returns an empty string before parsing. + *
      Check that get options in force return a non-empty string after parsing. + *
      + * + * @author Rupert Smith + */ +public class CommandLineParserTest extends TestCase +{ + private static final Logger log = Logger.getLogger(CommandLineParserTest.class); + + public CommandLineParserTest(String name) + { + super(name); + } + + /** + * Compile all the tests for the default test implementation of a traversable state into a test suite. + */ + public static Test suite() + { + // Build a new test suite + TestSuite suite = new TestSuite("CommandLineParser Tests"); + + // Add all the tests defined in this class (using the default constructor) + suite.addTestSuite(CommandLineParserTest.class); + + return suite; + } + + public void setUp() + { + NDC.push(getName()); + } + + /** Check that get errors returns an empty string on no errors. */ + public void testGetErrorsReturnsEmptyStringOnNoErrors() throws Exception + { + // Create a command line parser for some flags and options. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t1", "Test Flag 1." }, + { "t2", "Test Option 2.", "test" }, + { "t3", "Test Option 3.", "test", "true" }, + { "t4", "Test Option 4.", "test", null, "^test$" } + }); + + // Do some legal parsing. + parser.parseCommandLine(new String[] { "-t1", "-t2test", "-t3test", "-t4test" }); + + // Check that the get errors message returns an empty string. + assertTrue("The errors method did not return an empty string.", "".equals(parser.getErrors())); + } + + /** Check that get errors returns a string on errors. */ + public void testGetErrorsReturnsStringOnErrors() throws Exception + { + // Create a command line parser for some flags and options. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t1", "Test Flag 1." }, + { "t2", "Test Option 2.", "test" }, + { "t3", "Test Option 3.", "test", "true" }, + { "t4", "Test Option 4.", "test", null, "^test$" } + }); + + try + { + // Do some illegal parsing. + parser.parseCommandLine(new String[] { "-t1", "-t1t2test", "-t4fail" }); + } + catch (IllegalArgumentException e) + { } + + // Check that the get errors message returns a string. + assertTrue("The errors method returned an empty string.", + !((parser.getErrors() == null) || "".equals(parser.getErrors()))); + + } + + /** Check that get options in force returns an empty string before parsing. */ + public void testGetOptionsInForceReturnsEmptyStringBeforeParsing() throws Exception + { + // Create a command line parser for some flags and options. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t1", "Test Flag 1." }, + { "t2", "Test Option 2.", "test" }, + { "t3", "Test Option 3.", "test", "true" }, + { "t4", "Test Option 4.", "test", null, "^test$" } + }); + + // Check that the options in force method returns an empty string. + assertTrue("The options in force method did not return an empty string.", "".equals(parser.getOptionsInForce())); + } + + /** Check that get options in force return a non-empty string after parsing. */ + public void testGetOptionsInForceReturnsNonEmptyStringAfterParsing() throws Exception + { + // Create a command line parser for some flags and options. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t1", "Test Flag 1." }, + { "t2", "Test Option 2.", "test" }, + { "t3", "Test Option 3.", "test", "true" }, + { "t4", "Test Option 4.", "test", null, "^test$" } + }); + + // Do some parsing. + parser.parseCommandLine(new String[] { "-t1", "-t2test", "-t3test", "-t4test" }); + + // Check that the options in force method returns a string. + assertTrue("The options in force method did not return a non empty string.", + !((parser.getOptionsInForce() == null) || "".equals(parser.getOptionsInForce()))); + } + + /** Check that get usage returns a string. */ + public void testGetUsageReturnsString() throws Exception + { + // Create a command line parser for some flags and options. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t1", "Test Flag 1." }, + { "t2", "Test Option 2.", "test" }, + { "t3", "Test Option 3.", "test", "true" }, + { "t4", "Test Option 4.", "test", null, "^test$" } + }); + + // Check that the usage method returns a string. + assertTrue("The usage method did not return a non empty string.", + !((parser.getUsage() == null) || "".equals(parser.getUsage()))); + } + + /** Check that parsing multiple flags condensed together works ok. */ + public void testParseCondensedFlagsOk() throws Exception + { + // Create a command line parser for multiple flags. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t1", "Test Flag 1." }, + { "t2", "Test Flag 2." }, + { "t3", "Test Flag 3." } + }); + + // Parse a command line with the flags set and condensed together. + Properties testProps = parser.parseCommandLine(new String[] { "-t1t2t3" }); + + // Check that the flags were set in the parsed properties. + assertTrue("The t1 flag was not \"true\", it was: " + testProps.get("t1"), "true".equals(testProps.get("t1"))); + assertTrue("The t2 flag was not \"true\", it was: " + testProps.get("t2"), "true".equals(testProps.get("t2"))); + assertTrue("The t3 flag was not \"true\", it was: " + testProps.get("t3"), "true".equals(testProps.get("t3"))); + } + + /** Check that parsing a flag condensed together with an option fails. */ + public void testParseFlagCondensedWithOptionFails() throws Exception + { + // Create a command line parser for a flag and an option. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t1", "Test Flag 1." }, + { "t2", "Test Option 2.", "test" } + }); + + // Check that the parser reports an error. + boolean testPassed = false; + + try + { + // Parse a command line with the flag and option condensed together. + Properties testProps = parser.parseCommandLine(new String[] { "-t1t2" }); + } + catch (IllegalArgumentException e) + { + testPassed = true; + } + + assertTrue("IllegalArgumentException not thrown when a flag and option are condensed together.", testPassed); + } + + /** Check that parsing a free argument with specific format fails on bad argument. */ + public void testParseFormattedFreeArgumentFailsBadArgument() throws Exception + { + // Create a command line parser for a formatted free argument. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "1", "Test Free Argument.", "test", null, "^test$" } + }); + + // Check that the parser signals an error for a badly formatted argument. + boolean testPassed = false; + + try + { + // Parse a command line with this option set incorrectly. + Properties testProps = parser.parseCommandLine(new String[] { "fail" }); + } + catch (IllegalArgumentException e) + { + testPassed = true; + } + + assertTrue("IllegalArgumentException not thrown when a badly formatted argument was set.", testPassed); + } + + /** Check that parsing a free argument with specific format works ok. */ + public void testParseFormattedFreeArgumentOk() throws Exception + { + // Create a command line parser for a formatted free argument. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "1", "Test Free Argument.", "test", null, "^test$" } + }); + + // Parse a command line with this argument set correctly. + Properties testProps = parser.parseCommandLine(new String[] { "test" }); + + // Check that the resultant properties contains the correctly parsed option. + assertTrue("The first free argument was not equal to \"test\" but was: " + testProps.get("1"), + "test".equals(testProps.get("1"))); + } + + /** Check that parsing an option with specific argument format fails on bad argument. */ + public void testParseFormattedOptionArgumentFailsBadArgument() throws Exception + { + // Create a command line parser for a formatted option. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t", "Test Option.", "test", null, "^test$" } + }); + + // Check that the parser signals an error for a badly formatted argument. + boolean testPassed = false; + + try + { + // Parse a command line with this option set incorrectly. + Properties testProps = parser.parseCommandLine(new String[] { "-t", "fail" }); + } + catch (IllegalArgumentException e) + { + testPassed = true; + } + + assertTrue("IllegalArgumentException not thrown when a badly formatted argument was set.", testPassed); + } + + /** Check that parsing an option with specific argument format works ok. */ + public void testParseFormattedOptionArgumentOk() throws Exception + { + // Create a command line parser for a formatted option. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t", "Test Option.", "test", null, "^test$" } + }); + + // Parse a command line with this option set correctly. + Properties testProps = parser.parseCommandLine(new String[] { "-t", "test" }); + + // Check that the resultant properties contains the correctly parsed option. + assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"), "test".equals(testProps.get("t"))); + } + + /** Check that parsing a free argument works ok. */ + public void testParseFreeArgumentOk() throws Exception + { + // Create a command line parser for a free argument. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "1", "Test Free Argument.", "test" } + }); + + // Parse a command line with this argument set. + Properties testProps = parser.parseCommandLine(new String[] { "test" }); + + // Check that the resultant properties contains the correctly parsed option. + assertTrue("The first free argument was not equal to \"test\" but was: " + testProps.get("1"), + "test".equals(testProps.get("1"))); + } + + /** Check that parsing a mandatory option works ok. */ + public void testParseMandatoryOptionOk() throws Exception + { + // Create a command line parser for a mandatory option. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t", "Test Option.", "test", "true" } + }); + + // Parse a command line with this option set correctly. + Properties testProps = parser.parseCommandLine(new String[] { "-t", "test" }); + + // Check that the resultant properties contains the correctly parsed option. + assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"), "test".equals(testProps.get("t"))); + } + + /** Check that parsing a mandatory free argument works ok. */ + public void testParseMandatoryFreeArgumentOk() throws Exception + { + // Create a command line parser for a mandatory free argument. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "1", "Test Option.", "test", "true" } + }); + + // Parse a command line with this argument set. + Properties testProps = parser.parseCommandLine(new String[] { "test" }); + + // Check that the resultant properties contains the correctly parsed option. + assertTrue("The first free argument was not equal to \"test\" but was: " + testProps.get("1"), + "test".equals(testProps.get("1"))); + } + + /** Check that parsing a mandatory free argument fails when no argument is specified. */ + public void testParseManadatoryFreeArgumentFailsNoArgument() throws Exception + { + // Create a command line parser for a mandatory free argument. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "1", "Test Option.", "test", "true" } + }); + + // Check that parsing fails when this mandatory free argument is missing. + boolean testPassed = false; + + try + { + // Parse a command line with this free argument not set. + Properties testProps = parser.parseCommandLine(new String[] {}); + } + catch (IllegalArgumentException e) + { + testPassed = true; + } + + // Check that the resultant properties contains the correctly parsed option. + assertTrue("IllegalArgumentException not thrown for a missing mandatory option.", testPassed); + } + + /** Check that parsing a mandatory option fails when no option is set. */ + public void testParseMandatoryFailsNoOption() throws Exception + { + // Create a command line parser for a mandatory option. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t", "Test Option.", "test", "true" } + }); + + // Check that parsing fails when this mandatory option is missing. + boolean testPassed = false; + + try + { + // Parse a command line with this option not set. + Properties testProps = parser.parseCommandLine(new String[] {}); + } + catch (IllegalArgumentException e) + { + testPassed = true; + } + + // Check that the resultant properties contains the correctly parsed option. + assertTrue("IllegalArgumentException not thrown for a missing mandatory option.", testPassed); + } + + /** Check that parsing an option with no space between it and its argument works ok. */ + public void testParseOptionWithNoSpaceOk() throws Exception + { + // Create a command line parser for an option. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t", "Test Option.", "test" } + }); + + // Parse a command line with this option set with no space. + Properties testProps = parser.parseCommandLine(new String[] { "-ttest" }); + + // Check that the resultant properties contains the correctly parsed option. + assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"), "test".equals(testProps.get("t"))); + } + + /** Check that parsing an option with a space between it and its argument works ok. */ + public void testParseOptionWithSpaceOk() throws Exception + { + // Create a command line parser for an option. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t", "Test Option.", "test" } + }); + + // Parse a command line with this option set with a space. + Properties testProps = parser.parseCommandLine(new String[] { "-t", "test" }); + + // Check that the resultant properties contains the correctly parsed option. + assertTrue("The test option was not equal to \"test\" but was: " + testProps.get("t"), "test".equals(testProps.get("t"))); + } + + /** Check that parsing a single flag works ok. */ + public void testParseSingleFlagOk() throws Exception + { + // Create a command line parser for a single flag. + CommandLineParser parser = new CommandLineParser(new String[][] + { + { "t", "Test Flag." } + }); + + // Parse a command line with the single flag set. + Properties testProps = parser.parseCommandLine(new String[] { "-t" }); + + // Check that the flag is set in the parsed properties. + assertTrue("The t flag was not \"true\", it was: " + testProps.get("t"), "true".equals(testProps.get("t"))); + + // Reset the parser. + parser.reset(); + + // Parse a command line with the single flag not set. + testProps = parser.parseCommandLine(new String[] {}); + + // Check that the flag is cleared in the parsed properties. + assertTrue("The t flag was not \"false\", it was: " + testProps.get("t"), "false".equals(testProps.get("t"))); + } + + /** Check that parsing an unknown option works when unknowns not errors. */ + public void testParseUnknownOptionOk() throws Exception + { + // Create a command line parser for no flags or options + CommandLineParser parser = new CommandLineParser(new String[][] {}); + + // Check that parsing does not fail on an unknown flag. + try + { + parser.parseCommandLine(new String[] { "-t" }); + } + catch (IllegalArgumentException e) + { + fail("The parser threw an IllegalArgumentException on an unknown flag when errors on unkowns is off."); + } + } + + /** Check that parsing an unknown flag fails when unknowns are to be reported as errors. */ + public void testParseUnknownFlagFailsWhenUnknownsAreErrors() throws Exception + { + // Create a command line parser for no flags or options + CommandLineParser parser = new CommandLineParser(new String[][] {}); + + // Turn on fail on unknowns mode. + parser.setErrorsOnUnknowns(true); + + // Check that parsing fails on an unknown flag. + boolean testPassed = false; + + try + { + parser.parseCommandLine(new String[] { "-t" }); + } + catch (IllegalArgumentException e) + { + testPassed = true; + } + + assertTrue("IllegalArgumentException not thrown for an unknown flag when errors on unknowns mode is on.", testPassed); + } + + /** Check that parsing an unknown option fails when unknowns are to be reported as errors. */ + public void testParseUnknownOptionFailsWhenUnknownsAreErrors() throws Exception + { + // Create a command line parser for no flags or options + CommandLineParser parser = new CommandLineParser(new String[][] {}); + + // Turn on fail on unknowns mode. + parser.setErrorsOnUnknowns(true); + + // Check that parsing fails on an unknown flag. + boolean testPassed = false; + + try + { + parser.parseCommandLine(new String[] { "-t", "test" }); + } + catch (IllegalArgumentException e) + { + testPassed = true; + } + + assertTrue("IllegalArgumentException not thrown for an unknown option when errors on unknowns mode is on.", testPassed); + } + + protected void tearDown() throws Exception + { + NDC.pop(); + } +} -- cgit v1.2.1 From 0c0dbd5e00f5b057867546bb336ece262577841c Mon Sep 17 00:00:00 2001 From: Martin Ritchie Date: Tue, 6 Mar 2007 14:12:47 +0000 Subject: QPID-403 QPID-346 QPID-355 QPID-386 QPID-389 Updates to fix Transactional Rollback. QPID-346 Message loss after rollback\recover QPID-355 Closing a consumer does not ensure messages delivery will stop for that subscription QPID-386 Updated Transactional Tests to cover underlying AMQP/Qpid state. QPID-389 Prefetched message are not correctly returned to the queue QPID-403 Implement Basic.Reject Broker UnacknowledgedMessage - Added toString for debug UnacknowledgedMessageMapImpl - Removed resendMessages method as all sending should go via DeliveryManager and Subscription. AMQChannel - Updated resend and requeue methods so they do not directly write messages to a subscriber. This was violating the suspension state. - Used a local non-transactional context to requeue messages as the internal requeuing of messages on the broker should not be part of any client transaction. - Maked messages as resent. - Removed warnings from IDE about missing JavaDoc text etc. BasicAckMethodHandler - Added debugging BasicRecoverMethodHandler - Removed session from the resend call. BasicRejectMethodHandler - Initial implementation. Hooks left for possible 'resend' bit. ChannelCloseHandler - Fixed bug where channel wasn't marked as fully closed on reception of a close from the client. TxRollbackHandler - Removed session from resend call. AMQMinaProtocolSession - Fixed bug where channel was marked as awaiting closure before it had actually been closed. This causes problems as the close looks up the channel by id again which will return null after it has been marked as awaiting closure. AMQMessage - Initial implementation of Rejection. Currently inactive in hasInterest() as we are miss-using reject to requeue prefetched messages from the client. AMQQueue - Removed debug method as it made reading the log very difficult as all the logs had the same line number ConcurrentSelectorDeliveryManager - Fixed clearAllMessages() as it didn't actually remove the messages. - Fixed bad logic in getNextMessage when using null subscriber. (as done by clearAllMessages) - Added more logging messages. Made more frequent logging a trace value. - Added debugIdentity() method to reduce over head in calculating standard log prefix. - Allowed messages to be added to the front of the queue. - Added currentStatus() to an overview of the queue's current state. SubscriptionImpl - Updated to handle closure correctly (QPID-355) -Updated the deliver method so it doesn't use a try->finally to do msg.setDeliveredToConsumer() as this would be done even in the event of an error. - Created an additional logger to log suspension calls rather than through the SI logger which logs a lot of detail. Client pom.xml - Excluded older version of log4j that commons-collections exposes. AMQSession - Added ability for dispatcher to start in stopped state. - Added dispatcher logger - Added checks around logging - Added message rejection if the dispatcher receives a message that it doesn't have a consumer for. - Updated message rejection to allow the dispatcher to perform the rejection if running this ensures that all queued messages are processed correctly and rejection occurs in order. - rollback() before calling rollback all pending queued messages must be rejected as rollback will clear unacked map which the rejects caused by rollback() will need. - fixed closedProducersAndConsumers so that it will rethrow any JMS Exception - recover() as for rollback() the rejects need to be done before the Recover Call to the broker. - Allowed delclareExchange to be done synchronously programatically - Updated confirmConsumerCancelled to use the dispatcher to perform the clean up. This required the creation of the dispatcher in stopped mode so that it does not start and message attempted to be delivered while the subscriber is being cancelled. BasicMessageConsumer - Updated close not to perform the deregistration. This is done in via BasicCancelOkMethodHandler - Added guards on logging - Record all messages that have been received so they can be rejected if rollback occurs. so had to change impl of acknowledgeLastDelivered. - Updated Rollback to initially reject all received messages that are still unAcked. - Added a recursive call should the queue not be empty at the end of the rollback.. with a warning. BasicCancelOkMethodHandler - White space changes to meet style guide. Added guard on logging. UnprocessedMessage - White space changes to meet style guide. StateWaiter - Added comment about timeout bug. FlowControllingBlockingQueue - Tidied imports RecoverTest - Updated as declareExchange is now Synchronous ChannelCloseTest - added guard on logging MessageRequeueTest - Added to better test underlying AMQP/Qpid state QPID-386 StreamMessageTest - Updated as declareExchange is now Synchronous CommitRollbackTest - added Additional test case to ensure prefetch queue is correctly purged. TransactedTest - Added logging and additional tests. Cluster SimpleClusterTest - updated in line with AMQSession.delcareExchange changes Common AMQConstant - Fixed error code 'not allowed' should be 530 not 507. ConcurrentLinkedMessageQueueAtomicSize - Updated to beable to get the size of messages on the 'head' queue along with additional debug Systests ReturnUnroutableMandatoryMessageTest - Updated as declareExchange is now Synchronous git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@515127 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/protocol/AMQConstant.java | 2 +- .../ConcurrentLinkedMessageQueueAtomicSize.java | 26 +++++++++++++++++----- 2 files changed, 22 insertions(+), 6 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java index ed244396bf..379f7feb4f 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java @@ -100,7 +100,7 @@ public final class AMQConstant public static final AMQConstant RESOURCE_ERROR = new AMQConstant(506, "resource error", true); - public static final AMQConstant NOT_ALLOWED = new AMQConstant(507, "not allowed", true); + public static final AMQConstant NOT_ALLOWED = new AMQConstant(530, "not allowed", true); public static final AMQConstant NOT_IMPLEMENTED = new AMQConstant(540, "not implemented", true); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java b/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java index cdf686b4cb..883d5018cd 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java @@ -41,6 +41,11 @@ public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQ return super.size() + _messageHeadSize.get(); } + public int headSize() + { + return _messageHeadSize.get(); + } + @Override public E poll() { @@ -50,10 +55,14 @@ public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQ } else { - _logger.debug("Providing item from message head"); - E e = _messageHead.poll(); + if (_logger.isDebugEnabled()) + { + _logger.debug("Providing item(" + e + ")from message head"); + } + + if (e != null) { _messageHeadSize.decrementAndGet(); @@ -159,8 +168,12 @@ public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQ } else { - _logger.debug("Providing item from message head"); - return _messageHead.peek(); + E o = _messageHead.peek(); + if (_logger.isDebugEnabled()) + { + _logger.debug("Peeking item (" + o + ") from message head"); + } + return o; } } @@ -186,7 +199,10 @@ public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQ public boolean pushHead(E o) { - _logger.debug("Adding item to head of queue"); + if (_logger.isDebugEnabled()) + { + _logger.debug("Adding item(" + o + ") to head of queue"); + } if (_messageHead.offer(o)) { _messageHeadSize.incrementAndGet(); -- cgit v1.2.1 From 8606a752312f9c891fa90e36767bff4d348542c5 Mon Sep 17 00:00:00 2001 From: Martin Ritchie Date: Tue, 13 Mar 2007 10:35:42 +0000 Subject: QPID-346,QPID-386,QPID-403, QPID-410 Rollback, Basic-Reject, QueueBrowser NO_ACK. QPID-346 Message loss after rollback\recover QPID-386 Updated Transactional Tests to cover underlying AMQP/Qpid state. QPID-403 Implement Basic.Reject QPID-410 Queue Browsers should use not acknowledge messages. ------------------------------------- Broker TxAck - Added comment and fixed white space UnacknowledgedMessage - Added comment for messageDecrement AMQChannel - Added extra debugging. + Created a NonTransactionalContext for requeuing messages as using txContext will tie the requeue to any runing transaction. + Updated message reference counting. So it is in terms of queues don't increment when giving to client. BasicCancelMethodHandler - Added Debug log. BasicConsumeMethodHandler - Reverted to directly writes frames to the session, throwing ChannelException caused problems. Added Trace and debug logging. BasicRejectMethodHandler, ChannelCloseHandler, ConnectionCloseMethodHandler - Added Debug logging AMQPFastProtocolHandler - moved error log to before session.write AMQMessage - Added additional debug via debugIdentity() and comments AMQQueue - Decoupled reference counting from dequeue operation. ConcurrentSelectorDeliveryManager - Added comments and increased info in debug logging SubscriptionImpl - Disabled use of acks for browsers. For now put setDeliveredToConsumer back in the finally block. commented that I'm not sure this is correct as even an error writing to client will cause msg to be marked delivered to consumer. + On Close ensured that it is only called once. + Had problem where closing browser was causing two CancelOk frames to be sent back to client. RequiredDeliveryException - Added comment to explain incrementReference LocalTransactionalContext - Commented out incrementReference as it shouldn't be required here. NonTransactionalContext - Removed incrementReference on deliver + - Fixed bug where browsers - acks would cause messages to be discarded. new JIRA this needs tidied up. TxnBuffer - Added debug logging. Client ------ AMQQueueBrowser - Added comments AMQSession - Added comments and debug + Updated to cause closed consumer to reject messages rather than receive them. + Prevented NoConsumer's from rollingback and rejecting.. they simply clear their SyncQueue - JIRA to ensure clean state with rollback BasicMessageConsumer - Added trace level debuging on close calls + Forced noConsume-rs to use NO_ACK + added more logging Closeable - Updated to use isClosed rather than directly calling _closed.get() to aid in future work on ensuring multi threaded close still allows pending acks to be processed first. ChannelCloseOkMethodHandler - updated comment AMQProtocolSession - Update comments,whitespace TransportConnection - removed static block FlowControllingBlockingQueue - Added isEmpty() Method PropertyValueTest - Added VM Broker setup + Updated test to run once and 50 times to pull out delivery tag problems that were occuring. + Adjusted logging level to be more helpful. moved some info down to trace and debug. MessageRequeueTest - Moved QpidClientConnection its own file. + Fixed it so it actually runs more than one consumer, concurrently.Now 3 was 1. ConcurrentLinkedMessageQueueAtomicSize - Implemented iterator(). Added QueueBrowserTest to system tests to test QueueBrowsering. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@517638 13f79535-47bb-0310-9956-ffa450edef68 --- .../ConcurrentLinkedMessageQueueAtomicSize.java | 31 +++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java b/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java index 883d5018cd..4636f44795 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java @@ -181,8 +181,37 @@ public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQ @Override public Iterator iterator() { - throw new RuntimeException("Not Implemented"); + final Iterator mainMessageIterator = super.iterator(); + return new Iterator() + { + final Iterator _headIterator = _messageHead.iterator(); + final Iterator _mainIterator = mainMessageIterator; + + Iterator last; + + public boolean hasNext() + { + return _headIterator.hasNext() || _mainIterator.hasNext(); + } + public E next() + { + if (_headIterator.hasNext()) + { + last = _headIterator; + return _headIterator.next(); + } + else + { + last = _mainIterator; + return _mainIterator.next(); + } + } + public void remove() + { + last.remove(); + } + }; } @Override -- cgit v1.2.1 From 5495e89711087f5f5896ebc30e25dae222a72da0 Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Thu, 15 Mar 2007 10:12:57 +0000 Subject: Commit of interop test stuff prior to M2 branch. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@518559 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/util/PropertiesUtils.java | 199 ++++++++++++++++++ .../java/org/apache/qpid/util/ReflectionUtils.java | 228 +++++++++++++++++++++ .../apache/qpid/util/ReflectionUtilsException.java | 44 ++++ 3 files changed, 471 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/PropertiesUtils.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/ReflectionUtils.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/ReflectionUtilsException.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/PropertiesUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/util/PropertiesUtils.java new file mode 100644 index 0000000000..aa21841256 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/PropertiesUtils.java @@ -0,0 +1,199 @@ +/* + * + * 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.util; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Iterator; +import java.util.Properties; + +import org.apache.log4j.Logger; + +/** + * PropertiesHelper defines some static methods which are useful when working with properties + * files. + * + *

      + *
      CRC Card
      Responsibilities Collaborations + *
      Read properties from an input stream + *
      Read properties from a file + *
      Read properties from a URL + *
      Read properties given a path to a file + *
      Trim any whitespace from property values + *
      + */ +public class PropertiesUtils +{ + /** Used for logging. */ + private static final Logger log = Logger.getLogger(PropertiesUtils.class); + + /** + * Get properties from an input stream. + * + * @param is The input stream. + * + * @return The properties loaded from the input stream. + * + * @throws IOException If the is an I/O error reading from the stream. + */ + public static Properties getProperties(InputStream is) throws IOException + { + log.debug("getProperties(InputStream): called"); + + // Create properties object laoded from input stream + Properties properties = new Properties(); + + properties.load(is); + + return properties; + } + + /** + * Get properties from a file. + * + * @param file The file. + * + * @return The properties loaded from the file. + * + * @throws IOException If there is an I/O error reading from the file. + */ + public static Properties getProperties(File file) throws IOException + { + log.debug("getProperties(File): called"); + + // Open the file as an input stream + InputStream is = new FileInputStream(file); + + // Create properties object loaded from the stream + Properties properties = getProperties(is); + + // Close the file + is.close(); + + return properties; + } + + /** + * Get properties from a url. + * + * @param url The URL. + * + * @return The properties loaded from the url. + * + * @throws IOException If there is an I/O error reading from the URL. + */ + public static Properties getProperties(URL url) throws IOException + { + log.debug("getProperties(URL): called"); + + // Open the URL as an input stream + InputStream is = url.openStream(); + + // Create properties object loaded from the stream + Properties properties = getProperties(is); + + // Close the url + is.close(); + + return properties; + } + + /** + * Get properties from a path name. The path name may refer to either a file or a URL. + * + * @param pathname The path name. + * + * @return The properties loaded from the file or URL. + * + * @throws IOException If there is an I/O error reading from the URL or file named by the path. + */ + public static Properties getProperties(String pathname) throws IOException + { + log.debug("getProperties(String): called"); + + // Check that the path is not null + if (pathname == null) + { + return null; + } + + // Check if the path is a URL + if (isURL(pathname)) + { + // The path is a URL + return getProperties(new URL(pathname)); + } + else + { + // Assume the path is a file name + return getProperties(new File(pathname)); + } + } + + /** + * Trims whitespace from property values. This method returns a new set of properties + * the same as the properties specified as an argument but with any white space removed by + * the {@link java.lang.String#trim} method. + * + * @param properties The properties to trim whitespace from. + * + * @return The white space trimmed properties. + */ + public static Properties trim(Properties properties) + { + Properties trimmedProperties = new Properties(); + + // Loop over all the properties + for (Iterator i = properties.keySet().iterator(); i.hasNext();) + { + String next = (String) i.next(); + String nextValue = properties.getProperty(next); + + // Trim the value if it is not null + if (nextValue != null) + { + nextValue.trim(); + } + + // Store the trimmed value in the trimmed properties + trimmedProperties.setProperty(next, nextValue); + } + + return trimmedProperties; + } + + /** + * Helper method. Guesses whether a string is a URL or not. A String is considered to be a url if it begins with + * http:, ftp:, or uucp:. + * + * @param name The string to test for being a URL. + * + * @return True if the string is a URL and false if not. + */ + private static boolean isURL(String name) + { + return (name.toLowerCase().startsWith("http:") || name.toLowerCase().startsWith("ftp:") + || name.toLowerCase().startsWith("uucp:")); + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/ReflectionUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/util/ReflectionUtils.java new file mode 100644 index 0000000000..724f504474 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/ReflectionUtils.java @@ -0,0 +1,228 @@ +/* + * + * 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.util; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Provides helper methods for operating on classes and methods using reflection. Reflection methods tend to return + * a lot of checked exception so writing code to use them can be tedious and harder to read, especially when such errors + * are not expected to occur. This class always works with {@link ReflectionUtilsException}, which is a runtime exception, + * to wrap the checked exceptions raised by the standard Java reflection methods. Code using it does not normally + * expect these errors to occur, usually does not have a recovery mechanism for them when they do, but is cleaner, + * quicker to write and easier to read in the majority of cases. + * + *

      + *
      CRC Card
      Responsibilities Collaborations + *
      Look up Classes by name. + *
      Instantiate Classes by no-arg constructor. + *
      + */ +public class ReflectionUtils +{ + /** + * Gets the Class object for a named class. + * + * @param className The class to get the Class object for. + * + * @return The Class object for the named class. + */ + public static Class forName(String className) + { + try + { + return Class.forName(className); + } + catch (ClassNotFoundException e) + { + throw new ReflectionUtilsException("ClassNotFoundException whilst finding class.", e); + } + } + + /** + * Creates an instance of a Class, instantiated through its no-args constructor. + * + * @param cls The Class to instantiate. + * @param The Class type. + * + * @return An instance of the class. + */ + public static T newInstance(Class cls) + { + try + { + return cls.newInstance(); + } + catch (InstantiationException e) + { + throw new ReflectionUtilsException("InstantiationException whilst instantiating class.", e); + } + catch (IllegalAccessException e) + { + throw new ReflectionUtilsException("IllegalAccessException whilst instantiating class.", e); + } + } + + /** + * Calls a named method on an object with a specified set of parameters, any Java access modifier are overridden. + * + * @param o The object to call. + * @param method The method name to call. + * @param params The parameters to pass. + * @param paramClasses The argument types. + * + * @return The return value from the method call. + */ + public static Object callMethodOverridingIllegalAccess(Object o, String method, Object[] params, Class[] paramClasses) + { + // Get the objects class. + Class cls = o.getClass(); + + // Get the classes of the parameters. + /*Class[] paramClasses = new Class[params.length]; + + for (int i = 0; i < params.length; i++) + { + paramClasses[i] = params[i].getClass(); + }*/ + + try + { + // Try to find the matching method on the class. + Method m = cls.getDeclaredMethod(method, paramClasses); + + // Make it accessible. + m.setAccessible(true); + + // Invoke it with the parameters. + return m.invoke(o, params); + } + catch (NoSuchMethodException e) + { + throw new RuntimeException(e); + } + catch (IllegalAccessException e) + { + throw new RuntimeException(e); + } + catch (InvocationTargetException e) + { + throw new RuntimeException(e); + } + } + + /** + * Calls a named method on an object with a specified set of parameters. + * + * @param o The object to call. + * @param method The method name to call. + * @param params The parameters to pass. + * + * @return The return value from the method call. + */ + public static Object callMethod(Object o, String method, Object[] params) + { + // Get the objects class. + Class cls = o.getClass(); + + // Get the classes of the parameters. + Class[] paramClasses = new Class[params.length]; + + for (int i = 0; i < params.length; i++) + { + paramClasses[i] = params[i].getClass(); + } + + try + { + // Try to find the matching method on the class. + Method m = cls.getMethod(method, paramClasses); + + // Invoke it with the parameters. + return m.invoke(o, params); + } + catch (NoSuchMethodException e) + { + throw new RuntimeException(e); + } + catch (IllegalAccessException e) + { + throw new RuntimeException(e); + } + catch (InvocationTargetException e) + { + throw new RuntimeException(e); + } + } + + /** + * Calls a constuctor witht the specified arguments. + * + * @param constructor The constructor. + * @param args The arguments. + * @param The Class type. + * + * @return An instance of the class that the constructor is for. + */ + public static T newInstance(Constructor constructor, Object[] args) + { + try + { + return constructor.newInstance(args); + } + catch (InstantiationException e) + { + throw new RuntimeException(e); + } + catch (IllegalAccessException e) + { + throw new RuntimeException(e); + } + catch (InvocationTargetException e) + { + throw new RuntimeException(e); + } + } + + /** + * Gets the constructor of a class that takes the specified set of arguments if any matches. If no matching + * constructor is found then a runtime exception is raised. + * + * @param cls The class to get a constructor from. + * @param args The arguments to match. + * @param The class type. + * + * @return The constructor. + */ + public static Constructor getConstructor(Class cls, Class[] args) + { + try + { + return cls.getConstructor(args); + } + catch (NoSuchMethodException e) + { + throw new RuntimeException(e); + } + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/ReflectionUtilsException.java b/qpid/java/common/src/main/java/org/apache/qpid/util/ReflectionUtilsException.java new file mode 100644 index 0000000000..20499641ac --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/ReflectionUtilsException.java @@ -0,0 +1,44 @@ +/* + * + * 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.util; + +/** + * Wraps a checked exception that occurs when {@link ReflectionUtils} encounters checked exceptions using standard + * Java reflection methods. + * + *

      + *
      CRC Card
      Responsibilities Collaborations + *
      Wrap a checked reflection exception. + *
      + */ +public class ReflectionUtilsException extends RuntimeException +{ + /** + * Creates a runtime reflection exception, from a checked one. + * + * @param message The message. + * @param cause The causing exception. + */ + public ReflectionUtilsException(String message, Throwable cause) + { + super(message, cause); + } +} -- cgit v1.2.1 From dd42e2aaa19b0d0a8dac5b3511dbfa60772ed8de Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Mon, 19 Mar 2007 13:11:41 +0000 Subject: Merged revisions 519933 via svnmerge from https://svn.apache.org/repos/asf/incubator/qpid/branches/M2 ........ r519933 | rgreig | 2007-03-19 12:55:39 +0000 (Mon, 19 Mar 2007) | 1 line Correction to exception type thrown. ........ git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@519938 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/util/ReflectionUtils.java | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/ReflectionUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/util/ReflectionUtils.java index 724f504474..495918911a 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/ReflectionUtils.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/ReflectionUtils.java @@ -119,15 +119,15 @@ public class ReflectionUtils } catch (NoSuchMethodException e) { - throw new RuntimeException(e); + throw new ReflectionUtilsException("NoSuchMethodException.", e); } catch (IllegalAccessException e) { - throw new RuntimeException(e); + throw new ReflectionUtilsException("IllegalAccessException.", e); } catch (InvocationTargetException e) { - throw new RuntimeException(e); + throw new ReflectionUtilsException("InvocationTargetException", e); } } @@ -163,15 +163,15 @@ public class ReflectionUtils } catch (NoSuchMethodException e) { - throw new RuntimeException(e); + throw new ReflectionUtilsException("NoSuchMethodException.", e); } catch (IllegalAccessException e) { - throw new RuntimeException(e); + throw new ReflectionUtilsException("IllegalAccessException", e); } catch (InvocationTargetException e) { - throw new RuntimeException(e); + throw new ReflectionUtilsException("InvocationTargetException", e); } } @@ -192,15 +192,15 @@ public class ReflectionUtils } catch (InstantiationException e) { - throw new RuntimeException(e); + throw new ReflectionUtilsException("InstantiationException", e); } catch (IllegalAccessException e) { - throw new RuntimeException(e); + throw new ReflectionUtilsException("IllegalAccessException", e); } catch (InvocationTargetException e) { - throw new RuntimeException(e); + throw new ReflectionUtilsException("InvocationTargetException", e); } } @@ -222,7 +222,7 @@ public class ReflectionUtils } catch (NoSuchMethodException e) { - throw new RuntimeException(e); + throw new ReflectionUtilsException("NoSuchMethodException", e); } } } -- cgit v1.2.1 From 0370e5550e1d9bc72d742bbbee1f6f0e2835406e Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Thu, 5 Apr 2007 13:36:04 +0000 Subject: Merged revisions 525531-525536 via svnmerge from https://svn.apache.org/repos/asf/incubator/qpid/branches/M2 ........ r525531 | rgreig | 2007-04-04 16:18:44 +0100 (Wed, 04 Apr 2007) | 1 line Added standard command line handline ........ r525533 | rgreig | 2007-04-04 16:19:38 +0100 (Wed, 04 Apr 2007) | 1 line Added simeple file copy function. ........ r525535 | rgreig | 2007-04-04 16:20:30 +0100 (Wed, 04 Apr 2007) | 1 line Added comments and logging to track down bug. ........ r525536 | rgreig | 2007-04-04 16:21:43 +0100 (Wed, 04 Apr 2007) | 1 line Fixed dangling transaction problem by correctly binding queue. ........ git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@525825 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/util/CommandLineParser.java | 42 +++++++++++++++++++--- .../main/java/org/apache/qpid/util/FileUtils.java | 36 +++++++++++++++++++ 2 files changed, 73 insertions(+), 5 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java b/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java index 6173780aa7..9051d6b470 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java @@ -143,8 +143,8 @@ public class CommandLineParser String[] nextOptionSpec = config[i]; addOption(nextOptionSpec[0], nextOptionSpec[1], (nextOptionSpec.length > 2) ? nextOptionSpec[2] : null, - (nextOptionSpec.length > 3) ? ("true".equals(nextOptionSpec[3]) ? true : false) : false, - (nextOptionSpec.length > 4) ? nextOptionSpec[4] : null); + (nextOptionSpec.length > 3) ? ("true".equals(nextOptionSpec[3]) ? true : false) : false, + (nextOptionSpec.length > 4) ? nextOptionSpec[4] : null); } } @@ -209,8 +209,9 @@ public class CommandLineParser // Print usage on each of the command line options. for (CommandLineOption optionInfo : optionMap.values()) { - result += optionInfo.option + " " + ((optionInfo.argument != null) ? (optionInfo.argument + " ") : "") - + optionInfo.comment + "\n"; + result += + optionInfo.option + " " + ((optionInfo.argument != null) ? (optionInfo.argument + " ") : "") + + optionInfo.comment + "\n"; } return result; @@ -603,6 +604,37 @@ public class CommandLineParser } } + /** + * Extracts all name=value pairs from the command line, sets them all as system properties and also returns + * a map of properties containing them. + * + * @param args The command line. + * + * @return A set of properties containing all name=value pairs from the command line. + */ + public static Properties processCommandLine(String[] args, CommandLineParser commandLine) + { + // Capture the command line arguments or display errors and correct usage and then exit. + Properties options = null; + + try + { + options = commandLine.parseCommandLine(args); + + // Add all the trailing command line options (name=value pairs) to system properties. They may be picked up + // from there. + commandLine.addCommandLineToSysProperties(); + } + catch (IllegalArgumentException e) + { + System.out.println(commandLine.getErrors()); + System.out.println(commandLine.getUsage()); + System.exit(1); + } + + return options; + } + /** * Holds information about a command line options. This includes what its name is, whether or not it is a flag, * whether or not it is mandatory, what its user comment is, what its argument reminder text is and what its @@ -646,7 +678,7 @@ public class CommandLineParser * @param formatRegexp The regular expression that the argument to this option must meet to be valid. */ public CommandLineOption(String option, boolean expectsArgs, String comment, String argument, boolean mandatory, - String formatRegexp) + String formatRegexp) { this.option = option; this.expectsArgs = expectsArgs; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java index ba79a6e8d4..3c8d3f916b 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java @@ -158,4 +158,40 @@ public class FileUtils return is; } + + /** + * Copies the specified source file to the specified destintaion file. If the destinationst file does not exist, + * it is created. + * + * @param src The source file name. + * @param dst The destination file name. + */ + public static void copy(File src, File dst) + { + try + { + InputStream in = new FileInputStream(src); + if (!dst.exists()) + { + dst.createNewFile(); + } + + OutputStream out = new FileOutputStream(dst); + + // Transfer bytes from in to out + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) + { + out.write(buf, 0, len); + } + + in.close(); + out.close(); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + } } -- cgit v1.2.1 From 64f42a1b3dea9d64e5e26dd3e3d2242ad16f4568 Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Sat, 7 Apr 2007 16:03:07 +0000 Subject: Refactoring and multi-version support git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@526447 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/AMQChannelException.java | 4 +- .../org/apache/qpid/AMQConnectionException.java | 3 +- .../java/org/apache/qpid/codec/AMQDecoder.java | 16 ++- .../org/apache/qpid/common/ClientProperties.java | 20 ++- .../main/java/org/apache/qpid/framing/AMQBody.java | 21 ++- .../java/org/apache/qpid/framing/AMQBodyImpl.java | 27 ++++ .../apache/qpid/framing/AMQDataBlockDecoder.java | 2 +- .../org/apache/qpid/framing/AMQMethodBody.java | 136 +++--------------- .../apache/qpid/framing/AMQMethodBodyFactory.java | 2 +- .../org/apache/qpid/framing/AMQMethodBodyImpl.java | 102 +++++++++++++ .../qpid/framing/AMQMethodBodyInstanceFactory.java | 3 +- .../org/apache/qpid/framing/AMQMethodFactory.java | 90 ++++++++++++ .../java/org/apache/qpid/framing/ContentBody.java | 2 +- .../apache/qpid/framing/ContentBodyFactory.java | 2 +- .../org/apache/qpid/framing/ContentHeaderBody.java | 4 +- .../qpid/framing/ContentHeaderBodyFactory.java | 2 +- .../framing/ContentHeaderPropertiesFactory.java | 4 +- .../org/apache/qpid/framing/HeartbeatBody.java | 6 +- .../apache/qpid/framing/HeartbeatBodyFactory.java | 2 +- .../java/org/apache/qpid/framing/MainRegistry.java | 35 +++++ .../apache/qpid/framing/MethodConverter_8_0.java | 22 ++- .../qpid/framing/VersionSpecificRegistry.java | 2 +- .../abstraction/MessagePublishInfoConverter.java | 3 +- .../ProtocolVersionMethodConverter.java | 3 +- .../qpid/framing/amqp_8_0/AMQMethodBody_8_0.java | 160 +++++++++++++++++++++ .../framing/amqp_8_0/AMQMethodFactory_8_0.java | 117 +++++++++++++++ .../java/org/apache/qpid/pool/PoolingFilter.java | 1 + .../org/apache/qpid/protocol/AMQMethodEvent.java | 1 + .../apache/qpid/protocol/AMQMethodListener.java | 4 +- .../protocol/AMQVersionAwareProtocolSession.java | 4 +- .../apache/qpid/protocol/ProtocolVersionAware.java | 5 +- 31 files changed, 631 insertions(+), 174 deletions(-) create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBodyImpl.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyImpl.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodFactory.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/MainRegistry.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodBody_8_0.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodFactory_8_0.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java index d8c9b287bd..12120bd10d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java @@ -23,6 +23,8 @@ package org.apache.qpid; import org.apache.qpid.framing.AMQFrame; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.ChannelCloseBody; +import org.apache.qpid.framing.amqp_8_0.ConnectionCloseBodyImpl; +import org.apache.qpid.framing.amqp_8_0.ChannelCloseBodyImpl; import org.apache.qpid.protocol.AMQConstant; public class AMQChannelException extends AMQException @@ -53,6 +55,6 @@ public class AMQChannelException extends AMQException public AMQFrame getCloseFrame(int channel) { - return ChannelCloseBody.createAMQFrame(channel, major, minor, _classId, _methodId, getErrorCode().getCode(), new AMQShortString(getMessage())); + return new AMQFrame(channel, new ChannelCloseBodyImpl(getErrorCode().getCode(), new AMQShortString(getMessage()),0,0)); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java index c4f80191a3..094e26802d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java @@ -24,6 +24,7 @@ package org.apache.qpid; import org.apache.qpid.framing.AMQFrame; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.ConnectionCloseBody; +import org.apache.qpid.framing.amqp_8_0.ConnectionCloseBodyImpl; import org.apache.qpid.protocol.AMQConstant; public class AMQConnectionException extends AMQException @@ -57,7 +58,7 @@ public class AMQConnectionException extends AMQException public AMQFrame getCloseFrame(int channel) { - return ConnectionCloseBody.createAMQFrame(channel, major, minor, _classId, _methodId, getErrorCode().getCode(), new AMQShortString(getMessage())); + return new AMQFrame(channel, new ConnectionCloseBodyImpl(getErrorCode().getCode(), new AMQShortString(getMessage()),_classId,_methodId)); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java index bb981a242f..6e0a5c3786 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java @@ -48,13 +48,21 @@ public class AMQDecoder extends CumulativeProtocolDecoder protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { - if (_expectProtocolInitiation) + try { - return doDecodePI(session, in, out); + if (_expectProtocolInitiation) + { + return doDecodePI(session, in, out); + } + else + { + return doDecodeDataBlock(session, in, out); + } } - else + catch (Exception e) { - return doDecodeDataBlock(session, in, out); + e.printStackTrace(); + throw e; } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java index 07371b5182..1f1911aa35 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java @@ -20,10 +20,28 @@ */ package org.apache.qpid.common; +import org.apache.qpid.framing.AMQShortString; + public enum ClientProperties { + + instance, product, version, - platform + platform; + + + private final AMQShortString _name; + + private ClientProperties() + { + _name = new AMQShortString(toString()); + } + + public AMQShortString getName() + { + return _name; + } + } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java index ebeea8d2b4..4dd5ab7a9a 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java @@ -7,9 +7,9 @@ * 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 @@ -22,18 +22,15 @@ package org.apache.qpid.framing; import org.apache.mina.common.ByteBuffer; -public abstract class AMQBody +public interface AMQBody { - public abstract byte getFrameType(); - - /** + byte getFrameType(); + + /** * Get the size of the body * @return unsigned short */ - protected abstract int getSize(); - - protected abstract void writePayload(ByteBuffer buffer); - - protected abstract void populateFromBuffer(ByteBuffer buffer, long size) - throws AMQFrameDecodingException, AMQProtocolVersionException; + int getSize(); + + void writePayload(ByteBuffer buffer); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBodyImpl.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBodyImpl.java new file mode 100644 index 0000000000..6b2d1feae5 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBodyImpl.java @@ -0,0 +1,27 @@ +/* + * + * 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.framing; + + +public abstract class AMQBodyImpl implements AMQBody +{ + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java index 43f888c029..2ecd4d4650 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java @@ -72,7 +72,7 @@ public class AMQDataBlockDecoder final byte type = in.get(); BodyFactory bodyFactory; - if(type == AMQMethodBody.TYPE) + if(type == AMQMethodBodyImpl.TYPE) { bodyFactory = (BodyFactory) session.getAttribute(SESSION_METHOD_BODY_FACTORY); if(bodyFactory == null) diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java index f2e91083ca..ddd03145c4 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java @@ -1,132 +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. - * - */ package org.apache.qpid.framing; -import org.apache.mina.common.ByteBuffer; import org.apache.qpid.AMQChannelException; import org.apache.qpid.AMQConnectionException; import org.apache.qpid.protocol.AMQConstant; -public abstract class AMQMethodBody extends AMQBody +/** + * Created by IntelliJ IDEA. + * User: U146758 + * Date: 08-Mar-2007 + * Time: 11:30:28 + * To change this template use File | Settings | File Templates. + */ +public interface AMQMethodBody extends AMQBody { - public static final byte TYPE = 1; - - /** AMQP version */ - protected byte major; - protected byte minor; - - public byte getMajor() - { - return major; - } - - public byte getMinor() - { - return minor; - } - - public AMQMethodBody(byte major, byte minor) - { - this.major = major; - this.minor = minor; - } - - /** unsigned short */ - protected abstract int getBodySize(); - - /** @return unsigned short */ - protected abstract int getClazz(); - - /** @return unsigned short */ - protected abstract int getMethod(); - - protected abstract void writeMethodPayload(ByteBuffer buffer); - - public byte getFrameType() - { - return TYPE; - } - - protected int getSize() - { - return 2 + 2 + getBodySize(); - } - - protected void writePayload(ByteBuffer buffer) - { - EncodingUtils.writeUnsignedShort(buffer, getClazz()); - EncodingUtils.writeUnsignedShort(buffer, getMethod()); - writeMethodPayload(buffer); - } - - protected abstract void populateMethodBodyFromBuffer(ByteBuffer buffer) throws AMQFrameDecodingException; - - protected void populateFromBuffer(ByteBuffer buffer, long size) throws AMQFrameDecodingException - { - populateMethodBodyFromBuffer(buffer); - } - - public String toString() - { - StringBuffer buf = new StringBuffer(getClass().getName()); - buf.append("[ Class: ").append(getClazz()); - buf.append(" Method: ").append(getMethod()).append(']'); - return buf.toString(); - } - - /** - * Creates an AMQChannelException for the corresponding body type (a channel exception should include the class and - * method ids of the body it resulted from). - */ - - /** - * Convenience Method to create a channel not found exception - * - * @param channelId The channel id that is not found - * - * @return new AMQChannelException - */ - public AMQChannelException getChannelNotFoundException(int channelId) - { - return getChannelException(AMQConstant.NOT_FOUND, "Channel not found for id:" + channelId); - } - - public AMQChannelException getChannelException(AMQConstant code, String message) - { - return new AMQChannelException(code, message, getClazz(), getMethod(), major, minor); - } + public int getClazz(); + public int getMethod(); + + AMQChannelException getChannelNotFoundException(int channelId); - public AMQChannelException getChannelException(AMQConstant code, String message, Throwable cause) - { - return new AMQChannelException(code, message, getClazz(), getMethod(), major, minor, cause); - } + AMQChannelException getChannelException(AMQConstant code, String message); - public AMQConnectionException getConnectionException(AMQConstant code, String message) - { - return new AMQConnectionException(code, message, getClazz(), getMethod(), major, minor); - } + AMQChannelException getChannelException(AMQConstant code, String message, Throwable cause); - public AMQConnectionException getConnectionException(AMQConstant code, String message, Throwable cause) - { - return new AMQConnectionException(code, message, getClazz(), getMethod(), major, minor, cause); - } + AMQConnectionException getConnectionException(AMQConstant code, String message); + AMQConnectionException getConnectionException(AMQConstant code, String message, Throwable cause); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java index 5293c00379..f5cd971c0e 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java @@ -37,6 +37,6 @@ public class AMQMethodBodyFactory implements BodyFactory public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException { - return _protocolSession.getRegistry().get((short)in.getUnsignedShort(), (short)in.getUnsignedShort(), in, bodySize); + return _protocolSession.getRegistry().convertToBody(in, bodySize); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyImpl.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyImpl.java new file mode 100644 index 0000000000..0a802f8857 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyImpl.java @@ -0,0 +1,102 @@ +/* + * + * 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.framing; + +import org.apache.mina.common.ByteBuffer; +import org.apache.qpid.AMQChannelException; +import org.apache.qpid.AMQConnectionException; +import org.apache.qpid.protocol.AMQConstant; + +public abstract class AMQMethodBodyImpl extends AMQBodyImpl implements AMQMethodBody +{ + public static final byte TYPE = 1; + + + public abstract byte getMajor(); + public abstract byte getMinor(); + + /** unsigned short */ + protected abstract int getBodySize(); + + /** @return unsigned short */ + public abstract int getClazz(); + + /** @return unsigned short */ + public abstract int getMethod(); + + protected abstract void writeMethodPayload(ByteBuffer buffer); + + public byte getFrameType() + { + return TYPE; + } + + public int getSize() + { + return 2 + 2 + getBodySize(); + } + + public void writePayload(ByteBuffer buffer) + { + EncodingUtils.writeUnsignedShort(buffer, getClazz()); + EncodingUtils.writeUnsignedShort(buffer, getMethod()); + writeMethodPayload(buffer); + } + + + /** + * Creates an AMQChannelException for the corresponding body type (a channel exception should include the class and + * method ids of the body it resulted from). + */ + + /** + * Convenience Method to create a channel not found exception + * + * @param channelId The channel id that is not found + * + * @return new AMQChannelException + */ + public AMQChannelException getChannelNotFoundException(int channelId) + { + return getChannelException(AMQConstant.NOT_FOUND, "Channel not found for id:" + channelId); + } + + public AMQChannelException getChannelException(AMQConstant code, String message) + { + return new AMQChannelException(code, message, getClazz(), getMethod(), getMajor(), getMinor()); + } + + public AMQChannelException getChannelException(AMQConstant code, String message, Throwable cause) + { + return new AMQChannelException(code, message, getClazz(), getMethod(), getMajor(), getMinor(), cause); + } + + public AMQConnectionException getConnectionException(AMQConstant code, String message) + { + return new AMQConnectionException(code, message, getClazz(), getMethod(), getMajor(), getMinor()); + } + + public AMQConnectionException getConnectionException(AMQConstant code, String message, Throwable cause) + { + return new AMQConnectionException(code, message, getClazz(), getMethod(), getMajor(), getMinor(), cause); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java index cfbc9d1828..9a7868f3cd 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java @@ -5,6 +5,5 @@ import org.apache.mina.common.ByteBuffer; public abstract interface AMQMethodBodyInstanceFactory { - public AMQMethodBody newInstance(byte major, byte minor, ByteBuffer buffer, long size) throws AMQFrameDecodingException; - public AMQMethodBody newInstance(byte major, byte minor, int clazzID, int methodID, ByteBuffer buffer, long size) throws AMQFrameDecodingException; + public AMQMethodBody newInstance(ByteBuffer buffer, long size) throws AMQFrameDecodingException; } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodFactory.java new file mode 100644 index 0000000000..4ffc9e0066 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodFactory.java @@ -0,0 +1,90 @@ +/* + * + * 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.framing; + +import org.apache.mina.common.ByteBuffer; + + +public interface AMQMethodFactory +{ + + // Connection Methods + + ConnectionCloseBody createConnectionClose(); + + // Access Methods + + AccessRequestBody createAccessRequest(boolean active, boolean exclusive, boolean passive, boolean read, AMQShortString realm, boolean write); + + + // Tx Methods + + TxSelectBody createTxSelect(); + + TxCommitBody createTxCommit(); + + TxRollbackBody createTxRollback(); + + // Channel Methods + + ChannelOpenBody createChannelOpen(); + + ChannelCloseBody createChannelClose(int replyCode, AMQShortString replyText); + + ChannelFlowBody createChannelFlow(boolean active); + + + // Exchange Methods + + + ExchangeBoundBody createExchangeBound(AMQShortString exchangeName, + AMQShortString queueName, + AMQShortString routingKey); + + ExchangeDeclareBody createExchangeDeclare(AMQShortString name, AMQShortString type, int ticket); + + + // Queue Methods + + QueueDeclareBody createQueueDeclare(AMQShortString name, FieldTable arguments, boolean autoDelete, boolean durable, boolean exclusive, boolean passive, int ticket); + + QueueBindBody createQueueBind(AMQShortString queueName, AMQShortString exchangeName, AMQShortString routingKey, FieldTable arguments, int ticket); + + QueueDeleteBody createQueueDelete(AMQShortString queueName, boolean ifEmpty, boolean ifUnused, int ticket); + + + // Message Methods + + // In different versions of the protocol we change the class used for message transfer + // abstract this out so the appropriate methods are created + AMQMethodBody createRecover(boolean requeue); + + AMQMethodBody createConsumer(AMQShortString tag, AMQShortString queueName, FieldTable arguments, boolean noAck, boolean exclusive, boolean noLocal, int ticket); + + AMQMethodBody createConsumerCancel(AMQShortString consumerTag); + + AMQMethodBody createAcknowledge(long deliveryTag, boolean multiple); + + AMQMethodBody createRejectBody(long deliveryTag, boolean requeue); + + AMQMethodBody createMessageQos(int prefetchCount, int prefetchSize); + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java index be38695384..a1aaab06c6 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java @@ -22,7 +22,7 @@ package org.apache.qpid.framing; import org.apache.mina.common.ByteBuffer; -public class ContentBody extends AMQBody +public class ContentBody extends AMQBodyImpl { public static final byte TYPE = 3; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java index 5636229d53..7b6a92e691 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java @@ -39,7 +39,7 @@ public class ContentBodyFactory implements BodyFactory _log.debug("Creating content body factory"); } - public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException + public AMQBodyImpl createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException { return new ContentBody(in, bodySize); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java index 02631a5f88..c71f47bad2 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java @@ -22,7 +22,7 @@ package org.apache.qpid.framing; import org.apache.mina.common.ByteBuffer; -public class ContentHeaderBody extends AMQBody +public class ContentHeaderBody extends AMQBodyImpl { public static final byte TYPE = 2; @@ -110,7 +110,7 @@ public class ContentHeaderBody extends AMQBody properties.writePropertyListPayload(buffer); } - public static AMQFrame createAMQFrame(int channelId, int classId, int weight, BasicContentHeaderProperties properties, + public static AMQFrame createAMQFrame(int channelId, int classId, int weight, CommonContentHeaderProperties properties, long bodySize) { return new AMQFrame(channelId, new ContentHeaderBody(classId, weight, properties, bodySize)); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java index 818fc9cf0c..9570ec800d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java @@ -39,7 +39,7 @@ public class ContentHeaderBodyFactory implements BodyFactory _log.debug("Creating content header body factory"); } - public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException + public AMQBodyImpl createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException { // all content headers are the same - it is only the properties that differ. // the content header body further delegates construction of properties diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java index 7dac018872..a8a8097fd2 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java @@ -20,6 +20,8 @@ */ package org.apache.qpid.framing; +import org.apache.qpid.framing.amqp_8_0.BasicConsumeBodyImpl; + import org.apache.mina.common.ByteBuffer; public class ContentHeaderPropertiesFactory @@ -43,7 +45,7 @@ public class ContentHeaderPropertiesFactory // AMQP version change: "Hardwired" version to major=8, minor=0 // TODO: Change so that the actual version is obtained from // the ProtocolInitiation object for this session. - if (classId == BasicConsumeBody.getClazz((byte)8, (byte)0)) + if (classId == BasicConsumeBodyImpl.CLASS_ID) { properties = new BasicContentHeaderProperties(); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java index 7246c4a1cf..17b2a2f9c2 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java @@ -22,7 +22,7 @@ package org.apache.qpid.framing; import org.apache.mina.common.ByteBuffer; -public class HeartbeatBody extends AMQBody +public class HeartbeatBody extends AMQBodyImpl { public static final byte TYPE = 8; public static AMQFrame FRAME = new HeartbeatBody().toFrame(); @@ -46,12 +46,12 @@ public class HeartbeatBody extends AMQBody return TYPE; } - protected int getSize() + public int getSize() { return 0;//heartbeats we generate have no payload } - protected void writePayload(ByteBuffer buffer) + public void writePayload(ByteBuffer buffer) { } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java index c7ada708dc..2249f1d1cf 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java @@ -24,7 +24,7 @@ import org.apache.mina.common.ByteBuffer; public class HeartbeatBodyFactory implements BodyFactory { - public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException + public AMQBodyImpl createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException { return new HeartbeatBody(); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/MainRegistry.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/MainRegistry.java new file mode 100644 index 0000000000..d75589f914 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/MainRegistry.java @@ -0,0 +1,35 @@ +/* + * + * 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.framing; + +public class MainRegistry +{ + + public static VersionSpecificRegistry getVersionSpecificRegistry(byte versionMajor, byte versionMinor) + { + return null; //To change body of created methods use File | Settings | File Templates. + } + + public static VersionSpecificRegistry getVersionSpecificRegistry(ProtocolVersion pv) + { + return null; //To change body of created methods use File | Settings | File Templates. + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/MethodConverter_8_0.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/MethodConverter_8_0.java index dd93cc97fa..f253372a65 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/MethodConverter_8_0.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/MethodConverter_8_0.java @@ -4,6 +4,7 @@ import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter; import org.apache.qpid.framing.abstraction.ContentChunk; import org.apache.qpid.framing.abstraction.MessagePublishInfo; import org.apache.qpid.framing.abstraction.AbstractMethodConverter; +import org.apache.qpid.framing.amqp_8_0.BasicPublishBodyImpl; import org.apache.mina.common.ByteBuffer; @@ -19,7 +20,7 @@ public class MethodConverter_8_0 extends AbstractMethodConverter implements Prot } - public AMQBody convertToBody(ContentChunk contentChunk) + public AMQBodyImpl convertToBody(ContentChunk contentChunk) { return new ContentBody(contentChunk.getData()); } @@ -52,8 +53,8 @@ public class MethodConverter_8_0 extends AbstractMethodConverter implements Prot public void configure() { - _basicPublishClassId = BasicPublishBody.getClazz(getProtocolMajorVersion(),getProtocolMinorVersion()); - _basicPublishMethodId = BasicPublishBody.getMethod(getProtocolMajorVersion(),getProtocolMinorVersion()); + _basicPublishClassId = BasicPublishBodyImpl.CLASS_ID; + _basicPublishMethodId = BasicPublishBodyImpl.METHOD_ID; } @@ -87,18 +88,15 @@ public class MethodConverter_8_0 extends AbstractMethodConverter implements Prot } - public AMQMethodBody convertToBody(MessagePublishInfo info) + public AMQMethodBodyImpl convertToBody(MessagePublishInfo info) { - return new BasicPublishBody(getProtocolMajorVersion(), - getProtocolMinorVersion(), - _basicPublishClassId, - _basicPublishMethodId, - info.getExchange(), - info.isImmediate(), + return new BasicPublishBodyImpl(0, // ticket + info.getExchange(), + info.getRoutingKey(), info.isMandatory(), - info.getRoutingKey(), - 0) ; // ticket + info.isImmediate() + ) ; } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java index ec371453aa..ebe0b91cf4 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java @@ -179,7 +179,7 @@ public class VersionSpecificRegistry } - return bodyFactory.newInstance(_protocolMajorVersion, _protocolMinorVersion, classID, methodID, in, size); + return bodyFactory.newInstance(in, size); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java index c9e15f18e3..d5da133837 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java @@ -18,12 +18,13 @@ package org.apache.qpid.framing.abstraction; +import org.apache.qpid.framing.AMQMethodBodyImpl; import org.apache.qpid.framing.AMQMethodBody; public interface MessagePublishInfoConverter { public MessagePublishInfo convertToInfo(AMQMethodBody body); - public AMQMethodBody convertToBody(MessagePublishInfo info); + public AMQMethodBodyImpl convertToBody(MessagePublishInfo info); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java index 52e82cdf07..b8e460eb05 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java @@ -18,11 +18,12 @@ package org.apache.qpid.framing.abstraction; +import org.apache.qpid.framing.AMQBodyImpl; import org.apache.qpid.framing.AMQBody; public interface ProtocolVersionMethodConverter extends MessagePublishInfoConverter { - AMQBody convertToBody(ContentChunk contentBody); + AMQBodyImpl convertToBody(ContentChunk contentBody); ContentChunk convertToContentChunk(AMQBody body); void configure(); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodBody_8_0.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodBody_8_0.java new file mode 100644 index 0000000000..63d0f0e407 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodBody_8_0.java @@ -0,0 +1,160 @@ +package org.apache.qpid.framing.amqp_8_0; + +import org.apache.qpid.framing.EncodingUtils; +import org.apache.qpid.framing.AMQFrameDecodingException; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.FieldTable; + +import org.apache.mina.common.ByteBuffer; + +public abstract class AMQMethodBody_8_0 extends org.apache.qpid.framing.AMQMethodBodyImpl +{ + + public byte getMajor() + { + return 8; + } + + public byte getMinor() + { + return 0; + } + + public int getSize() + { + return 2 + 2 + getBodySize(); + } + + public void writePayload(ByteBuffer buffer) + { + EncodingUtils.writeUnsignedShort(buffer, getClazz()); + EncodingUtils.writeUnsignedShort(buffer, getMethod()); + writeMethodPayload(buffer); + } + + + protected byte readByte(ByteBuffer buffer) + { + return buffer.get(); + } + + protected AMQShortString readAMQShortString(ByteBuffer buffer) + { + return EncodingUtils.readAMQShortString(buffer); + } + + protected int getSizeOf(AMQShortString string) + { + return EncodingUtils.encodedShortStringLength(string); + } + + protected void writeByte(ByteBuffer buffer, byte b) + { + buffer.put(b); + } + + protected void writeAMQShortString(ByteBuffer buffer, AMQShortString string) + { + EncodingUtils.writeShortStringBytes(buffer, string); + } + + protected int readInt(ByteBuffer buffer) + { + return buffer.getInt(); + } + + protected void writeInt(ByteBuffer buffer, int i) + { + buffer.putInt(i); + } + + protected FieldTable readFieldTable(ByteBuffer buffer) throws AMQFrameDecodingException + { + return EncodingUtils.readFieldTable(buffer); + } + + protected int getSizeOf(FieldTable table) + { + return EncodingUtils.encodedFieldTableLength(table); //To change body of created methods use File | Settings | File Templates. + } + + protected void writeFieldTable(ByteBuffer buffer, FieldTable table) + { + EncodingUtils.writeFieldTableBytes(buffer, table); + } + + protected long readLong(ByteBuffer buffer) + { + return buffer.getLong(); + } + + protected void writeLong(ByteBuffer buffer, long l) + { + buffer.putLong(l); + } + + protected int getSizeOf(byte[] response) + { + return response == null ? 4 : response.length + 4; //To change body of created methods use File | Settings | File Templates. + } + + protected void writeBytes(ByteBuffer buffer, byte[] data) + { + EncodingUtils.writeLongstr(buffer,data); + } + + protected byte[] readBytes(ByteBuffer buffer) + { + return EncodingUtils.readLongstr(buffer); + } + + protected short readShort(ByteBuffer buffer) + { + return EncodingUtils.readShort(buffer); + } + + protected void writeShort(ByteBuffer buffer, short s) + { + EncodingUtils.writeShort(buffer, s); + } + + protected short readUnsignedByte(ByteBuffer buffer) + { + return buffer.getUnsigned(); + } + + protected void writeUnsignedByte(ByteBuffer buffer, short unsignedByte) + { + EncodingUtils.writeUnsignedByte(buffer, unsignedByte); + } + + protected byte readBitfield(ByteBuffer buffer) + { + return readByte(buffer); + } + + protected int readUnsignedShort(ByteBuffer buffer) + { + return buffer.getUnsignedShort(); + } + + protected void writeBitfield(ByteBuffer buffer, byte bitfield0) + { + buffer.put(bitfield0); + } + + protected void writeUnsignedShort(ByteBuffer buffer, int s) + { + EncodingUtils.writeUnsignedShort(buffer, s); + } + + protected long readUnsignedInteger(ByteBuffer buffer) + { + return buffer.getUnsignedInt(); + } + protected void writeUnsignedInteger(ByteBuffer buffer, long i) + { + EncodingUtils.writeUnsignedInteger(buffer, i); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodFactory_8_0.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodFactory_8_0.java new file mode 100644 index 0000000000..188ed07a70 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodFactory_8_0.java @@ -0,0 +1,117 @@ +package org.apache.qpid.framing.amqp_8_0; + +import org.apache.qpid.framing.*; +import org.apache.qpid.protocol.AMQConstant; + +import org.apache.mina.common.ByteBuffer; + + +public class AMQMethodFactory_8_0 implements AMQMethodFactory +{ + private static final AMQShortString CLIENT_INITIATED_CONNECTION_CLOSE = + new AMQShortString("Client initiated connection close"); + + public ConnectionCloseBody createConnectionClose() + { + return new ConnectionCloseBodyImpl(AMQConstant.REPLY_SUCCESS.getCode(), + CLIENT_INITIATED_CONNECTION_CLOSE, + 0, + 0); + } + + public AccessRequestBody createAccessRequest(boolean active, boolean exclusive, boolean passive, boolean read, AMQShortString realm, boolean write) + { + return new AccessRequestBodyImpl(realm,exclusive,passive,active,write,read); + } + + public TxSelectBody createTxSelect() + { + return new TxSelectBodyImpl(); + } + + public TxCommitBody createTxCommit() + { + return new TxCommitBodyImpl(); + } + + public TxRollbackBody createTxRollback() + { + return new TxRollbackBodyImpl(); + } + + public ChannelOpenBody createChannelOpen() + { + return new ChannelOpenBodyImpl((AMQShortString)null); + } + + public ChannelCloseBody createChannelClose(int replyCode, AMQShortString replyText) + { + return new ChannelCloseBodyImpl(replyCode, replyText, 0, 0); + } + + public ExchangeDeclareBody createExchangeDeclare(AMQShortString name, AMQShortString type, int ticket) + { + return new ExchangeDeclareBodyImpl(ticket,name,type,false,false,false,false,false,null); + } + + public ExchangeBoundBody createExchangeBound(AMQShortString exchangeName, AMQShortString queueName, AMQShortString routingKey) + { + return new ExchangeBoundBodyImpl(exchangeName,routingKey,queueName); + } + + public QueueDeclareBody createQueueDeclare(AMQShortString name, FieldTable arguments, boolean autoDelete, boolean durable, boolean exclusive, boolean passive, int ticket) + { + return new QueueDeclareBodyImpl(ticket,name,passive,durable,exclusive,autoDelete,false,arguments); + } + + public QueueBindBody createQueueBind(AMQShortString queueName, AMQShortString exchangeName, AMQShortString routingKey, FieldTable arguments, int ticket) + { + return new QueueBindBodyImpl(ticket,queueName,exchangeName,routingKey,false,arguments); + } + + public QueueDeleteBody createQueueDelete(AMQShortString queueName, boolean ifEmpty, boolean ifUnused, int ticket) + { + return new QueueDeleteBodyImpl(ticket,queueName,ifUnused,ifEmpty,false); + } + + public ChannelFlowBody createChannelFlow(boolean active) + { + return new ChannelFlowBodyImpl(active); + } + + + // In different versions of the protocol we change the class used for message transfer + // abstract this out so the appropriate methods are created + public AMQMethodBody createRecover(boolean requeue) + { + return new BasicRecoverBodyImpl(requeue); + } + + public AMQMethodBody createConsumer(AMQShortString tag, AMQShortString queueName, FieldTable arguments, boolean noAck, boolean exclusive, boolean noLocal, int ticket) + { + return new BasicConsumeBodyImpl(ticket,queueName,tag,noLocal,noAck,exclusive,false,arguments); + } + + public AMQMethodBody createConsumerCancel(AMQShortString consumerTag) + { + return new BasicCancelBodyImpl(consumerTag, false); + } + + public AMQMethodBody createAcknowledge(long deliveryTag, boolean multiple) + { + return new BasicAckBodyImpl(deliveryTag,multiple); + } + + public AMQMethodBody createRejectBody(long deliveryTag, boolean requeue) + { + return new BasicRejectBodyImpl(deliveryTag, requeue); + } + + public AMQMethodBody createMessageQos(int prefetchCount, int prefetchSize) + { + return new BasicQosBodyImpl(prefetchSize, prefetchCount, false); + } + + + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java index 8126ca4bc8..17a2ec5d4e 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java @@ -136,6 +136,7 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH public void exceptionCaught(final NextFilter nextFilter, final IoSession session, final Throwable cause) throws Exception { + cause.printStackTrace(); nextFilter.exceptionCaught(session,cause); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java index ab36041cb8..db76b6fe7e 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java @@ -20,6 +20,7 @@ */ package org.apache.qpid.protocol; +import org.apache.qpid.framing.AMQMethodBodyImpl; import org.apache.qpid.framing.AMQMethodBody; /** diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java index 85bbe50b11..75ae6645e8 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java @@ -21,6 +21,7 @@ package org.apache.qpid.protocol; import org.apache.qpid.AMQException; +import org.apache.qpid.framing.AMQMethodBodyImpl; import org.apache.qpid.framing.AMQMethodBody; /** @@ -32,7 +33,6 @@ public interface AMQMethodListener /** * Invoked when a method frame has been received * @param evt the event that contains the method and channel - * @param protocolSession the protocol session associated with the event * @return true if the handler has processed the method frame, false otherwise. Note * that this does not prohibit the method event being delivered to subsequent listeners * but can be used to determine if nobody has dealt with an incoming method frame. @@ -40,7 +40,7 @@ public interface AMQMethodListener * to all registered listeners using the error() method (see below) allowing them to * perform cleanup if necessary. */ - boolean methodReceived(AMQMethodEvent evt) throws Exception; + boolean methodReceived(AMQMethodEvent evt) throws AMQException; /** * Callback when an error has occurred. Allows listeners to clean up. diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java index b57c26e496..65f60e7f59 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java @@ -20,9 +20,9 @@ */ package org.apache.qpid.protocol; -import org.apache.qpid.framing.VersionSpecificRegistry; +import org.apache.qpid.framing.MethodRegistry; public interface AMQVersionAwareProtocolSession extends AMQProtocolWriter, ProtocolVersionAware { - public VersionSpecificRegistry getRegistry(); + public MethodRegistry getRegistry(); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java index 64db953bc2..c2c0bf29b7 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java @@ -20,9 +20,10 @@ */ package org.apache.qpid.protocol; +import org.apache.qpid.framing.ProtocolVersion; + public interface ProtocolVersionAware { - public byte getProtocolMinorVersion(); + public ProtocolVersion getProtocolVersion(); - public byte getProtocolMajorVersion(); } -- cgit v1.2.1 From faf86c6e5f484feef6102533b177202282b7f091 Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Mon, 9 Apr 2007 11:45:48 +0000 Subject: Merged revisions 526714 via svnmerge from https://svn.apache.org/repos/asf/incubator/qpid/branches/M2 ........ r526714 | rgreig | 2007-04-09 12:25:32 +0100 (Mon, 09 Apr 2007) | 1 line Purged logging from exception constructors. ........ git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@526720 13f79535-47bb-0310-9956-ffa450edef68 --- .../main/java/org/apache/qpid/AMQException.java | 27 ++------ .../qpid/configuration/PropertyException.java | 20 +----- .../qpid/framing/AMQFrameDecodingException.java | 16 +---- .../qpid/framing/VersionSpecificRegistry.java | 71 +++++++++++----------- 4 files changed, 43 insertions(+), 91 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java index 0222fd9b4e..32c1e76a39 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java @@ -7,9 +7,9 @@ * 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 @@ -20,7 +20,6 @@ */ package org.apache.qpid; -import org.apache.log4j.Logger; import org.apache.qpid.protocol.AMQConstant; /** Generic AMQ exception. */ @@ -31,14 +30,14 @@ public class AMQException extends Exception public AMQException(String message) { super(message); - //fixme This method needs removed and all AMQExceptions need a valid error code + // fixme This method needs removed and all AMQExceptions need a valid error code _errorCode = AMQConstant.getConstant(-1); } public AMQException(String msg, Throwable t) { super(msg, t); - //fixme This method needs removed and all AMQExceptions need a valid error code + // fixme This method needs removed and all AMQExceptions need a valid error code _errorCode = AMQConstant.getConstant(-1); } @@ -54,24 +53,6 @@ public class AMQException extends Exception _errorCode = errorCode; } - public AMQException(Logger logger, String msg, Throwable t) - { - this(msg, t); - logger.error(getMessage(), this); - } - - public AMQException(Logger logger, String msg) - { - this(msg); - logger.error(getMessage(), this); - } - - public AMQException(Logger logger, AMQConstant errorCode, String msg) - { - this(errorCode, msg); - logger.error(getMessage(), this); - } - public AMQConstant getErrorCode() { return _errorCode; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java index 958f59191f..022e7b8a76 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java @@ -7,9 +7,9 @@ * 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 @@ -20,7 +20,6 @@ */ package org.apache.qpid.configuration; -import org.apache.log4j.Logger; import org.apache.qpid.AMQException; import org.apache.qpid.protocol.AMQConstant; @@ -48,19 +47,4 @@ public class PropertyException extends AMQException { super(errorCode, msg); } - - public PropertyException(Logger logger, String msg, Throwable t) - { - super(logger, msg, t); - } - - public PropertyException(Logger logger, String msg) - { - super(logger, msg); - } - - public PropertyException(Logger logger, AMQConstant errorCode, String msg) - { - super(logger, errorCode, msg); - } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java index a24bd6aaa9..a3d4513240 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java @@ -7,9 +7,9 @@ * 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 @@ -20,7 +20,6 @@ */ package org.apache.qpid.framing; -import org.apache.log4j.Logger; import org.apache.qpid.AMQException; public class AMQFrameDecodingException extends AMQException @@ -34,15 +33,4 @@ public class AMQFrameDecodingException extends AMQException { super(message, t); } - - public AMQFrameDecodingException(Logger log, String message) - { - super(log, message); - } - - public AMQFrameDecodingException(Logger log, String message, Throwable t) - { - super(log, message, t); - } - } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java index ebe0b91cf4..085479f227 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java @@ -20,16 +20,16 @@ */ package org.apache.qpid.framing; -import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter; - import org.apache.log4j.Logger; + import org.apache.mina.common.ByteBuffer; +import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter; + public class VersionSpecificRegistry { private static final Logger _log = Logger.getLogger(VersionSpecificRegistry.class); - private final byte _protocolMajorVersion; private final byte _protocolMinorVersion; @@ -48,26 +48,31 @@ public class VersionSpecificRegistry _protocolVersionConverter = loadProtocolVersionConverters(major, minor); } - private static ProtocolVersionMethodConverter loadProtocolVersionConverters(byte protocolMajorVersion, byte protocolMinorVersion) + private static ProtocolVersionMethodConverter loadProtocolVersionConverters(byte protocolMajorVersion, + byte protocolMinorVersion) { try { Class versionMethodConverterClass = - (Class) Class.forName("org.apache.qpid.framing.MethodConverter_"+protocolMajorVersion + "_" + protocolMinorVersion); + (Class) Class.forName("org.apache.qpid.framing.MethodConverter_" + + protocolMajorVersion + "_" + protocolMinorVersion); + return versionMethodConverterClass.newInstance(); } catch (ClassNotFoundException e) { _log.warn("Could not find protocol conversion classes for " + protocolMajorVersion + "-" + protocolMinorVersion); - if(protocolMinorVersion != 0) + if (protocolMinorVersion != 0) { protocolMinorVersion--; + return loadProtocolVersionConverters(protocolMajorVersion, protocolMinorVersion); } else if (protocolMajorVersion != 0) { protocolMajorVersion--; + return loadProtocolVersionConverters(protocolMajorVersion, protocolMinorVersion); } else @@ -75,7 +80,6 @@ public class VersionSpecificRegistry return null; } - } catch (IllegalAccessException e) { @@ -83,7 +87,7 @@ public class VersionSpecificRegistry } catch (InstantiationException e) { - throw new IllegalStateException("Unable to load protocol version converter: ", e); + throw new IllegalStateException("Unable to load protocol version converter: ", e); } } @@ -115,73 +119,68 @@ public class VersionSpecificRegistry public void registerMethod(final short classID, final short methodID, final AMQMethodBodyInstanceFactory instanceFactory) { - if(_registry.length <= classID) + if (_registry.length <= classID) { AMQMethodBodyInstanceFactory[][] oldRegistry = _registry; - _registry = new AMQMethodBodyInstanceFactory[classID+1][]; + _registry = new AMQMethodBodyInstanceFactory[classID + 1][]; System.arraycopy(oldRegistry, 0, _registry, 0, oldRegistry.length); } - if(_registry[classID] == null) + if (_registry[classID] == null) { - _registry[classID] = new AMQMethodBodyInstanceFactory[methodID > DEFAULT_MAX_METHOD_ID ? methodID + 1 : DEFAULT_MAX_METHOD_ID + 1]; + _registry[classID] = + new AMQMethodBodyInstanceFactory[(methodID > DEFAULT_MAX_METHOD_ID) ? (methodID + 1) + : (DEFAULT_MAX_METHOD_ID + 1)]; } - else if(_registry[classID].length <= methodID) + else if (_registry[classID].length <= methodID) { AMQMethodBodyInstanceFactory[] oldMethods = _registry[classID]; - _registry[classID] = new AMQMethodBodyInstanceFactory[methodID+1]; - System.arraycopy(oldMethods,0,_registry[classID],0,oldMethods.length); + _registry[classID] = new AMQMethodBodyInstanceFactory[methodID + 1]; + System.arraycopy(oldMethods, 0, _registry[classID], 0, oldMethods.length); } _registry[classID][methodID] = instanceFactory; } - - public AMQMethodBody get(short classID, short methodID, ByteBuffer in, long size) - throws AMQFrameDecodingException + public AMQMethodBody get(short classID, short methodID, ByteBuffer in, long size) throws AMQFrameDecodingException { AMQMethodBodyInstanceFactory bodyFactory; try { bodyFactory = _registry[classID][methodID]; } - catch(NullPointerException e) + catch (NullPointerException e) { - throw new AMQFrameDecodingException(_log, - "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion - + " (while trying to decode class " + classID + " method " + methodID + "."); + throw new AMQFrameDecodingException("Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + " method " + methodID + "."); } - catch(IndexOutOfBoundsException e) + catch (IndexOutOfBoundsException e) { - if(classID >= _registry.length) + if (classID >= _registry.length) { - throw new AMQFrameDecodingException(_log, - "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion - + " (while trying to decode class " + classID + " method " + methodID + "."); + throw new AMQFrameDecodingException("Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + " method " + methodID + + "."); } else { - throw new AMQFrameDecodingException(_log, - "Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion - + " (while trying to decode class " + classID + " method " + methodID + "."); + throw new AMQFrameDecodingException("Method " + methodID + " unknown in AMQP version " + + _protocolMajorVersion + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + + " method " + methodID + "."); } } - if (bodyFactory == null) { - throw new AMQFrameDecodingException(_log, - "Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion - + " (while trying to decode class " + classID + " method " + methodID + "."); + throw new AMQFrameDecodingException("Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion + + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + " method " + methodID + "."); } - return bodyFactory.newInstance(in, size); - } public ProtocolVersionMethodConverter getProtocolVersionMethodConverter() -- cgit v1.2.1 From 0a35fd3f7ce29edfd4697a9392f4e6eb13ff585e Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Thu, 12 Apr 2007 16:04:05 +0000 Subject: Unbreaking trunk due to erroneous commit git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@527999 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/AMQChannelException.java | 4 +- .../org/apache/qpid/AMQConnectionException.java | 3 +- .../main/java/org/apache/qpid/AMQException.java | 27 +++- .../java/org/apache/qpid/codec/AMQDecoder.java | 16 +-- .../org/apache/qpid/common/ClientProperties.java | 20 +-- .../qpid/configuration/PropertyException.java | 20 ++- .../main/java/org/apache/qpid/framing/AMQBody.java | 75 +++++----- .../apache/qpid/framing/AMQDataBlockDecoder.java | 2 +- .../qpid/framing/AMQFrameDecodingException.java | 16 ++- .../org/apache/qpid/framing/AMQMethodBody.java | 160 +++++++++++++++++---- .../apache/qpid/framing/AMQMethodBodyFactory.java | 2 +- .../qpid/framing/AMQMethodBodyInstanceFactory.java | 3 +- .../java/org/apache/qpid/framing/ContentBody.java | 2 +- .../apache/qpid/framing/ContentBodyFactory.java | 2 +- .../org/apache/qpid/framing/ContentHeaderBody.java | 4 +- .../qpid/framing/ContentHeaderBodyFactory.java | 2 +- .../framing/ContentHeaderPropertiesFactory.java | 4 +- .../org/apache/qpid/framing/HeartbeatBody.java | 6 +- .../apache/qpid/framing/HeartbeatBodyFactory.java | 2 +- .../apache/qpid/framing/MethodConverter_8_0.java | 22 +-- .../qpid/framing/VersionSpecificRegistry.java | 73 +++++----- .../abstraction/MessagePublishInfoConverter.java | 3 +- .../ProtocolVersionMethodConverter.java | 3 +- .../java/org/apache/qpid/pool/PoolingFilter.java | 1 - .../org/apache/qpid/protocol/AMQMethodEvent.java | 1 - .../apache/qpid/protocol/AMQMethodListener.java | 4 +- .../protocol/AMQVersionAwareProtocolSession.java | 4 +- .../apache/qpid/protocol/ProtocolVersionAware.java | 5 +- 28 files changed, 304 insertions(+), 182 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java index 12120bd10d..d8c9b287bd 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java @@ -23,8 +23,6 @@ package org.apache.qpid; import org.apache.qpid.framing.AMQFrame; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.ChannelCloseBody; -import org.apache.qpid.framing.amqp_8_0.ConnectionCloseBodyImpl; -import org.apache.qpid.framing.amqp_8_0.ChannelCloseBodyImpl; import org.apache.qpid.protocol.AMQConstant; public class AMQChannelException extends AMQException @@ -55,6 +53,6 @@ public class AMQChannelException extends AMQException public AMQFrame getCloseFrame(int channel) { - return new AMQFrame(channel, new ChannelCloseBodyImpl(getErrorCode().getCode(), new AMQShortString(getMessage()),0,0)); + return ChannelCloseBody.createAMQFrame(channel, major, minor, _classId, _methodId, getErrorCode().getCode(), new AMQShortString(getMessage())); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java index 094e26802d..c4f80191a3 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java @@ -24,7 +24,6 @@ package org.apache.qpid; import org.apache.qpid.framing.AMQFrame; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.ConnectionCloseBody; -import org.apache.qpid.framing.amqp_8_0.ConnectionCloseBodyImpl; import org.apache.qpid.protocol.AMQConstant; public class AMQConnectionException extends AMQException @@ -58,7 +57,7 @@ public class AMQConnectionException extends AMQException public AMQFrame getCloseFrame(int channel) { - return new AMQFrame(channel, new ConnectionCloseBodyImpl(getErrorCode().getCode(), new AMQShortString(getMessage()),_classId,_methodId)); + return ConnectionCloseBody.createAMQFrame(channel, major, minor, _classId, _methodId, getErrorCode().getCode(), new AMQShortString(getMessage())); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java index 32c1e76a39..0222fd9b4e 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java @@ -7,9 +7,9 @@ * 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 @@ -20,6 +20,7 @@ */ package org.apache.qpid; +import org.apache.log4j.Logger; import org.apache.qpid.protocol.AMQConstant; /** Generic AMQ exception. */ @@ -30,14 +31,14 @@ public class AMQException extends Exception public AMQException(String message) { super(message); - // fixme This method needs removed and all AMQExceptions need a valid error code + //fixme This method needs removed and all AMQExceptions need a valid error code _errorCode = AMQConstant.getConstant(-1); } public AMQException(String msg, Throwable t) { super(msg, t); - // fixme This method needs removed and all AMQExceptions need a valid error code + //fixme This method needs removed and all AMQExceptions need a valid error code _errorCode = AMQConstant.getConstant(-1); } @@ -53,6 +54,24 @@ public class AMQException extends Exception _errorCode = errorCode; } + public AMQException(Logger logger, String msg, Throwable t) + { + this(msg, t); + logger.error(getMessage(), this); + } + + public AMQException(Logger logger, String msg) + { + this(msg); + logger.error(getMessage(), this); + } + + public AMQException(Logger logger, AMQConstant errorCode, String msg) + { + this(errorCode, msg); + logger.error(getMessage(), this); + } + public AMQConstant getErrorCode() { return _errorCode; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java index 6e0a5c3786..bb981a242f 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java @@ -48,21 +48,13 @@ public class AMQDecoder extends CumulativeProtocolDecoder protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { - try + if (_expectProtocolInitiation) { - if (_expectProtocolInitiation) - { - return doDecodePI(session, in, out); - } - else - { - return doDecodeDataBlock(session, in, out); - } + return doDecodePI(session, in, out); } - catch (Exception e) + else { - e.printStackTrace(); - throw e; + return doDecodeDataBlock(session, in, out); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java index 1f1911aa35..07371b5182 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java @@ -20,28 +20,10 @@ */ package org.apache.qpid.common; -import org.apache.qpid.framing.AMQShortString; - public enum ClientProperties { - - instance, product, version, - platform; - - - private final AMQShortString _name; - - private ClientProperties() - { - _name = new AMQShortString(toString()); - } - - public AMQShortString getName() - { - return _name; - } - + platform } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java index 022e7b8a76..958f59191f 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java @@ -7,9 +7,9 @@ * 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 @@ -20,6 +20,7 @@ */ package org.apache.qpid.configuration; +import org.apache.log4j.Logger; import org.apache.qpid.AMQException; import org.apache.qpid.protocol.AMQConstant; @@ -47,4 +48,19 @@ public class PropertyException extends AMQException { super(errorCode, msg); } + + public PropertyException(Logger logger, String msg, Throwable t) + { + super(logger, msg, t); + } + + public PropertyException(Logger logger, String msg) + { + super(logger, msg); + } + + public PropertyException(Logger logger, AMQConstant errorCode, String msg) + { + super(logger, errorCode, msg); + } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java index 4dd5ab7a9a..c497717870 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java @@ -1,36 +1,39 @@ -/* - * - * 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.framing; - -import org.apache.mina.common.ByteBuffer; - -public interface AMQBody -{ - byte getFrameType(); - - /** - * Get the size of the body - * @return unsigned short - */ - int getSize(); - - void writePayload(ByteBuffer buffer); -} +/* + * + * 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.framing; + +import org.apache.mina.common.ByteBuffer; + +public abstract class AMQBody +{ + public abstract byte getFrameType(); + + /** + * Get the size of the body + * @return unsigned short + */ + protected abstract int getSize(); + + protected abstract void writePayload(ByteBuffer buffer); + + protected abstract void populateFromBuffer(ByteBuffer buffer, long size) + throws AMQFrameDecodingException, AMQProtocolVersionException; +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java index 2ecd4d4650..43f888c029 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java @@ -72,7 +72,7 @@ public class AMQDataBlockDecoder final byte type = in.get(); BodyFactory bodyFactory; - if(type == AMQMethodBodyImpl.TYPE) + if(type == AMQMethodBody.TYPE) { bodyFactory = (BodyFactory) session.getAttribute(SESSION_METHOD_BODY_FACTORY); if(bodyFactory == null) diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java index a3d4513240..a24bd6aaa9 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java @@ -7,9 +7,9 @@ * 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 @@ -20,6 +20,7 @@ */ package org.apache.qpid.framing; +import org.apache.log4j.Logger; import org.apache.qpid.AMQException; public class AMQFrameDecodingException extends AMQException @@ -33,4 +34,15 @@ public class AMQFrameDecodingException extends AMQException { super(message, t); } + + public AMQFrameDecodingException(Logger log, String message) + { + super(log, message); + } + + public AMQFrameDecodingException(Logger log, String message, Throwable t) + { + super(log, message, t); + } + } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java index ddd03145c4..23a1ce367e 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java @@ -1,28 +1,132 @@ -package org.apache.qpid.framing; - -import org.apache.qpid.AMQChannelException; -import org.apache.qpid.AMQConnectionException; -import org.apache.qpid.protocol.AMQConstant; - -/** - * Created by IntelliJ IDEA. - * User: U146758 - * Date: 08-Mar-2007 - * Time: 11:30:28 - * To change this template use File | Settings | File Templates. - */ -public interface AMQMethodBody extends AMQBody -{ - public int getClazz(); - public int getMethod(); - - AMQChannelException getChannelNotFoundException(int channelId); - - AMQChannelException getChannelException(AMQConstant code, String message); - - AMQChannelException getChannelException(AMQConstant code, String message, Throwable cause); - - AMQConnectionException getConnectionException(AMQConstant code, String message); - - AMQConnectionException getConnectionException(AMQConstant code, String message, Throwable cause); -} +/* + * + * 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.framing; + +import org.apache.mina.common.ByteBuffer; +import org.apache.qpid.AMQChannelException; +import org.apache.qpid.AMQConnectionException; +import org.apache.qpid.protocol.AMQConstant; + +public abstract class AMQMethodBody extends AMQBody +{ + public static final byte TYPE = 1; + + /** AMQP version */ + protected byte major; + protected byte minor; + + public byte getMajor() + { + return major; + } + + public byte getMinor() + { + return minor; + } + + public AMQMethodBody(byte major, byte minor) + { + this.major = major; + this.minor = minor; + } + + /** unsigned short */ + protected abstract int getBodySize(); + + /** @return unsigned short */ + protected abstract int getClazz(); + + /** @return unsigned short */ + protected abstract int getMethod(); + + protected abstract void writeMethodPayload(ByteBuffer buffer); + + public byte getFrameType() + { + return TYPE; + } + + protected int getSize() + { + return 2 + 2 + getBodySize(); + } + + protected void writePayload(ByteBuffer buffer) + { + EncodingUtils.writeUnsignedShort(buffer, getClazz()); + EncodingUtils.writeUnsignedShort(buffer, getMethod()); + writeMethodPayload(buffer); + } + + protected abstract void populateMethodBodyFromBuffer(ByteBuffer buffer) throws AMQFrameDecodingException; + + protected void populateFromBuffer(ByteBuffer buffer, long size) throws AMQFrameDecodingException + { + populateMethodBodyFromBuffer(buffer); + } + + public String toString() + { + StringBuffer buf = new StringBuffer(getClass().getName()); + buf.append("[ Class: ").append(getClazz()); + buf.append(" Method: ").append(getMethod()).append(']'); + return buf.toString(); + } + + /** + * Creates an AMQChannelException for the corresponding body type (a channel exception should include the class and + * method ids of the body it resulted from). + */ + + /** + * Convenience Method to create a channel not found exception + * + * @param channelId The channel id that is not found + * + * @return new AMQChannelException + */ + public AMQChannelException getChannelNotFoundException(int channelId) + { + return getChannelException(AMQConstant.NOT_FOUND, "Channel not found for id:" + channelId); + } + + public AMQChannelException getChannelException(AMQConstant code, String message) + { + return new AMQChannelException(code, message, getClazz(), getMethod(), major, minor); + } + + public AMQChannelException getChannelException(AMQConstant code, String message, Throwable cause) + { + return new AMQChannelException(code, message, getClazz(), getMethod(), major, minor, cause); + } + + public AMQConnectionException getConnectionException(AMQConstant code, String message) + { + return new AMQConnectionException(code, message, getClazz(), getMethod(), major, minor); + } + + public AMQConnectionException getConnectionException(AMQConstant code, String message, Throwable cause) + { + return new AMQConnectionException(code, message, getClazz(), getMethod(), major, minor, cause); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java index f5cd971c0e..5293c00379 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java @@ -37,6 +37,6 @@ public class AMQMethodBodyFactory implements BodyFactory public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException { - return _protocolSession.getRegistry().convertToBody(in, bodySize); + return _protocolSession.getRegistry().get((short)in.getUnsignedShort(), (short)in.getUnsignedShort(), in, bodySize); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java index 9a7868f3cd..cfbc9d1828 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java @@ -5,5 +5,6 @@ import org.apache.mina.common.ByteBuffer; public abstract interface AMQMethodBodyInstanceFactory { - public AMQMethodBody newInstance(ByteBuffer buffer, long size) throws AMQFrameDecodingException; + public AMQMethodBody newInstance(byte major, byte minor, ByteBuffer buffer, long size) throws AMQFrameDecodingException; + public AMQMethodBody newInstance(byte major, byte minor, int clazzID, int methodID, ByteBuffer buffer, long size) throws AMQFrameDecodingException; } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java index a1aaab06c6..be38695384 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBody.java @@ -22,7 +22,7 @@ package org.apache.qpid.framing; import org.apache.mina.common.ByteBuffer; -public class ContentBody extends AMQBodyImpl +public class ContentBody extends AMQBody { public static final byte TYPE = 3; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java index 7b6a92e691..5636229d53 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java @@ -39,7 +39,7 @@ public class ContentBodyFactory implements BodyFactory _log.debug("Creating content body factory"); } - public AMQBodyImpl createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException + public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException { return new ContentBody(in, bodySize); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java index c71f47bad2..02631a5f88 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBody.java @@ -22,7 +22,7 @@ package org.apache.qpid.framing; import org.apache.mina.common.ByteBuffer; -public class ContentHeaderBody extends AMQBodyImpl +public class ContentHeaderBody extends AMQBody { public static final byte TYPE = 2; @@ -110,7 +110,7 @@ public class ContentHeaderBody extends AMQBodyImpl properties.writePropertyListPayload(buffer); } - public static AMQFrame createAMQFrame(int channelId, int classId, int weight, CommonContentHeaderProperties properties, + public static AMQFrame createAMQFrame(int channelId, int classId, int weight, BasicContentHeaderProperties properties, long bodySize) { return new AMQFrame(channelId, new ContentHeaderBody(classId, weight, properties, bodySize)); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java index 9570ec800d..818fc9cf0c 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java @@ -39,7 +39,7 @@ public class ContentHeaderBodyFactory implements BodyFactory _log.debug("Creating content header body factory"); } - public AMQBodyImpl createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException + public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException { // all content headers are the same - it is only the properties that differ. // the content header body further delegates construction of properties diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java index a8a8097fd2..7dac018872 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java @@ -20,8 +20,6 @@ */ package org.apache.qpid.framing; -import org.apache.qpid.framing.amqp_8_0.BasicConsumeBodyImpl; - import org.apache.mina.common.ByteBuffer; public class ContentHeaderPropertiesFactory @@ -45,7 +43,7 @@ public class ContentHeaderPropertiesFactory // AMQP version change: "Hardwired" version to major=8, minor=0 // TODO: Change so that the actual version is obtained from // the ProtocolInitiation object for this session. - if (classId == BasicConsumeBodyImpl.CLASS_ID) + if (classId == BasicConsumeBody.getClazz((byte)8, (byte)0)) { properties = new BasicContentHeaderProperties(); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java index 17b2a2f9c2..7246c4a1cf 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java @@ -22,7 +22,7 @@ package org.apache.qpid.framing; import org.apache.mina.common.ByteBuffer; -public class HeartbeatBody extends AMQBodyImpl +public class HeartbeatBody extends AMQBody { public static final byte TYPE = 8; public static AMQFrame FRAME = new HeartbeatBody().toFrame(); @@ -46,12 +46,12 @@ public class HeartbeatBody extends AMQBodyImpl return TYPE; } - public int getSize() + protected int getSize() { return 0;//heartbeats we generate have no payload } - public void writePayload(ByteBuffer buffer) + protected void writePayload(ByteBuffer buffer) { } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java index 2249f1d1cf..c7ada708dc 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java @@ -24,7 +24,7 @@ import org.apache.mina.common.ByteBuffer; public class HeartbeatBodyFactory implements BodyFactory { - public AMQBodyImpl createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException + public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException { return new HeartbeatBody(); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/MethodConverter_8_0.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/MethodConverter_8_0.java index f253372a65..dd93cc97fa 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/MethodConverter_8_0.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/MethodConverter_8_0.java @@ -4,7 +4,6 @@ import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter; import org.apache.qpid.framing.abstraction.ContentChunk; import org.apache.qpid.framing.abstraction.MessagePublishInfo; import org.apache.qpid.framing.abstraction.AbstractMethodConverter; -import org.apache.qpid.framing.amqp_8_0.BasicPublishBodyImpl; import org.apache.mina.common.ByteBuffer; @@ -20,7 +19,7 @@ public class MethodConverter_8_0 extends AbstractMethodConverter implements Prot } - public AMQBodyImpl convertToBody(ContentChunk contentChunk) + public AMQBody convertToBody(ContentChunk contentChunk) { return new ContentBody(contentChunk.getData()); } @@ -53,8 +52,8 @@ public class MethodConverter_8_0 extends AbstractMethodConverter implements Prot public void configure() { - _basicPublishClassId = BasicPublishBodyImpl.CLASS_ID; - _basicPublishMethodId = BasicPublishBodyImpl.METHOD_ID; + _basicPublishClassId = BasicPublishBody.getClazz(getProtocolMajorVersion(),getProtocolMinorVersion()); + _basicPublishMethodId = BasicPublishBody.getMethod(getProtocolMajorVersion(),getProtocolMinorVersion()); } @@ -88,15 +87,18 @@ public class MethodConverter_8_0 extends AbstractMethodConverter implements Prot } - public AMQMethodBodyImpl convertToBody(MessagePublishInfo info) + public AMQMethodBody convertToBody(MessagePublishInfo info) { - return new BasicPublishBodyImpl(0, // ticket - info.getExchange(), - info.getRoutingKey(), + return new BasicPublishBody(getProtocolMajorVersion(), + getProtocolMinorVersion(), + _basicPublishClassId, + _basicPublishMethodId, + info.getExchange(), + info.isImmediate(), info.isMandatory(), - info.isImmediate() - ) ; + info.getRoutingKey(), + 0) ; // ticket } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java index 085479f227..ec371453aa 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java @@ -20,16 +20,16 @@ */ package org.apache.qpid.framing; -import org.apache.log4j.Logger; +import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter; +import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; -import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter; - public class VersionSpecificRegistry { private static final Logger _log = Logger.getLogger(VersionSpecificRegistry.class); + private final byte _protocolMajorVersion; private final byte _protocolMinorVersion; @@ -48,31 +48,26 @@ public class VersionSpecificRegistry _protocolVersionConverter = loadProtocolVersionConverters(major, minor); } - private static ProtocolVersionMethodConverter loadProtocolVersionConverters(byte protocolMajorVersion, - byte protocolMinorVersion) + private static ProtocolVersionMethodConverter loadProtocolVersionConverters(byte protocolMajorVersion, byte protocolMinorVersion) { try { Class versionMethodConverterClass = - (Class) Class.forName("org.apache.qpid.framing.MethodConverter_" - + protocolMajorVersion + "_" + protocolMinorVersion); - + (Class) Class.forName("org.apache.qpid.framing.MethodConverter_"+protocolMajorVersion + "_" + protocolMinorVersion); return versionMethodConverterClass.newInstance(); } catch (ClassNotFoundException e) { _log.warn("Could not find protocol conversion classes for " + protocolMajorVersion + "-" + protocolMinorVersion); - if (protocolMinorVersion != 0) + if(protocolMinorVersion != 0) { protocolMinorVersion--; - return loadProtocolVersionConverters(protocolMajorVersion, protocolMinorVersion); } else if (protocolMajorVersion != 0) { protocolMajorVersion--; - return loadProtocolVersionConverters(protocolMajorVersion, protocolMinorVersion); } else @@ -80,6 +75,7 @@ public class VersionSpecificRegistry return null; } + } catch (IllegalAccessException e) { @@ -87,7 +83,7 @@ public class VersionSpecificRegistry } catch (InstantiationException e) { - throw new IllegalStateException("Unable to load protocol version converter: ", e); + throw new IllegalStateException("Unable to load protocol version converter: ", e); } } @@ -119,67 +115,72 @@ public class VersionSpecificRegistry public void registerMethod(final short classID, final short methodID, final AMQMethodBodyInstanceFactory instanceFactory) { - if (_registry.length <= classID) + if(_registry.length <= classID) { AMQMethodBodyInstanceFactory[][] oldRegistry = _registry; - _registry = new AMQMethodBodyInstanceFactory[classID + 1][]; + _registry = new AMQMethodBodyInstanceFactory[classID+1][]; System.arraycopy(oldRegistry, 0, _registry, 0, oldRegistry.length); } - if (_registry[classID] == null) + if(_registry[classID] == null) { - _registry[classID] = - new AMQMethodBodyInstanceFactory[(methodID > DEFAULT_MAX_METHOD_ID) ? (methodID + 1) - : (DEFAULT_MAX_METHOD_ID + 1)]; + _registry[classID] = new AMQMethodBodyInstanceFactory[methodID > DEFAULT_MAX_METHOD_ID ? methodID + 1 : DEFAULT_MAX_METHOD_ID + 1]; } - else if (_registry[classID].length <= methodID) + else if(_registry[classID].length <= methodID) { AMQMethodBodyInstanceFactory[] oldMethods = _registry[classID]; - _registry[classID] = new AMQMethodBodyInstanceFactory[methodID + 1]; - System.arraycopy(oldMethods, 0, _registry[classID], 0, oldMethods.length); + _registry[classID] = new AMQMethodBodyInstanceFactory[methodID+1]; + System.arraycopy(oldMethods,0,_registry[classID],0,oldMethods.length); } _registry[classID][methodID] = instanceFactory; } - public AMQMethodBody get(short classID, short methodID, ByteBuffer in, long size) throws AMQFrameDecodingException + + public AMQMethodBody get(short classID, short methodID, ByteBuffer in, long size) + throws AMQFrameDecodingException { AMQMethodBodyInstanceFactory bodyFactory; try { bodyFactory = _registry[classID][methodID]; } - catch (NullPointerException e) + catch(NullPointerException e) { - throw new AMQFrameDecodingException("Class " + classID + " unknown in AMQP version " + _protocolMajorVersion - + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + " method " + methodID + "."); + throw new AMQFrameDecodingException(_log, + "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion + + " (while trying to decode class " + classID + " method " + methodID + "."); } - catch (IndexOutOfBoundsException e) + catch(IndexOutOfBoundsException e) { - if (classID >= _registry.length) + if(classID >= _registry.length) { - throw new AMQFrameDecodingException("Class " + classID + " unknown in AMQP version " + _protocolMajorVersion - + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + " method " + methodID - + "."); + throw new AMQFrameDecodingException(_log, + "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion + + " (while trying to decode class " + classID + " method " + methodID + "."); } else { - throw new AMQFrameDecodingException("Method " + methodID + " unknown in AMQP version " - + _protocolMajorVersion + "-" + _protocolMinorVersion + " (while trying to decode class " + classID - + " method " + methodID + "."); + throw new AMQFrameDecodingException(_log, + "Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion + + " (while trying to decode class " + classID + " method " + methodID + "."); } } + if (bodyFactory == null) { - throw new AMQFrameDecodingException("Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion - + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + " method " + methodID + "."); + throw new AMQFrameDecodingException(_log, + "Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion + + " (while trying to decode class " + classID + " method " + methodID + "."); } - return bodyFactory.newInstance(in, size); + + return bodyFactory.newInstance(_protocolMajorVersion, _protocolMinorVersion, classID, methodID, in, size); + } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java index d5da133837..c9e15f18e3 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java @@ -18,13 +18,12 @@ package org.apache.qpid.framing.abstraction; -import org.apache.qpid.framing.AMQMethodBodyImpl; import org.apache.qpid.framing.AMQMethodBody; public interface MessagePublishInfoConverter { public MessagePublishInfo convertToInfo(AMQMethodBody body); - public AMQMethodBodyImpl convertToBody(MessagePublishInfo info); + public AMQMethodBody convertToBody(MessagePublishInfo info); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java index b8e460eb05..52e82cdf07 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java @@ -18,12 +18,11 @@ package org.apache.qpid.framing.abstraction; -import org.apache.qpid.framing.AMQBodyImpl; import org.apache.qpid.framing.AMQBody; public interface ProtocolVersionMethodConverter extends MessagePublishInfoConverter { - AMQBodyImpl convertToBody(ContentChunk contentBody); + AMQBody convertToBody(ContentChunk contentBody); ContentChunk convertToContentChunk(AMQBody body); void configure(); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java index 17a2ec5d4e..8126ca4bc8 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java @@ -136,7 +136,6 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH public void exceptionCaught(final NextFilter nextFilter, final IoSession session, final Throwable cause) throws Exception { - cause.printStackTrace(); nextFilter.exceptionCaught(session,cause); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java index db76b6fe7e..ab36041cb8 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java @@ -20,7 +20,6 @@ */ package org.apache.qpid.protocol; -import org.apache.qpid.framing.AMQMethodBodyImpl; import org.apache.qpid.framing.AMQMethodBody; /** diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java index 75ae6645e8..85bbe50b11 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java @@ -21,7 +21,6 @@ package org.apache.qpid.protocol; import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQMethodBodyImpl; import org.apache.qpid.framing.AMQMethodBody; /** @@ -33,6 +32,7 @@ public interface AMQMethodListener /** * Invoked when a method frame has been received * @param evt the event that contains the method and channel + * @param protocolSession the protocol session associated with the event * @return true if the handler has processed the method frame, false otherwise. Note * that this does not prohibit the method event being delivered to subsequent listeners * but can be used to determine if nobody has dealt with an incoming method frame. @@ -40,7 +40,7 @@ public interface AMQMethodListener * to all registered listeners using the error() method (see below) allowing them to * perform cleanup if necessary. */ - boolean methodReceived(AMQMethodEvent evt) throws AMQException; + boolean methodReceived(AMQMethodEvent evt) throws Exception; /** * Callback when an error has occurred. Allows listeners to clean up. diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java index 65f60e7f59..b57c26e496 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java @@ -20,9 +20,9 @@ */ package org.apache.qpid.protocol; -import org.apache.qpid.framing.MethodRegistry; +import org.apache.qpid.framing.VersionSpecificRegistry; public interface AMQVersionAwareProtocolSession extends AMQProtocolWriter, ProtocolVersionAware { - public MethodRegistry getRegistry(); + public VersionSpecificRegistry getRegistry(); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java index c2c0bf29b7..64db953bc2 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java @@ -20,10 +20,9 @@ */ package org.apache.qpid.protocol; -import org.apache.qpid.framing.ProtocolVersion; - public interface ProtocolVersionAware { - public ProtocolVersion getProtocolVersion(); + public byte getProtocolMinorVersion(); + public byte getProtocolMajorVersion(); } -- cgit v1.2.1 From 599defce5ebec6fcaa2721b8a72d9f5589599424 Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Thu, 12 Apr 2007 16:05:50 +0000 Subject: Unbreaking trunk due to erroneous commit git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@528000 13f79535-47bb-0310-9956-ffa450edef68 --- .../qpid/framing/amqp_8_0/AMQMethodBody_8_0.java | 160 --------------------- .../framing/amqp_8_0/AMQMethodFactory_8_0.java | 117 --------------- 2 files changed, 277 deletions(-) delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodBody_8_0.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodFactory_8_0.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodBody_8_0.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodBody_8_0.java deleted file mode 100644 index 63d0f0e407..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodBody_8_0.java +++ /dev/null @@ -1,160 +0,0 @@ -package org.apache.qpid.framing.amqp_8_0; - -import org.apache.qpid.framing.EncodingUtils; -import org.apache.qpid.framing.AMQFrameDecodingException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; - -import org.apache.mina.common.ByteBuffer; - -public abstract class AMQMethodBody_8_0 extends org.apache.qpid.framing.AMQMethodBodyImpl -{ - - public byte getMajor() - { - return 8; - } - - public byte getMinor() - { - return 0; - } - - public int getSize() - { - return 2 + 2 + getBodySize(); - } - - public void writePayload(ByteBuffer buffer) - { - EncodingUtils.writeUnsignedShort(buffer, getClazz()); - EncodingUtils.writeUnsignedShort(buffer, getMethod()); - writeMethodPayload(buffer); - } - - - protected byte readByte(ByteBuffer buffer) - { - return buffer.get(); - } - - protected AMQShortString readAMQShortString(ByteBuffer buffer) - { - return EncodingUtils.readAMQShortString(buffer); - } - - protected int getSizeOf(AMQShortString string) - { - return EncodingUtils.encodedShortStringLength(string); - } - - protected void writeByte(ByteBuffer buffer, byte b) - { - buffer.put(b); - } - - protected void writeAMQShortString(ByteBuffer buffer, AMQShortString string) - { - EncodingUtils.writeShortStringBytes(buffer, string); - } - - protected int readInt(ByteBuffer buffer) - { - return buffer.getInt(); - } - - protected void writeInt(ByteBuffer buffer, int i) - { - buffer.putInt(i); - } - - protected FieldTable readFieldTable(ByteBuffer buffer) throws AMQFrameDecodingException - { - return EncodingUtils.readFieldTable(buffer); - } - - protected int getSizeOf(FieldTable table) - { - return EncodingUtils.encodedFieldTableLength(table); //To change body of created methods use File | Settings | File Templates. - } - - protected void writeFieldTable(ByteBuffer buffer, FieldTable table) - { - EncodingUtils.writeFieldTableBytes(buffer, table); - } - - protected long readLong(ByteBuffer buffer) - { - return buffer.getLong(); - } - - protected void writeLong(ByteBuffer buffer, long l) - { - buffer.putLong(l); - } - - protected int getSizeOf(byte[] response) - { - return response == null ? 4 : response.length + 4; //To change body of created methods use File | Settings | File Templates. - } - - protected void writeBytes(ByteBuffer buffer, byte[] data) - { - EncodingUtils.writeLongstr(buffer,data); - } - - protected byte[] readBytes(ByteBuffer buffer) - { - return EncodingUtils.readLongstr(buffer); - } - - protected short readShort(ByteBuffer buffer) - { - return EncodingUtils.readShort(buffer); - } - - protected void writeShort(ByteBuffer buffer, short s) - { - EncodingUtils.writeShort(buffer, s); - } - - protected short readUnsignedByte(ByteBuffer buffer) - { - return buffer.getUnsigned(); - } - - protected void writeUnsignedByte(ByteBuffer buffer, short unsignedByte) - { - EncodingUtils.writeUnsignedByte(buffer, unsignedByte); - } - - protected byte readBitfield(ByteBuffer buffer) - { - return readByte(buffer); - } - - protected int readUnsignedShort(ByteBuffer buffer) - { - return buffer.getUnsignedShort(); - } - - protected void writeBitfield(ByteBuffer buffer, byte bitfield0) - { - buffer.put(bitfield0); - } - - protected void writeUnsignedShort(ByteBuffer buffer, int s) - { - EncodingUtils.writeUnsignedShort(buffer, s); - } - - protected long readUnsignedInteger(ByteBuffer buffer) - { - return buffer.getUnsignedInt(); - } - protected void writeUnsignedInteger(ByteBuffer buffer, long i) - { - EncodingUtils.writeUnsignedInteger(buffer, i); - } - -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodFactory_8_0.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodFactory_8_0.java deleted file mode 100644 index 188ed07a70..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/amqp_8_0/AMQMethodFactory_8_0.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.apache.qpid.framing.amqp_8_0; - -import org.apache.qpid.framing.*; -import org.apache.qpid.protocol.AMQConstant; - -import org.apache.mina.common.ByteBuffer; - - -public class AMQMethodFactory_8_0 implements AMQMethodFactory -{ - private static final AMQShortString CLIENT_INITIATED_CONNECTION_CLOSE = - new AMQShortString("Client initiated connection close"); - - public ConnectionCloseBody createConnectionClose() - { - return new ConnectionCloseBodyImpl(AMQConstant.REPLY_SUCCESS.getCode(), - CLIENT_INITIATED_CONNECTION_CLOSE, - 0, - 0); - } - - public AccessRequestBody createAccessRequest(boolean active, boolean exclusive, boolean passive, boolean read, AMQShortString realm, boolean write) - { - return new AccessRequestBodyImpl(realm,exclusive,passive,active,write,read); - } - - public TxSelectBody createTxSelect() - { - return new TxSelectBodyImpl(); - } - - public TxCommitBody createTxCommit() - { - return new TxCommitBodyImpl(); - } - - public TxRollbackBody createTxRollback() - { - return new TxRollbackBodyImpl(); - } - - public ChannelOpenBody createChannelOpen() - { - return new ChannelOpenBodyImpl((AMQShortString)null); - } - - public ChannelCloseBody createChannelClose(int replyCode, AMQShortString replyText) - { - return new ChannelCloseBodyImpl(replyCode, replyText, 0, 0); - } - - public ExchangeDeclareBody createExchangeDeclare(AMQShortString name, AMQShortString type, int ticket) - { - return new ExchangeDeclareBodyImpl(ticket,name,type,false,false,false,false,false,null); - } - - public ExchangeBoundBody createExchangeBound(AMQShortString exchangeName, AMQShortString queueName, AMQShortString routingKey) - { - return new ExchangeBoundBodyImpl(exchangeName,routingKey,queueName); - } - - public QueueDeclareBody createQueueDeclare(AMQShortString name, FieldTable arguments, boolean autoDelete, boolean durable, boolean exclusive, boolean passive, int ticket) - { - return new QueueDeclareBodyImpl(ticket,name,passive,durable,exclusive,autoDelete,false,arguments); - } - - public QueueBindBody createQueueBind(AMQShortString queueName, AMQShortString exchangeName, AMQShortString routingKey, FieldTable arguments, int ticket) - { - return new QueueBindBodyImpl(ticket,queueName,exchangeName,routingKey,false,arguments); - } - - public QueueDeleteBody createQueueDelete(AMQShortString queueName, boolean ifEmpty, boolean ifUnused, int ticket) - { - return new QueueDeleteBodyImpl(ticket,queueName,ifUnused,ifEmpty,false); - } - - public ChannelFlowBody createChannelFlow(boolean active) - { - return new ChannelFlowBodyImpl(active); - } - - - // In different versions of the protocol we change the class used for message transfer - // abstract this out so the appropriate methods are created - public AMQMethodBody createRecover(boolean requeue) - { - return new BasicRecoverBodyImpl(requeue); - } - - public AMQMethodBody createConsumer(AMQShortString tag, AMQShortString queueName, FieldTable arguments, boolean noAck, boolean exclusive, boolean noLocal, int ticket) - { - return new BasicConsumeBodyImpl(ticket,queueName,tag,noLocal,noAck,exclusive,false,arguments); - } - - public AMQMethodBody createConsumerCancel(AMQShortString consumerTag) - { - return new BasicCancelBodyImpl(consumerTag, false); - } - - public AMQMethodBody createAcknowledge(long deliveryTag, boolean multiple) - { - return new BasicAckBodyImpl(deliveryTag,multiple); - } - - public AMQMethodBody createRejectBody(long deliveryTag, boolean requeue) - { - return new BasicRejectBodyImpl(deliveryTag, requeue); - } - - public AMQMethodBody createMessageQos(int prefetchCount, int prefetchSize) - { - return new BasicQosBodyImpl(prefetchSize, prefetchCount, false); - } - - - -} -- cgit v1.2.1 From 6d9261f4c3c51debd9ef62ff34aad0bb161c4f33 Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Thu, 12 Apr 2007 16:30:49 +0000 Subject: Unbreaking trunk due to erroneous commit git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@528013 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/framing/AMQBodyImpl.java | 27 ------ .../org/apache/qpid/framing/AMQMethodBodyImpl.java | 102 --------------------- .../java/org/apache/qpid/framing/MainRegistry.java | 35 ------- 3 files changed, 164 deletions(-) delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBodyImpl.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyImpl.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/MainRegistry.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBodyImpl.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBodyImpl.java deleted file mode 100644 index 6b2d1feae5..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQBodyImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * - * 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.framing; - - -public abstract class AMQBodyImpl implements AMQBody -{ - -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyImpl.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyImpl.java deleted file mode 100644 index 0a802f8857..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyImpl.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * - * 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.framing; - -import org.apache.mina.common.ByteBuffer; -import org.apache.qpid.AMQChannelException; -import org.apache.qpid.AMQConnectionException; -import org.apache.qpid.protocol.AMQConstant; - -public abstract class AMQMethodBodyImpl extends AMQBodyImpl implements AMQMethodBody -{ - public static final byte TYPE = 1; - - - public abstract byte getMajor(); - public abstract byte getMinor(); - - /** unsigned short */ - protected abstract int getBodySize(); - - /** @return unsigned short */ - public abstract int getClazz(); - - /** @return unsigned short */ - public abstract int getMethod(); - - protected abstract void writeMethodPayload(ByteBuffer buffer); - - public byte getFrameType() - { - return TYPE; - } - - public int getSize() - { - return 2 + 2 + getBodySize(); - } - - public void writePayload(ByteBuffer buffer) - { - EncodingUtils.writeUnsignedShort(buffer, getClazz()); - EncodingUtils.writeUnsignedShort(buffer, getMethod()); - writeMethodPayload(buffer); - } - - - /** - * Creates an AMQChannelException for the corresponding body type (a channel exception should include the class and - * method ids of the body it resulted from). - */ - - /** - * Convenience Method to create a channel not found exception - * - * @param channelId The channel id that is not found - * - * @return new AMQChannelException - */ - public AMQChannelException getChannelNotFoundException(int channelId) - { - return getChannelException(AMQConstant.NOT_FOUND, "Channel not found for id:" + channelId); - } - - public AMQChannelException getChannelException(AMQConstant code, String message) - { - return new AMQChannelException(code, message, getClazz(), getMethod(), getMajor(), getMinor()); - } - - public AMQChannelException getChannelException(AMQConstant code, String message, Throwable cause) - { - return new AMQChannelException(code, message, getClazz(), getMethod(), getMajor(), getMinor(), cause); - } - - public AMQConnectionException getConnectionException(AMQConstant code, String message) - { - return new AMQConnectionException(code, message, getClazz(), getMethod(), getMajor(), getMinor()); - } - - public AMQConnectionException getConnectionException(AMQConstant code, String message, Throwable cause) - { - return new AMQConnectionException(code, message, getClazz(), getMethod(), getMajor(), getMinor(), cause); - } - -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/MainRegistry.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/MainRegistry.java deleted file mode 100644 index d75589f914..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/MainRegistry.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * - * 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.framing; - -public class MainRegistry -{ - - public static VersionSpecificRegistry getVersionSpecificRegistry(byte versionMajor, byte versionMinor) - { - return null; //To change body of created methods use File | Settings | File Templates. - } - - public static VersionSpecificRegistry getVersionSpecificRegistry(ProtocolVersion pv) - { - return null; //To change body of created methods use File | Settings | File Templates. - } -} -- cgit v1.2.1 From ffe5e29f94b376c6f5900b2f9577c8bbaef7407b Mon Sep 17 00:00:00 2001 From: Robert Greig Date: Thu, 19 Apr 2007 16:24:30 +0000 Subject: Merged revisions 1-447993,447995-448007,448009-448141,448143-448157,448161-448194,448196-448210,448212-448218,448220-448223,448225-448233,448235,448237-448241,448243-448596,448598-448623,448625-448850,448852-448880,448882-448982,448984-449635,449637-449639,449641-449642,449644-449645,449647-449674,449676-449719,449721-449749,449751-449762,449764-449933,449935-449941,449943-450383,450385,450387-450400,450402-450433,450435-450503,450505-450555,450557-450860,450862-451024,451026-451149,451151-451316,451318-451931,451933-452139,452141-452162,452164-452320,452322,452324-452325,452327-452333,452335-452429,452431-452528,452530-452545,452547-453192,453194-453195,453197-453536,453538,453540-453656,453658-454676,454678-454735,454737,454739-454781,454783-462728,462730-462819,462821-462833,462835-462839,462841-463071,463073-463178,463180-463308,463310-463362,463364-463375,463377-463396,463398-463402,463404-463409,463411-463661,463663-463670,463672-463673,463675-464493,464495-464502,464504-464576,464578-464613,464615-464628,464630,464632-464866,464868-464899,464901-464942,464944-464949,464951-465004,465006-465016,465018-465053,465055-465165,465167-465321,465323-465406,465408-465427,465429-465431,465433-465548,465550-466044,466047-466075,466077,466079-466081,466083-466099,466101-466112,466114-466126,466128-466240,466242-466971,466973-466978,466980-467309,467311-467312,467316-467328,467330-467485,467487-467588,467590-467604,467606-467699,467701-467706,467708-467749,467751-468069,468071-468537,468539-469241,469244-469246,469248-469318,469320-469421,469423,469425-469429,469431-469435,469437-469462,469464-469469,469472-469477,469479-469490,469492-469503,469505-469529,469531-469598,469600-469624,469626-469737,469739-469752,469754-469806,469808-469928,469930-469953,469955-470011,470013-470109,470111-470335,470338-470339,470341-470379,470381,470383-470399,470401-470446,470448-470741,470743-470758,470760-470809,470811-470817,470819-470993,470995-471001,471003-471788,471790-471792,471794-472028,472030-472032,472034-472036,472038,472040,472043,472045-472059,472061,472063,472065-472066,472068,472070-472072,472074-472080,472082,472084-472092,472094-472107,472109-472123,472125-472158,472160-472165,472167-472172,472174-472457,472459-472460,472462-472464,472466-472470,472472-472483,472486-472491,472493-472494,472496-472497,472499,472501-472503,472505-472512,472514-472544,472546-472556,472558-472560,472562-472572,472574-472587,472589-472591,472593-472605,472607,472609-472731,472733-472786,472788-472843,472845-472849,472851-472859,472861-472878,472880-472903,472905,472907-472988,472990-472991,472993-473071,473073-473086,473088-473090,473093,473095-473096,473098-473106,473108-473110,473112-473185,473187-473260,473262,473268-473270,473275-473279,473281,473284-473287,473289-473295,473297-473306,473308-473330,473332-473335,473337,473339-473344,473346-473351,473353-473355,473357-473358,473361-473471,473473-473497,473499-473535,473537-473567,473569-473888,473890-474451,474454-474492,474494-474563,474565-474843,474845-474865,474867-474932,474934-475035,475037-475144,475146-475180,475182-475265,475267-475285,475287,475289-475293,475295-475296,475298-475302,475304-475631,475633-475649,475651-475748,475750-475752,475754-476107,476109-476302,476304-476413,476415-476430,476432-476700,476702-476868,476870-477147,477149-477213,477215-477263,477265-477340,477342-477635,477637-477789,477791-477825,477827-477841,477843,477846-477852,477854,477856,477858-477865,477867-477894,477896-478022,478024-478182,478184-478211,478213-478233,478235-478236,478238-478241,478243-478252,478254-478259,478261-478263,478265,478267-478269,478271-478286,478288-478342,478344-478379,478381-478412,478414-478443,478445-478636,478639-478658,478660-478821,478823-478853,478855-478922,478924-478962,478965-478974,478976-479029,479031-479049,479051-479210,479212-479214,479216-479407,479409-479415,479417-479425,479427-479559,479561-479639,479641-479676,479678-479685,479687-480030,480033-480086,480091-480093,480095-480118,480120-480139,480141,480143-480148,480150-480156,480158-480163,480165-480177,480179-480189,480191-480193,480195-480198,480200-480220,480222-480282,480284-480292,480294-480308,480310-480317,480320-480422,480424,480426-480581,480583-480656,480658-480692,480695-480702,480704,480706-480710,480712-480910,480913-480933,480935-480945,480947-480972,480974-480993,480995-481034,481036-481158,481161-481174,481176-481220,481222-481234,481236-481260,481263-481264,481266-481296,481298-481304,481306-481311,481313-481332,481334,481336-481380,481382-481441,481443-482144,482146-482180,482182-482193,482195-482232,482234-482236,482239,482241-482242,482244-482247,482250-482251,482253,482256-482261,482264-482288,482290-482364,482366,482368,482370-482554,482556,482558-482569,482572-482636,482638,482640-482696,482698-482722,482724-482732,482734-482771,482774-482957,482959-483045,483047-483105,483108,483110-483115,483117,483119-483127,483130-483134,483136-483148,483150-483158,483160-483164,483166-483178,483180-483391,483393-483400,483402-483403,483405-483418,483420-483421,483425-483436,483438-483470,483472-483502,483504-483558,483560-483599,483601-483637,483639-483644,483646-483659,483661-483670,483672-483878,483880-483910,483912-483915,483917-483940,483942,483944-483968,483970-483972,483974-483976,483978,483980-484612,484614-484657,484659-484693,484695-484718,484720-484842,484844-484847,484849-484986,484988-485019,485021-485489,485491-485544,485546-485591,485593,485595-485697,485699-485729,485731-485734,485736-485779,485781-485787,485789-485851,485853,485855-486007,486009,486011-486020,486022-486083,486085-486097,486099-486117,486120-486131,486133-486148,486150-486161,486163-486164,486166-486197,486199-486205,486208-486247,486249-486253,486256-486427,486429-486431,486433-486554,486556-486573,486575-486593,486595,486597-486609,486611-486619,486622,486625,486627-486641,486643-486645,486649-486687,486689-486721,486723-486730,486732-486746,486748-486759,486761,486763-486777,486779-486782,486784-486788,486790,486792,486794-486796,486798-487175,487178,487180-487213,487215,487217-487267,487269-487284,487286-487298,487300-487358,487360-487367,487369-487382,487384-487434,487436-487480,487482-487547,487549-487561,487563-487565,487567-487578,487580-487615,487617-487622,487624,487626,487628,487630-487635,487637-487703,487705-487777,487780-487781,487783-487800,487802-487803,487805-487820,487822-487848,487850-487902,487904-488103,488105-488133,488135-488158,488160-488163,488165-488187,488189-488216,488218-488248,488250-488278,488280,488282-488303,488305-488313,488315-488342,488344-488351,488353-488376,488378-488449,488451-488593,488595,488597-488623,488625-488700,488702-488704,488706-488710,488714,488716-488725,488727-488744,488746-488770,488772-488798,488800,488802-488807,488809,488811-488829,488831-488843,488845-488851,488853-489069,489071-489077,489079-489081,489084-489102,489104-489105,489107-489109,489111-489112,489114-489139,489141-489178,489181-489203,489205-489211,489213,489216-489329,489332-489402,489404-489417,489419-489421,489423-489643,489645-489690,489692-489703,489705-489714,489716-489747,489749-489753,489755-489803,489805-489904,489906-490372,490374-490504,490506-490604,490606-490707,490710-490733,490735-490871,490873-490984,490986-491028,491030,491032-491071,491073-491119,491121-491576,491578-491672,491674-491800,491802-491838,491840-491878,491880-492183,492185-492279,492281-492317,492319-492513,492515-492584,492586-492587,492589-492601,492603-492635,492637-492640,492642-492717,492719-492723,492725-492729,492731-492755,492757-492901,492903-492955,492957-492962,492964-492997,492999-493002,493004-493041,493043-493059,493062-493063,493065-493086,493088-493125,493127-493139,493141-493150,493152-493871,493873-494017,494019-494030,494032-494041,494043-494091,494093-494120,494122-494354,494356-494436,494438-494539,494541-494552,494554-494586,494588-494649,494651,494653-494654,494656-494657,494659-494764,494766-494768,494770-494796,494798-494799,494802,494804-494860,494862-494903,494905-494906,494908-495019,495021-495160,495162-495168,495171-495188,495190-495229,495231-495254,495256-495303,495305-495313,495315-495336,495338-495372,495374-495379,495381-495454,495457-495459,495462-495516,495518-495524,495526-495531,495533-495548,495551-495553,495555,495557-495558,495560,495562-495573,495575-495583,495585-495594,495596-495628,495630-495638,495640-495651,495653-495660,495662-495753,495755-496259,496261-496262,496264-496269,496271-496275,496277-496301,496303-496316,496318-496383,496385-496413,496415-496495,496497-496625,496627-496636,496638-496640,496642-496647,496650-496657,496659-496660,496663-496664,496666-496677,496679-496681,496683-496730,496732-496750,496752,496754-496784,496786-496832,496834-496840,496842-496990,496992-496995,496997-497340,497343-497351,497353-497403,497405-497424,497426-497438,497440-497481,497483-497497,497499-497765,497767-497769,497771-497775,497777-497778,497780,497782-497783,497785,497787-497812,497814-497871,497873-497877,497879-498573,498575-498588,498590,498592,498594-498636,498638-498669,498671-498686,498688-498689,498691-498719,498721-498964,498966-498969,498971-498973,498975-498982,498985-499035,499037-499040,499042,499044-499048,499050-499082,499084-499086,499088-499164,499167-499169,499171-499355,499357-499370,499372-499373,499375-499391,499393,499395-499425,499428,499430-499445,499447-499455,499457-499460,499462-499465,499467,499469-499489,499491-499492,499494-499531,499533-499562,499566-499627,499629-499715,499717-499732,499734-499755,499758-499763,499765-499780,499782-499795,499797-499802,499804-499844,499846,499848-499850,499852-499863,499865-499873,499875-499974,499976-499978,499980-500263,500265-500283,500285-500309,500311-501000,501002,501012-501057,501059-501095,501097-501390,501392-501410,501413-501447,501449-501454,501456,501458-501464,501466-501471,501473-501803,501805-501913,501915-501916,501918-501919,501921-501944,501946-502171,502173-502177,502181,502183-502247,502250-502252,502254-502260,502262-502267,502270,502272,502274-502575,502577-502609,502611-502619,502621-502626,502628-502654,502656-503592,503594-503603,503605-503608,503610-503636,503638-503645,503647-503705,503707-503789,503791-504024,504026-504111,504113-504506,504508-504735,504737-504863,504865-504867,504869-504914,504916-505241,505243-505254,505257-505267,505269-505354,505356-505891,505893-505971,505973-506400,506402-506404,506407-506438,506440-506516,506518-506541,506543-506966,506968-506971,506973-507095,507097-507108,507111-507454,507456,507459-507471,507473-507556,507558,507560-507581,507585-507594,507597,507599-507608,507610-507728,507730-507893,507895-507937,507940-508234,508236-508350,508352-508365,508367-508380,508383,508386-508415,508417-508648,508650-508941,508943-509146,509148-509171,509173-509175,509179-509201,509203-509207,509209-509215,509217-509222,509224-509477,509480-509627,509629-509634,509636-509641,509643-509736,509738-509931,509933-510059,510061-510075,510077-510158,510161-510896,510898-510938,510940-511388,511390-511922,511924-512287,512289-512698,512702-512813,512815-512817,512819-513359,513361-513370,513372-514702,514704-514886,514888-514902,514904-515126,515129-515141,515143-515516,515518-515534,515536-515538,515540-515648,515650-515651,515653-516070,516072-516411,516413-516448,516450,516452-517637,517639-517647,517649-517659,517661-517663,517665-517677,517679-517682,517684-517744,517746-518085,518087-518175,518177-518558,518560-518568,518571-518666,518668,518670-518699,518701-518987,518990-518992,518994-519908,519910-519932,519934-520414,520416-520842,520844-520937,520939-521362,521364-521792,521794-522462,522464-522527,522529-522534,522536-522566,522568-522993,522995-523244,523246-525530,525532,525534,525537-526149,526151-526682,526686-526713,526715-530399 via svnmerge from https://svn.apache.org/repos/asf/incubator/qpid/branches/M2 ........ r521682 | bhupendrab | 2007-03-23 11:50:55 +0000 (Fri, 23 Mar 2007) | 2 lines QPID-418 (merged from trunk) svn merge -r521336:521345 https://svn.apache.org/repos/asf/incubator/qpid/trunk/qpid/java . ........ r521705 | rgreig | 2007-03-23 12:44:14 +0000 (Fri, 23 Mar 2007) | 1 line Updates to performance tests. ........ r521710 | ritchiem | 2007-03-23 12:59:18 +0000 (Fri, 23 Mar 2007) | 2 lines QPID-419 Access Control QPID-423 Authentication per virtualhost Improved error handling when hostconfig is not specifed. Was NPE-ing ........ r521715 | ritchiem | 2007-03-23 13:10:33 +0000 (Fri, 23 Mar 2007) | 2 lines QPID-423 Authentication per virtualhost Improved error handling when hostconfig is not specifed. Was NPE-ing ........ r521782 | bhupendrab | 2007-03-23 16:02:51 +0000 (Fri, 23 Mar 2007) | 1 line QPID-420 (merged from trunk) And r518998:518999 and r520846:520850 ........ r522959 | ritchiem | 2007-03-27 16:39:51 +0100 (Tue, 27 Mar 2007) | 2 lines Updated assembly/bin.xml to include transient_config.xml persistent_config.xml ........ r522961 | ritchiem | 2007-03-27 16:42:40 +0100 (Tue, 27 Mar 2007) | 1 line forgot to rename files after they had been copied ........ r522967 | ritchiem | 2007-03-27 16:56:03 +0100 (Tue, 27 Mar 2007) | 1 line correctly renamed transient and persistent config files ........ r522977 | ritchiem | 2007-03-27 17:06:15 +0100 (Tue, 27 Mar 2007) | 1 line updated config files ........ r522981 | ritchiem | 2007-03-27 17:10:45 +0100 (Tue, 27 Mar 2007) | 1 line Added echo of progress and reduced timeout ........ r522989 | ritchiem | 2007-03-27 17:33:04 +0100 (Tue, 27 Mar 2007) | 1 line fixed error where script wouldn't pickup running pids ........ r522990 | ritchiem | 2007-03-27 17:36:34 +0100 (Tue, 27 Mar 2007) | 1 line Added additional logging and comments ........ r522991 | ritchiem | 2007-03-27 17:37:17 +0100 (Tue, 27 Mar 2007) | 1 line Added additional comments ........ r523747 | rajith | 2007-03-29 16:32:56 +0100 (Thu, 29 Mar 2007) | 1 line Fix for setting the message id ........ r524050 | rgreig | 2007-03-30 12:51:09 +0100 (Fri, 30 Mar 2007) | 1 line Removed excess logging to optimize performance. ........ r524739 | ritchiem | 2007-04-02 08:29:06 +0100 (Mon, 02 Apr 2007) | 1 line Added BDB Test scripts and updated pom to contain same tests as were used in perftesting ........ r524740 | ritchiem | 2007-04-02 08:47:29 +0100 (Mon, 02 Apr 2007) | 1 line Fixed error with passwordfile parameter ........ r524743 | ritchiem | 2007-04-02 09:07:55 +0100 (Mon, 02 Apr 2007) | 1 line Added CTQ tests ........ r524763 | ritchiem | 2007-04-02 11:50:06 +0100 (Mon, 02 Apr 2007) | 1 line Added verify password method to PrincipalDatabase ........ r524765 | ritchiem | 2007-04-02 11:55:12 +0100 (Mon, 02 Apr 2007) | 1 line Moved broker details to a separate variable. ........ r524767 | ritchiem | 2007-04-02 12:17:54 +0100 (Mon, 02 Apr 2007) | 1 line ignored idea files ........ r525487 | ritchiem | 2007-04-04 11:42:59 +0100 (Wed, 04 Apr 2007) | 3 lines Added default timeout to AMQConnection.close(); ........ r525553 | ritchiem | 2007-04-04 17:34:35 +0100 (Wed, 04 Apr 2007) | 1 line Updated case of properties ........ r525766 | ritchiem | 2007-04-05 09:51:55 +0100 (Thu, 05 Apr 2007) | 1 line QPID-308 Added test case to demonstrate heap exhaustion of broker. Can't be run InVM as it kills the broker. ........ r525777 | ritchiem | 2007-04-05 10:29:22 +0100 (Thu, 05 Apr 2007) | 20 lines QPID-414 : Addition of CRAM-MD5-HASHED authentication. Same as CRAM-MD5 but the client uses the hash of the password rather than the original password. This allows the broker to store the hash not the original password. Added initial tool for generation passwords. Broker: Renamed MD5PasswordFilePrincipalDatabase.java to Base64MD5PasswordFilePrincipalDatabase.java as that more accurately represents the file contents. PlainPasswordVhostFilePrincipalDatabase.java - import tidy up PrincipalDatabaseAuthenticationManager.java - Changed to add our SASL providers at the start of the SASL list. CRAMMD5Hashed* - New SASL mechanism that delegates to CRAM-MD5 but understands that the password to use is the hash of the users password. JCAProvider - Removed the addProvider() line as this is done after the construction in PrincipalDatabaseAuthenticationManager. PlainSaslServerFactory - White Space Passwd.java - New util stub for managing passwords ala htpasswd. Client Added CRAM-MD5-HASHED to CallbackHandlerRegistry Added ClientFactory for CRAMMD5Hashed that returns the first CRAM-MD5 SaslClient. DynamicSaslRegistrar.java - Tidied imports added new JCAProviders at the start of the Sasl lists. DynamicSaslRegistrar.properties - Added CRAM-MD5-HASHED handler. JCAProvider.java - as with broker stopped JCAProvider.java adding itself as the DynamicSaslRegistrar.java does this on the client. UsernameHashedPasswordCallbackHandler.java - New callback handler that is used by CRAM-MD5-HASHED. It hashes the client's password and uses that in the CRAM-MD5 algorithm. ........ r525785 | ritchiem | 2007-04-05 10:48:43 +0100 (Thu, 05 Apr 2007) | 1 line Old ant folder ........ r525786 | ritchiem | 2007-04-05 10:57:33 +0100 (Thu, 05 Apr 2007) | 1 line QPID-440 - added comments in the code relating to this bug. ........ r525787 | ritchiem | 2007-04-05 10:58:20 +0100 (Thu, 05 Apr 2007) | 2 lines QPID-308 removed closeConnection() that calls close(-1) and may result in a client hang. better to call closeConnection(long timeout) so forced this my removing closeConnection(); ........ r525788 | ritchiem | 2007-04-05 11:00:56 +0100 (Thu, 05 Apr 2007) | 1 line QPID-414 update to config.xml to give usage example. ........ r525804 | ritchiem | 2007-04-05 13:19:31 +0100 (Thu, 05 Apr 2007) | 1 line QPID-308 Updated HeapExhaustion to be able to be run from command line ........ r525817 | ritchiem | 2007-04-05 14:14:50 +0100 (Thu, 05 Apr 2007) | 1 line Update to qpid stop scripts to properly check for existing broker instances and promptly stop them. ........ r525829 | ritchiem | 2007-04-05 14:50:56 +0100 (Thu, 05 Apr 2007) | 1 line Updated scripts to work correctly under solaris and bash 2.0 ........ r525862 | rgodfrey | 2007-04-05 17:37:40 +0100 (Thu, 05 Apr 2007) | 1 line QPID-443 : Fix to transactionality of message publishing ........ r525867 | ritchiem | 2007-04-05 17:47:59 +0100 (Thu, 05 Apr 2007) | 2 lines QPID-416 Provided simple update to Access Control via FileAccessManager to allow access rights for a virtualhost to be stored in a separate file. Updated PrincipalDatabaseAccessManager to use the default AccessManager if the specified PrincipalDatabase is not an AccessManager. ........ r526091 | ritchiem | 2007-04-06 09:21:01 +0100 (Fri, 06 Apr 2007) | 5 lines QPID-416 Update to Access control to allow simply read/write permissions per Virtual host. access - updated file to have examples of access control. AccessManager - Deprecated old isAuthorised method Implemented new isAuthorized method on all AccessManagers ........ r526113 | ritchiem | 2007-04-06 11:28:43 +0100 (Fri, 06 Apr 2007) | 1 line Updated case of properties to be true cammelCase and updated tests to run for a duration of 10 minutes rather than set message count. To provide better results for graphing. ........ r526117 | ritchiem | 2007-04-06 11:42:11 +0100 (Fri, 06 Apr 2007) | 9 lines QPID-416 Update to Access control to allow simply read/write permissions per Virtual host. access - updated file to have examples of access control. Changed AMQProtocolSession to record an authorized Principal not just a String. - Required Added AccessRights files needed for VirtualHostAccess control. Updated ConnectionOpenMethodHandler to allow Principals with any access to connect not just read. UsernamePrincipal - Added a toString ........ r526118 | rgodfrey | 2007-04-06 11:55:17 +0100 (Fri, 06 Apr 2007) | 1 line ........ r526122 | ritchiem | 2007-04-06 12:26:06 +0100 (Fri, 06 Apr 2007) | 1 line removed pauses between batches ........ r526154 | rgodfrey | 2007-04-06 14:24:46 +0100 (Fri, 06 Apr 2007) | 1 line QPID-443 : Fix to transactionality of message publishing ........ r526157 | bhupendrab | 2007-04-06 14:32:56 +0100 (Fri, 06 Apr 2007) | 1 line QPID-444 : Enabling the Qpid to use SASL. jmxmp can be plugged into for SASL. Can be configured to use security. ........ r526158 | ritchiem | 2007-04-06 14:34:52 +0100 (Fri, 06 Apr 2007) | 1 line Duplicate of BDB-Qpid.sh ........ r526159 | bhupendrab | 2007-04-06 14:37:47 +0100 (Fri, 06 Apr 2007) | 1 line QPID-444 : adding jmxport, which is used when out of the box JMXAgent is not used ........ r526166 | ritchiem | 2007-04-06 14:51:41 +0100 (Fri, 06 Apr 2007) | 1 line QPID-414 - Initial script to run the passwd gen. ........ r526187 | bhupendrab | 2007-04-06 15:53:36 +0100 (Fri, 06 Apr 2007) | 2 lines QPID-444 : Enabling the SASL support. jmxmp can be plugged into for SASL. ........ r526194 | rgreig | 2007-04-06 16:21:19 +0100 (Fri, 06 Apr 2007) | 1 line Added some ramping up performance tests. ........ r526195 | marnie | 2007-04-06 16:21:33 +0100 (Fri, 06 Apr 2007) | 1 line QPID-381 Amended session constructor to be non-transactional and use client ack mode. ........ r526198 | rgreig | 2007-04-06 16:26:02 +0100 (Fri, 06 Apr 2007) | 1 line Fixed message sizes. ........ r526199 | rgreig | 2007-04-06 16:29:06 +0100 (Fri, 06 Apr 2007) | 1 line Fixed commit batch size. ........ r526666 | ritchiem | 2007-04-09 08:47:14 +0100 (Mon, 09 Apr 2007) | 1 line Updated so the FileAppender includes time stamps by default.. ConversionPattern made the same as STDOUT and RollingFileAppender ........ r526691 | ritchiem | 2007-04-09 10:39:47 +0100 (Mon, 09 Apr 2007) | 1 line Added $@ to allow pass through of command line args to each sub process ........ r526692 | bhupendrab | 2007-04-09 10:45:06 +0100 (Mon, 09 Apr 2007) | 4 lines QPID-444 : added log statements and some config parameters. Removed the autoDelete parameter from createNewQueue method used from Management Console. ........ r526694 | bhupendrab | 2007-04-09 10:51:46 +0100 (Mon, 09 Apr 2007) | 1 line ........ r526709 | bhupendrab | 2007-04-09 12:02:08 +0100 (Mon, 09 Apr 2007) | 2 lines QPID-444 : updated the management console dependency configuration for sasl support ........ r526776 | rgreig | 2007-04-09 16:26:04 +0100 (Mon, 09 Apr 2007) | 1 line Stopped throwing away exception causes. ........ r526803 | rgreig | 2007-04-09 17:09:24 +0100 (Mon, 09 Apr 2007) | 1 line Got rid of some uses of System.out instead of log4j logging. ........ r526807 | rgreig | 2007-04-09 17:12:49 +0100 (Mon, 09 Apr 2007) | 1 line Got rid of some uses of System.out instead of log4j logging. ........ r527049 | ritchiem | 2007-04-10 08:58:26 +0100 (Tue, 10 Apr 2007) | 1 line Moved bdb tests to bdbstore package ........ r527050 | ritchiem | 2007-04-10 09:00:42 +0100 (Tue, 10 Apr 2007) | 1 line QueueDeclareHandler.java - Added more detail to error messages. Such as returning the queue name that was attempted to be declared but failed. ........ r527053 | ritchiem | 2007-04-10 09:03:15 +0100 (Tue, 10 Apr 2007) | 1 line Added a test to check that Persistent Queues do actually persist. ........ r527182 | ritchiem | 2007-04-10 17:29:47 +0100 (Tue, 10 Apr 2007) | 1 line QPID-446 Initial MBean framework. ........ r527487 | ritchiem | 2007-04-11 14:31:18 +0100 (Wed, 11 Apr 2007) | 5 lines QPID-446 AMQUserManagementMBean Initial implementation of user management in authentication file. UserManagement - Added annotations for MBeanOperations PrincipalDatabase - Added new methods to update,create,delete Principal. - Implemented method on all PrincipalDatabase implementations, most return false to say not complete except Base64MD5PasswordFilePrincipalDatabase - which now stores in memory the password file and flushes any changes to disk. ........ r527493 | ritchiem | 2007-04-11 14:50:40 +0100 (Wed, 11 Apr 2007) | 1 line QPID-446 Missed the commit of JMXManagedObjectRegistry change on verifyPassword char[] to String ........ r527499 | bhupendrab | 2007-04-11 15:16:02 +0100 (Wed, 11 Apr 2007) | 1 line QPID-444 : added CRAM-MD5-HASHED mechanism for sasl ........ r527509 | bhupendrab | 2007-04-11 15:47:22 +0100 (Wed, 11 Apr 2007) | 1 line ........ r527518 | ritchiem | 2007-04-11 16:21:37 +0100 (Wed, 11 Apr 2007) | 14 lines QPID-446 JMXManagedObjectRegistry - Split instantiation from starting up. To all the setting of the Access file when loaded later in the startup sequence. ManagedObjectRegistry - Added Start method MBeanInvocationHandlerImpl - Updated to allow the setting of the access properties object from the AMQUserManagementMBean NoopManagedObjectRegistry - implemented no-op start ConfigurationFileApplicationRegistry - Adjusted to split creation of ManagedObjectRegistry from starting server to allow the setting of access rights. AMQUserManagementMBean - Implemented reading of access rights file. Base64MD5PasswordFilePrincipalDatabase - added comment for future Management. PrincipalDatabaseManager - added initialiseManagement method ConfigurationFilePrincipalDatabaseManager - implemented general Management initialisation. PropertiesPrincipalDatabaseManager - no-op implementation ........ r527537 | ritchiem | 2007-04-11 16:47:30 +0100 (Wed, 11 Apr 2007) | 2 lines QPID-446 Update to contain jmx config settings. ........ r527556 | bhupendrab | 2007-04-11 17:07:58 +0100 (Wed, 11 Apr 2007) | 1 line synchronized with hash mechanism used in Broker ........ r527557 | ritchiem | 2007-04-11 17:08:54 +0100 (Wed, 11 Apr 2007) | 1 line Fixed Bug in convertPassword where data wasn't correctly updated PropertiesPrincipalDatabase, ........ r527558 | ritchiem | 2007-04-11 17:09:54 +0100 (Wed, 11 Apr 2007) | 1 line QpiQPID-446 Update to ensure qpid.password file is correctly written in savePasswordFile ........ r527803 | ritchiem | 2007-04-12 08:16:54 +0100 (Thu, 12 Apr 2007) | 5 lines QPID-446 Update to write accessRights file and correctly write Base64 MD5 Hashed password to password file. MBeanInvocationHandlerImpl - made statics ADMIN,READONLY,READWRITE public so they can be used in writing the access file. AMQUserManagementMBean - Update to write the access File. PrincipalDatabase - create getUser(username) to retrieve a Principal from the database this is then implemented in all PDs. Used to check for existence of a user. ........ r527843 | ritchiem | 2007-04-12 09:52:19 +0100 (Thu, 12 Apr 2007) | 10 lines QPID-446 Update to send userList to JMX Management console. Currently niave implementation just sending ALL users in one go. If a LDAPPrincipalDatabase was created this could be quite a lot of data a) to send but b) to create in broker Heap. PrincipalDatabase - javadoc'd and getUsers method, -changed verifyPassword method to take String for username rather than Principal only the Managment Console uses this method and it the MC should be changed to use the Broker SASL modules directly rather than having very similar ones of its own. - Removed AccountNotFound exception from createPrincipal as it made no sence No-op implementation in PlainPasswordFilePrincipalDatabase and PropertiesPrincipalDatabase Base64MD5PasswordFilePrincipalDatabase changed local User class to implement Principal so current Map can be returned via getUsers - Added locking to ensure integrity of files in the face of multiple edits. ........ r527848 | ritchiem | 2007-04-12 10:11:19 +0100 (Thu, 12 Apr 2007) | 1 line QPID-446 Removed hashing of presented password in Base64MD5PasswordFilePrincipalDatabase. ........ r527876 | rgodfrey | 2007-04-12 11:31:51 +0100 (Thu, 12 Apr 2007) | 3 lines QPID-451 Throw InvalidDestinationException on attempt to publish to a Queue which does not exist Changed QueueSenderAdapter to check if the routing key is bound to a queue on the given exchange. The checking can be turned off by setting the system property org.apache.qpid.client.verifyQueueBindingBeforePublish to anything but true ........ r527941 | bhupendrab | 2007-04-12 14:49:10 +0100 (Thu, 12 Apr 2007) | 1 line not needed for management console ........ r527959 | bhupendrab | 2007-04-12 15:40:36 +0100 (Thu, 12 Apr 2007) | 1 line refining the mbean operations ........ r527972 | ritchiem | 2007-04-12 16:11:16 +0100 (Thu, 12 Apr 2007) | 3 lines QPID-446 Updated sample configs to contain jmx security options. ........ r528003 | marnie | 2007-04-12 17:15:48 +0100 (Thu, 12 Apr 2007) | 1 line QPID-352 Changes ........ r528005 | marnie | 2007-04-12 17:16:34 +0100 (Thu, 12 Apr 2007) | 1 line QPID-352 Changes ........ r528424 | rgreig | 2007-04-13 11:17:12 +0100 (Fri, 13 Apr 2007) | 1 line Created new ping client that sends messages only. Usefull for examaning known queue states in mgmnt console. ........ r529233 | bhupendrab | 2007-04-16 14:25:58 +0100 (Mon, 16 Apr 2007) | 1 line added parameter for SASL ........ r529246 | bhupendrab | 2007-04-16 14:48:31 +0100 (Mon, 16 Apr 2007) | 1 line removed default username as guest. Added hashing for new user password field. ........ r529297 | rgodfrey | 2007-04-16 16:53:45 +0100 (Mon, 16 Apr 2007) | 1 line QPID-453 : AMQShortString should implement Comparable ........ r529635 | bhupendrab | 2007-04-17 16:07:06 +0100 (Tue, 17 Apr 2007) | 1 line QPID-422 : Combined all user configured notifications on one view. ........ r529659 | ritchiem | 2007-04-17 17:08:00 +0100 (Tue, 17 Apr 2007) | 7 lines QPID-454 Message 'taken' notion is per message. But should be per message per queue AMQChannel - pass queue in on all take/release/getSubscriptionDelievered calls BasicRejectMethodHandler - pass queue in on getSubscriptionDelievered calls AMQMessage - Changes to require AMQQueue on all take/release/getSubscriptionDelievered calls ConcurrentSelectorDeliveryManager - pass queue in on take/release/getSubscriptionDelievered calls SubscriptionImpl - - pass queue in on release calls ........ r529666 | ritchiem | 2007-04-17 17:19:59 +0100 (Tue, 17 Apr 2007) | 11 lines QPID-455 Prefetched messages can cause problems with client tools. AMQSession - suspend channel at startup until start() and recieve/setMessageListener are called. BasicMessageConsumer - mainly style sheet changes MessageListenerMultiConsumerTest - removed one test case as we cannot ensure round-robin effect at start up .. added test case for only c2 consuming when c1 does nothing. MessageListenerTest - added new test that can demonstrate a further bug of message 'loss' when a receive is called only once before a message listener is set. Prefetched message end up on _SynchronousQueue regression of QPID-293 as of r501004. MessageRequeueTest - Was missing a conn.start() DurableSubscriptionTest - Removed blocking receives() so we don't block on failure CommitRollbackTest - Text message was wrong on testGetThenDisconnect tests so adjusted ........ r529669 | bhupendrab | 2007-04-17 17:43:53 +0100 (Tue, 17 Apr 2007) | 1 line QPID-417 ........ r530034 | bhupendrab | 2007-04-18 15:32:02 +0100 (Wed, 18 Apr 2007) | 2 lines AMQUserManagementMBean.java - calling relaod within viewUsers method. Creating user list on management console instead of typing the user name. ........ r530037 | ritchiem | 2007-04-18 15:37:30 +0100 (Wed, 18 Apr 2007) | 1 line QPID-454 Message 'taken' notion is per message. REVERTED as it just wasn't right.. needs to be refactored. ........ r530041 | ritchiem | 2007-04-18 15:40:47 +0100 (Wed, 18 Apr 2007) | 1 line QPID-457 Fixed rollback inTran problem with test case ........ r530042 | ritchiem | 2007-04-18 15:42:16 +0100 (Wed, 18 Apr 2007) | 1 line QPID-457 Fixed rollback inTran problem with test case Missed the actual file fix. ........ r530043 | ritchiem | 2007-04-18 15:46:36 +0100 (Wed, 18 Apr 2007) | 1 line QPID-458 Fix to make the CSDM check if a message is taken when deliverying to browser. Removing the message from the queue and continuing if that is the caee. ........ r530044 | ritchiem | 2007-04-18 15:54:36 +0100 (Wed, 18 Apr 2007) | 1 line Removed e.printstacktrace that sneaked in with the other code style changes. ........ r530047 | ritchiem | 2007-04-18 16:09:28 +0100 (Wed, 18 Apr 2007) | 1 line Fix for intermittent CRT expected <1> but was <2> errors ........ r530048 | ritchiem | 2007-04-18 16:10:24 +0100 (Wed, 18 Apr 2007) | 3 lines ResetMessageListenerTest was using the wrong queue for running tests. This was causing problems during testing. Changed queue to use ResetMessageListenerTest queue ........ r530049 | ritchiem | 2007-04-18 16:11:22 +0100 (Wed, 18 Apr 2007) | 2 lines QPID-455 Prefetched messages can cause problems with client tools. Removed the changes as this was causing problems. Guarded with a check for now but solution is till not correct. ........ r530052 | ritchiem | 2007-04-18 16:12:45 +0100 (Wed, 18 Apr 2007) | 1 line QPID-455 - Guarded test with a check until a full solution is found ........ git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@530474 13f79535-47bb-0310-9956-ffa450edef68 --- .../main/java/org/apache/qpid/AMQException.java | 58 ++++- .../qpid/configuration/PropertyException.java | 10 +- .../apache/qpid/framing/AMQDataBlockDecoder.java | 8 +- .../qpid/framing/AMQFrameDecodingException.java | 20 +- .../org/apache/qpid/framing/AMQShortString.java | 2 +- .../qpid/framing/BasicContentHeaderProperties.java | 4 +- .../framing/ContentHeaderPropertiesFactory.java | 2 +- .../org/apache/qpid/framing/EncodingUtils.java | 261 ++++++++------------- .../qpid/framing/VersionSpecificRegistry.java | 24 +- .../src/main/java/org/apache/qpid/pool/Event.java | 23 ++ .../java/org/apache/qpid/pool/PoolingFilter.java | 107 ++++----- .../java/org/apache/qpid/url/AMQBindingURL.java | 53 ++--- .../main/java/org/apache/qpid/url/URLHelper.java | 44 ++-- 13 files changed, 301 insertions(+), 315 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java index 0222fd9b4e..3e93243a1d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java @@ -23,11 +23,41 @@ package org.apache.qpid; import org.apache.log4j.Logger; import org.apache.qpid.protocol.AMQConstant; -/** Generic AMQ exception. */ +/** + * AMQException forms the root exception of all exceptions relating to the AMQ protocol. It provides space to associate + * an AMQ error code with the exception, which is a numberic value, with a meaning defined by the protocol. + * + *

      + *
      CRC Card
      Responsibilities Collaborations + *
      Represents an exception condition associated with an AMQ protocol error code. + *
      + * + * @todo This exception class is also used as a generic exception throughout Qpid code. This usage may not be strictly + * correct if this is to signify a protocol exception. Should review. + */ public class AMQException extends Exception { + /** Holds the AMQ error code constant associated with this exception. */ private AMQConstant _errorCode; + /** + * Creates an exception with an optional error code, optional message and optional underlying cause. + * + * @param errorCode The error code. May be null if not to be set. + * @param msg The exception message. May be null if not to be set. + * @param t The underlying cause of the exception. May be null if not to be set. + */ + public AMQException(AMQConstant errorCode, String msg, Throwable t) + { + super(((msg == null) ? "" : msg) + ((errorCode == null) ? "" : (" [error code " + errorCode + "]")), t); + _errorCode = errorCode; + } + + /** + * @param message + * + * @deprecated Use {@link #AMQException(org.apache.qpid.protocol.AMQConstant, String, Throwable)} instead. + */ public AMQException(String message) { super(message); @@ -35,6 +65,12 @@ public class AMQException extends Exception _errorCode = AMQConstant.getConstant(-1); } + /** + * @param msg + * @param t + * + * @deprecated Use {@link #AMQException(org.apache.qpid.protocol.AMQConstant, String, Throwable)} instead. + */ public AMQException(String msg, Throwable t) { super(msg, t); @@ -42,18 +78,19 @@ public class AMQException extends Exception _errorCode = AMQConstant.getConstant(-1); } - public AMQException(AMQConstant errorCode, String msg, Throwable t) - { - super(msg + " [error code " + errorCode + ']', t); - _errorCode = errorCode; - } - + /** + * @param errorCode + * @param msg + * + * @deprecated Use {@link #AMQException(org.apache.qpid.protocol.AMQConstant, String, Throwable)} instead. + */ public AMQException(AMQConstant errorCode, String msg) { super(msg + " [error code " + errorCode + ']'); _errorCode = errorCode; } + /* public AMQException(Logger logger, String msg, Throwable t) { this(msg, t); @@ -71,10 +108,15 @@ public class AMQException extends Exception this(errorCode, msg); logger.error(getMessage(), this); } + */ + /** + * Gets the AMQ protocol exception code associated with this exception. + * + * @return The AMQ protocol exception code associated with this exception. + */ public AMQConstant getErrorCode() { return _errorCode; } - } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java index 958f59191f..7c85a08e11 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java @@ -1,3 +1,4 @@ +/* Copyright Rupert Smith, 2005 to 2006, all rights reserved. */ /* * * Licensed to the Apache Software Foundation (ASF) under one @@ -7,9 +8,9 @@ * 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 @@ -21,6 +22,7 @@ package org.apache.qpid.configuration; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.protocol.AMQConstant; @@ -49,7 +51,7 @@ public class PropertyException extends AMQException super(errorCode, msg); } - public PropertyException(Logger logger, String msg, Throwable t) + /*public PropertyException(Logger logger, String msg, Throwable t) { super(logger, msg, t); } @@ -62,5 +64,5 @@ public class PropertyException extends AMQException public PropertyException(Logger logger, AMQConstant errorCode, String msg) { super(logger, errorCode, msg); - } + }*/ } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java index 43f888c029..9f36448986 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java @@ -94,7 +94,7 @@ public class AMQDataBlockDecoder if(bodyFactory == null) { - throw new AMQFrameDecodingException("Unsupported frame type: " + type); + throw new AMQFrameDecodingException(null, "Unsupported frame type: " + type, null); } final int channel = in.getUnsignedShort(); @@ -103,8 +103,8 @@ public class AMQDataBlockDecoder // bodySize can be zero if (channel < 0 || bodySize < 0) { - throw new AMQFrameDecodingException("Undecodable frame: type = " + type + " channel = " + channel + - " bodySize = " + bodySize); + throw new AMQFrameDecodingException(null, "Undecodable frame: type = " + type + " channel = " + channel + + " bodySize = " + bodySize, null); } AMQFrame frame = new AMQFrame(in, channel, bodySize, bodyFactory); @@ -113,7 +113,7 @@ public class AMQDataBlockDecoder byte marker = in.get(); if ((marker & 0xFF) != 0xCE) { - throw new AMQFrameDecodingException("End of frame marker not found. Read " + marker + " length=" + bodySize + " type=" + type); + throw new AMQFrameDecodingException(null, "End of frame marker not found. Read " + marker + " length=" + bodySize + " type=" + type, null); } return frame; } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java index a24bd6aaa9..c462dec2a3 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java @@ -1,3 +1,4 @@ +/* Copyright Rupert Smith, 2005 to 2006, all rights reserved. */ /* * * Licensed to the Apache Software Foundation (ASF) under one @@ -7,9 +8,9 @@ * 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 @@ -21,21 +22,23 @@ package org.apache.qpid.framing; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; +import org.apache.qpid.protocol.AMQConstant; public class AMQFrameDecodingException extends AMQException { - public AMQFrameDecodingException(String message) + /*public AMQFrameDecodingException(String message) { super(message); - } + }*/ - public AMQFrameDecodingException(String message, Throwable t) + public AMQFrameDecodingException(AMQConstant errorCode, String message, Throwable t) { - super(message, t); + super(errorCode, message, t); } - public AMQFrameDecodingException(Logger log, String message) + /*public AMQFrameDecodingException(Logger log, String message) { super(log, message); } @@ -43,6 +46,5 @@ public class AMQFrameDecodingException extends AMQException public AMQFrameDecodingException(Logger log, String message, Throwable t) { super(log, message, t); - } - + }*/ } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java index f51296dafc..f2492585bc 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java @@ -9,7 +9,7 @@ import org.apache.mina.common.ByteBuffer; * and thus can be held more effectively in a byte buffer. * */ -public final class AMQShortString implements CharSequence +public final class AMQShortString implements CharSequence, Comparable { private static final Logger _logger = Logger.getLogger(AMQShortString.class); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java index 8b784fa3f7..008afb490e 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java @@ -341,7 +341,7 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti } catch (AMQFrameDecodingException e) { - throw new RuntimeException("Error in content header data: " + e); + throw new RuntimeException("Error in content header data: " + e, e); } final int endPos = buffer.position(); @@ -381,7 +381,7 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti } catch (AMQFrameDecodingException e) { - throw new RuntimeException("Error in content header data: " + e); + throw new RuntimeException("Error in content header data: " + e, e); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java index 7dac018872..712eb437db 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderPropertiesFactory.java @@ -49,7 +49,7 @@ public class ContentHeaderPropertiesFactory } else { - throw new AMQFrameDecodingException("Unsupport content header class id: " + classId); + throw new AMQFrameDecodingException(null, "Unsupport content header class id: " + classId, null); } properties.populatePropertiesFromBuffer(buffer, propertyFlags, size); return properties; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java index f94cd4934c..f0cdda487c 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java @@ -7,9 +7,9 @@ * 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 @@ -23,6 +23,7 @@ package org.apache.qpid.framing; import java.nio.charset.Charset; import org.apache.log4j.Logger; + import org.apache.mina.common.ByteBuffer; public class EncodingUtils @@ -49,96 +50,95 @@ public class EncodingUtils } } - public static int encodedShortStringLength(short s) { - if( s == 0 ) + if (s == 0) { return 1 + 1; } int len = 0; - if(s < 0) + if (s < 0) { - len=1; + len = 1; // sloppy - doesn't work of Integer.MIN_VALUE - s=(short)-s; + s = (short) -s; } - if(s>9999) + if (s > 9999) { - return 1+5; + return 1 + 5; } - else if(s>999) + else if (s > 999) { - return 1+4; + return 1 + 4; } - else if(s>99) + else if (s > 99) { - return 1+3; + return 1 + 3; } - else if(s>9) + else if (s > 9) { - return 1+2; + return 1 + 2; } else { - return 1+1; + return 1 + 1; } } - public static int encodedShortStringLength(int i) { - if( i == 0 ) + if (i == 0) { return 1 + 1; } int len = 0; - if(i < 0) + if (i < 0) { - len=1; + len = 1; // sloppy - doesn't work of Integer.MIN_VALUE - i=-i; + i = -i; } // range is now 1 - 2147483647 - if(i < Short.MAX_VALUE) + if (i < Short.MAX_VALUE) { - return len + encodedShortStringLength((short)i); + return len + encodedShortStringLength((short) i); } else if (i > 999999) { - return len + 6 + encodedShortStringLength((short)(i/1000000)); + return len + 6 + encodedShortStringLength((short) (i / 1000000)); } else // if (i > 99999) { - return len + 5 + encodedShortStringLength((short)(i/100000)); + return len + 5 + encodedShortStringLength((short) (i / 100000)); } } public static int encodedShortStringLength(long l) { - if(l == 0) + if (l == 0) { return 1 + 1; } int len = 0; - if(l < 0) + if (l < 0) { - len=1; + len = 1; // sloppy - doesn't work of Long.MIN_VALUE - l=-l; + l = -l; } - if(l < Integer.MAX_VALUE) + + if (l < Integer.MAX_VALUE) { return len + encodedShortStringLength((int) l); } - else if(l > 9999999999L) + else if (l > 9999999999L) { return len + 10 + encodedShortStringLength((int) (l / 10000000000L)); } @@ -149,7 +149,6 @@ public class EncodingUtils } - public static int encodedShortStringLength(AMQShortString s) { if (s == null) @@ -162,7 +161,6 @@ public class EncodingUtils } } - public static int encodedLongStringLength(String s) { if (s == null) @@ -219,7 +217,6 @@ public class EncodingUtils return 0; } - public static void writeShortStringBytes(ByteBuffer buffer, String s) { if (s != null) @@ -230,6 +227,7 @@ public class EncodingUtils { encodedString[i] = (byte) cha[i]; } + writeBytes(buffer, encodedString); } else @@ -239,7 +237,6 @@ public class EncodingUtils } } - public static void writeShortStringBytes(ByteBuffer buffer, AMQShortString s) { if (s != null) @@ -256,7 +253,7 @@ public class EncodingUtils public static void writeLongStringBytes(ByteBuffer buffer, String s) { - assert s == null || s.length() <= 0xFFFE; + assert (s == null) || (s.length() <= 0xFFFE); if (s != null) { int len = s.length(); @@ -267,6 +264,7 @@ public class EncodingUtils { encodedString[i] = (byte) cha[i]; } + buffer.put(encodedString); } else @@ -277,7 +275,7 @@ public class EncodingUtils public static void writeLongStringBytes(ByteBuffer buffer, char[] s) { - assert s == null || s.length <= 0xFFFE; + assert (s == null) || (s.length <= 0xFFFE); if (s != null) { int len = s.length; @@ -287,6 +285,7 @@ public class EncodingUtils { encodedString[i] = (byte) s[i]; } + buffer.put(encodedString); } else @@ -297,7 +296,7 @@ public class EncodingUtils public static void writeLongStringBytes(ByteBuffer buffer, byte[] bytes) { - assert bytes == null || bytes.length <= 0xFFFE; + assert (bytes == null) || (bytes.length <= 0xFFFE); if (bytes != null) { writeUnsignedInteger(buffer, bytes.length); @@ -330,7 +329,6 @@ public class EncodingUtils } } - public static int unsignedIntegerLength() { return 4; @@ -356,7 +354,6 @@ public class EncodingUtils } } - public static void writeFieldTableBytes(ByteBuffer buffer, FieldTable table) { if (table != null) @@ -400,10 +397,9 @@ public class EncodingUtils if (value1) { - packedValue = (byte) (packedValue | (byte)(1 << 1)); + packedValue = (byte) (packedValue | (byte) (1 << 1)); } - buffer.put(packedValue); } @@ -413,213 +409,181 @@ public class EncodingUtils if (value1) { - packedValue = (byte) (packedValue | (byte)(1 << 1)); + packedValue = (byte) (packedValue | (byte) (1 << 1)); } if (value2) { - packedValue = (byte) (packedValue | (byte)(1 << 2)); + packedValue = (byte) (packedValue | (byte) (1 << 2)); } - buffer.put(packedValue); } - - - public static void writeBooleans(ByteBuffer buffer, - boolean value0, - boolean value1, - boolean value2, - boolean value3) + public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1, boolean value2, boolean value3) { byte packedValue = value0 ? (byte) 1 : (byte) 0; if (value1) { - packedValue = (byte) (packedValue | (byte)(1 << 1)); + packedValue = (byte) (packedValue | (byte) (1 << 1)); } if (value2) { - packedValue = (byte) (packedValue | (byte)(1 << 2)); + packedValue = (byte) (packedValue | (byte) (1 << 2)); } if (value3) { - packedValue = (byte) (packedValue | (byte)(1 << 3)); + packedValue = (byte) (packedValue | (byte) (1 << 3)); } buffer.put(packedValue); } - public static void writeBooleans(ByteBuffer buffer, - boolean value0, - boolean value1, - boolean value2, - boolean value3, - boolean value4) + public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1, boolean value2, boolean value3, + boolean value4) { byte packedValue = value0 ? (byte) 1 : (byte) 0; if (value1) { - packedValue = (byte) (packedValue | (byte)(1 << 1)); + packedValue = (byte) (packedValue | (byte) (1 << 1)); } if (value2) { - packedValue = (byte) (packedValue | (byte)(1 << 2)); + packedValue = (byte) (packedValue | (byte) (1 << 2)); } if (value3) { - packedValue = (byte) (packedValue | (byte)(1 << 3)); + packedValue = (byte) (packedValue | (byte) (1 << 3)); } if (value4) { - packedValue = (byte) (packedValue | (byte)(1 << 4)); + packedValue = (byte) (packedValue | (byte) (1 << 4)); } buffer.put(packedValue); } - public static void writeBooleans(ByteBuffer buffer, - boolean value0, - boolean value1, - boolean value2, - boolean value3, - boolean value4, - boolean value5) + public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1, boolean value2, boolean value3, + boolean value4, boolean value5) { byte packedValue = value0 ? (byte) 1 : (byte) 0; if (value1) { - packedValue = (byte) (packedValue | (byte)(1 << 1)); + packedValue = (byte) (packedValue | (byte) (1 << 1)); } if (value2) { - packedValue = (byte) (packedValue | (byte)(1 << 2)); + packedValue = (byte) (packedValue | (byte) (1 << 2)); } if (value3) { - packedValue = (byte) (packedValue | (byte)(1 << 3)); + packedValue = (byte) (packedValue | (byte) (1 << 3)); } if (value4) { - packedValue = (byte) (packedValue | (byte)(1 << 4)); + packedValue = (byte) (packedValue | (byte) (1 << 4)); } if (value5) { - packedValue = (byte) (packedValue | (byte)(1 << 5)); + packedValue = (byte) (packedValue | (byte) (1 << 5)); } buffer.put(packedValue); } - public static void writeBooleans(ByteBuffer buffer, - boolean value0, - boolean value1, - boolean value2, - boolean value3, - boolean value4, - boolean value5, - boolean value6) + public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1, boolean value2, boolean value3, + boolean value4, boolean value5, boolean value6) { byte packedValue = value0 ? (byte) 1 : (byte) 0; if (value1) { - packedValue = (byte) (packedValue | (byte)(1 << 1)); + packedValue = (byte) (packedValue | (byte) (1 << 1)); } if (value2) { - packedValue = (byte) (packedValue | (byte)(1 << 2)); + packedValue = (byte) (packedValue | (byte) (1 << 2)); } if (value3) { - packedValue = (byte) (packedValue | (byte)(1 << 3)); + packedValue = (byte) (packedValue | (byte) (1 << 3)); } if (value4) { - packedValue = (byte) (packedValue | (byte)(1 << 4)); + packedValue = (byte) (packedValue | (byte) (1 << 4)); } if (value5) { - packedValue = (byte) (packedValue | (byte)(1 << 5)); + packedValue = (byte) (packedValue | (byte) (1 << 5)); } if (value6) { - packedValue = (byte) (packedValue | (byte)(1 << 6)); + packedValue = (byte) (packedValue | (byte) (1 << 6)); } buffer.put(packedValue); } - public static void writeBooleans(ByteBuffer buffer, - boolean value0, - boolean value1, - boolean value2, - boolean value3, - boolean value4, - boolean value5, - boolean value6, - boolean value7) + public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1, boolean value2, boolean value3, + boolean value4, boolean value5, boolean value6, boolean value7) { byte packedValue = value0 ? (byte) 1 : (byte) 0; if (value1) { - packedValue = (byte) (packedValue | (byte)(1 << 1)); + packedValue = (byte) (packedValue | (byte) (1 << 1)); } if (value2) { - packedValue = (byte) (packedValue | (byte)(1 << 2)); + packedValue = (byte) (packedValue | (byte) (1 << 2)); } if (value3) { - packedValue = (byte) (packedValue | (byte)(1 << 3)); + packedValue = (byte) (packedValue | (byte) (1 << 3)); } if (value4) { - packedValue = (byte) (packedValue | (byte)(1 << 4)); + packedValue = (byte) (packedValue | (byte) (1 << 4)); } if (value5) { - packedValue = (byte) (packedValue | (byte)(1 << 5)); + packedValue = (byte) (packedValue | (byte) (1 << 5)); } if (value6) { - packedValue = (byte) (packedValue | (byte)(1 << 6)); + packedValue = (byte) (packedValue | (byte) (1 << 6)); } if (value7) { - packedValue = (byte) (packedValue | (byte)(1 << 7)); + packedValue = (byte) (packedValue | (byte) (1 << 7)); } buffer.put(packedValue); } - - - /** * This is used for writing longstrs. * @@ -647,26 +611,27 @@ public class EncodingUtils public static boolean[] readBooleans(ByteBuffer buffer) { final byte packedValue = buffer.get(); - if(packedValue == 0) + if (packedValue == 0) { return ALL_FALSE_ARRAY; } + final boolean[] result = new boolean[8]; result[0] = ((packedValue & 1) != 0); result[1] = ((packedValue & (1 << 1)) != 0); result[2] = ((packedValue & (1 << 2)) != 0); result[3] = ((packedValue & (1 << 3)) != 0); - if((packedValue & 0xF0) == 0) + if ((packedValue & 0xF0) == 0) { result[0] = ((packedValue & 1) != 0); } + result[4] = ((packedValue & (1 << 4)) != 0); result[5] = ((packedValue & (1 << 5)) != 0); result[6] = ((packedValue & (1 << 6)) != 0); result[7] = ((packedValue & (1 << 7)) != 0); - return result; } @@ -742,6 +707,7 @@ public class EncodingUtils { stringChars[i] = (char) stringBytes[i]; } + return new String(stringChars); } } @@ -757,6 +723,7 @@ public class EncodingUtils { byte[] result = new byte[(int) length]; buffer.get(result); + return result; } } @@ -764,15 +731,14 @@ public class EncodingUtils public static long readTimestamp(ByteBuffer buffer) { // Discard msb from AMQ timestamp - //buffer.getUnsignedInt(); + // buffer.getUnsignedInt(); return buffer.getLong(); } - static byte[] hexToByteArray(String id) { // Should check param for null, long enough for this check, upper-case and trailing char - String s = (id.charAt(1) == 'x') ? id.substring(2) : id; // strip 0x + String s = (id.charAt(1) == 'x') ? id.substring(2) : id; // strip 0x int len = s.length(); int byte_len = len / 2; @@ -786,7 +752,7 @@ public class EncodingUtils byte b1 = Byte.parseByte(s.substring(ch, ch + 1), 16); byte b2 = Byte.parseByte(s.substring(ch + 1, ch + 2), 16); - b[i] = (byte) (b1 * 16 + b2); + b[i] = (byte) ((b1 * 16) + b2); } return (b); @@ -795,7 +761,7 @@ public class EncodingUtils public static char[] convertToHexCharArray(byte[] from) { int length = from.length; - char[] result_buff = new char[length * 2 + 2]; + char[] result_buff = new char[(length * 2) + 2]; result_buff[0] = '0'; result_buff[1] = 'x'; @@ -831,7 +797,7 @@ public class EncodingUtils byte[] from = new byte[size]; // Is this not the same. - //bb.get(from, 0, length); + // bb.get(from, 0, length); for (int i = 0; i < size; i++) { from[i] = bb.get(i); @@ -840,9 +806,9 @@ public class EncodingUtils return (new String(convertToHexCharArray(from))); } - private static char hex_chars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + private static char[] hex_chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - //**** new methods + // **** new methods // AMQP_BOOLEAN_PROPERTY_PREFIX @@ -854,6 +820,7 @@ public class EncodingUtils public static boolean readBoolean(ByteBuffer buffer) { byte packedValue = buffer.get(); + return (packedValue == 1); } @@ -878,7 +845,6 @@ public class EncodingUtils return 1; } - // AMQP_SHORT_PROPERTY_PREFIX public static void writeShort(ByteBuffer buffer, Short aShort) { @@ -943,7 +909,6 @@ public class EncodingUtils return 4; } - // Double_PROPERTY_PREFIX public static void writeDouble(ByteBuffer buffer, Double aDouble) { @@ -960,7 +925,6 @@ public class EncodingUtils return 8; } - public static byte[] readBytes(ByteBuffer buffer) { short length = buffer.getUnsigned(); @@ -981,7 +945,7 @@ public class EncodingUtils { if (data != null) { - // TODO: check length fits in an unsigned byte + // TODO: check length fits in an unsigned byte writeUnsignedByte(buffer, (short) data.length); buffer.put(data); } @@ -992,7 +956,7 @@ public class EncodingUtils } } - //CHAR_PROPERTY + // CHAR_PROPERTY public static int encodedCharLength() { return encodedByteLength(); @@ -1000,31 +964,29 @@ public class EncodingUtils public static char readChar(ByteBuffer buffer) { - //This is valid as we know that the Character is ASCII 0..127 + // This is valid as we know that the Character is ASCII 0..127 return (char) buffer.get(); } public static void writeChar(ByteBuffer buffer, char character) { - //This is valid as we know that the Character is ASCII 0..127 + // This is valid as we know that the Character is ASCII 0..127 writeByte(buffer, (byte) character); } - - - public static long readLongAsShortString(ByteBuffer buffer) { short length = buffer.getUnsigned(); short pos = 0; - if(length == 0) + if (length == 0) { return 0L; } + byte digit = buffer.get(); boolean isNegative; long result = 0; - if(digit == (byte)'-') + if (digit == (byte) '-') { isNegative = true; pos++; @@ -1034,15 +996,16 @@ public class EncodingUtils { isNegative = false; } - result = digit - (byte)'0'; + + result = digit - (byte) '0'; pos++; - while(pos < length) + while (pos < length) { pos++; digit = buffer.get(); result = (result << 3) + (result << 1); - result += digit - (byte)'0'; + result += digit - (byte) '0'; } return result; @@ -1051,33 +1014,13 @@ public class EncodingUtils public static long readUnsignedInteger(ByteBuffer buffer) { long l = 0xFF & buffer.get(); - l <<=8; + l <<= 8; l = l | (0xFF & buffer.get()); - l <<=8; + l <<= 8; l = l | (0xFF & buffer.get()); - l <<=8; + l <<= 8; l = l | (0xFF & buffer.get()); return l; } - - - public static void main(String[] args) - { - ByteBuffer buf = ByteBuffer.allocate(8); - buf.setAutoExpand(true); - - long l = (long) Integer.MAX_VALUE; - l += 1024L; - - writeUnsignedInteger(buf, l); - - buf.flip(); - - long l2 = readUnsignedInteger(buf); - - System.out.println("before: " + l); - System.out.println("after: " + l2); - } - } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java index ec371453aa..faa7cc1e82 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java @@ -148,34 +148,30 @@ public class VersionSpecificRegistry } catch(NullPointerException e) { - throw new AMQFrameDecodingException(_log, - "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion - + " (while trying to decode class " + classID + " method " + methodID + "."); + throw new AMQFrameDecodingException(null, "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + " method " + methodID + ".", e); } catch(IndexOutOfBoundsException e) { if(classID >= _registry.length) { - throw new AMQFrameDecodingException(_log, - "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion - + " (while trying to decode class " + classID + " method " + methodID + "."); - + throw new AMQFrameDecodingException(null, "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + " method " + methodID + + ".", e); } else { - throw new AMQFrameDecodingException(_log, - "Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion - + " (while trying to decode class " + classID + " method " + methodID + "."); - + throw new AMQFrameDecodingException(null, "Method " + methodID + " unknown in AMQP version " + + _protocolMajorVersion + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + + " method " + methodID + ".", e); } } if (bodyFactory == null) { - throw new AMQFrameDecodingException(_log, - "Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion - + " (while trying to decode class " + classID + " method " + methodID + "."); + throw new AMQFrameDecodingException(null, "Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion + + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + " method " + methodID + ".", null); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/Event.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/Event.java index 09890a103d..7300ec8c3f 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/Event.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/Event.java @@ -85,4 +85,27 @@ abstract public class Event } + + public static final class CloseEvent extends Event + { + private final IoFilter.NextFilter _nextFilter; + + public CloseEvent(final IoFilter.NextFilter nextFilter) + { + super(); + _nextFilter = nextFilter; + } + + + public void process(IoSession session) + { + _nextFilter.sessionClosed(session); + } + + public IoFilter.NextFilter getNextFilter() + { + return _nextFilter; + } + } + } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java index 8126ca4bc8..c9c96925cb 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java @@ -7,9 +7,9 @@ * 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 @@ -24,10 +24,13 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.log4j.Logger; + import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoSession; +import org.apache.qpid.pool.Event.CloseEvent; + public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionHandler { private static final Logger _logger = Logger.getLogger(PoolingFilter.class); @@ -47,12 +50,12 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH void fireAsynchEvent(IoSession session, Event event) { Job job = getJobForSession(session); - // job.acquire(); //prevents this job being removed from _jobs + // job.acquire(); //prevents this job being removed from _jobs job.add(event); - //Additional checks on pool to check that it hasn't shutdown. + // Additional checks on pool to check that it hasn't shutdown. // The alternative is to catch the RejectedExecutionException that will result from executing on a shutdown pool - if (job.activate() && _poolReference.getPool() != null && !_poolReference.getPool().isShutdown()) + if (job.activate() && (_poolReference.getPool() != null) && !_poolReference.getPool().isShutdown()) { _poolReference.getPool().execute(job); } @@ -68,16 +71,6 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH private Job getJobForSession(IoSession session) { return (Job) session.getAttribute(_name); - -/* if(job == null) - { - System.err.println("Error in " + _name); - Thread.dumpStack(); - } - - - job = _jobs.get(session); - return job == null ? createJobForSession(session) : job;*/ } private Job createJobForSession(IoSession session) @@ -87,35 +80,36 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH private Job addJobForSession(IoSession session, Job job) { - //atomic so ensures all threads agree on the same job + // atomic so ensures all threads agree on the same job Job existing = _jobs.putIfAbsent(session, job); - return existing == null ? job : existing; + + return (existing == null) ? job : existing; } - //Job.JobCompletionHandler + // Job.JobCompletionHandler public void completed(IoSession session, Job job) { -// if (job.isComplete()) -// { -// job.release(); -// if (!job.isReferenced()) -// { -// _jobs.remove(session); -// } -// } -// else - if(!job.isComplete()) + // if (job.isComplete()) + // { + // job.release(); + // if (!job.isReferenced()) + // { + // _jobs.remove(session); + // } + // } + // else + if (!job.isComplete()) { // ritchiem : 2006-12-13 Do we need to perform the additional checks here? - // Can the pool be shutdown at this point? - if (job.activate() && _poolReference.getPool() != null && !_poolReference.getPool().isShutdown()) + // Can the pool be shutdown at this point? + if (job.activate() && (_poolReference.getPool() != null) && !_poolReference.getPool().isShutdown()) { _poolReference.getPool().execute(job); } } } - //IoFilter methods that are processed by threads on the pool + // IoFilter methods that are processed by threads on the pool public void sessionOpened(final NextFilter nextFilter, final IoSession session) throws Exception { @@ -127,37 +121,33 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH nextFilter.sessionClosed(session); } - public void sessionIdle(final NextFilter nextFilter, final IoSession session, - final IdleStatus status) throws Exception + public void sessionIdle(final NextFilter nextFilter, final IoSession session, final IdleStatus status) throws Exception { nextFilter.sessionIdle(session, status); } - public void exceptionCaught(final NextFilter nextFilter, final IoSession session, - final Throwable cause) throws Exception + public void exceptionCaught(final NextFilter nextFilter, final IoSession session, final Throwable cause) throws Exception { - nextFilter.exceptionCaught(session,cause); + nextFilter.exceptionCaught(session, cause); } - public void messageReceived(final NextFilter nextFilter, final IoSession session, - final Object message) throws Exception + public void messageReceived(final NextFilter nextFilter, final IoSession session, final Object message) throws Exception { - nextFilter.messageReceived(session,message); + nextFilter.messageReceived(session, message); } - public void messageSent(final NextFilter nextFilter, final IoSession session, - final Object message) throws Exception + public void messageSent(final NextFilter nextFilter, final IoSession session, final Object message) throws Exception { nextFilter.messageSent(session, message); } - public void filterWrite(final NextFilter nextFilter, final IoSession session, - final WriteRequest writeRequest) throws Exception + public void filterWrite(final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest) + throws Exception { nextFilter.filterWrite(session, writeRequest); } - //IoFilter methods that are processed on current thread (NOT on pooled thread) + // IoFilter methods that are processed on current thread (NOT on pooled thread) public void filterClose(NextFilter nextFilter, IoSession session) throws Exception { @@ -199,13 +189,17 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH super(refCountingPool, name); } - public void messageReceived(final NextFilter nextFilter, final IoSession session, - final Object message) throws Exception + public void messageReceived(final NextFilter nextFilter, final IoSession session, final Object message) + throws Exception { fireAsynchEvent(session, new Event.ReceivedEvent(nextFilter, message)); } + public void sessionClosed(final NextFilter nextFilter, final IoSession session) throws Exception + { + fireAsynchEvent(session, new CloseEvent(nextFilter)); + } } @@ -217,26 +211,27 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH super(refCountingPool, name); } - - public void filterWrite(final NextFilter nextFilter, final IoSession session, - final WriteRequest writeRequest) throws Exception + public void filterWrite(final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest) + throws Exception { fireAsynchEvent(session, new Event.WriteEvent(nextFilter, writeRequest)); } + public void sessionClosed(final NextFilter nextFilter, final IoSession session) throws Exception + { + fireAsynchEvent(session, new CloseEvent(nextFilter)); + } + } - public static PoolingFilter createAynschReadPoolingFilter(ReferenceCountingExecutorService refCountingPool,String name) + public static PoolingFilter createAynschReadPoolingFilter(ReferenceCountingExecutorService refCountingPool, String name) { - return new AsynchReadPoolingFilter(refCountingPool,name); + return new AsynchReadPoolingFilter(refCountingPool, name); } - - public static PoolingFilter createAynschWritePoolingFilter(ReferenceCountingExecutorService refCountingPool,String name) + public static PoolingFilter createAynschWritePoolingFilter(ReferenceCountingExecutorService refCountingPool, String name) { - return new AsynchWritePoolingFilter(refCountingPool,name); + return new AsynchWritePoolingFilter(refCountingPool, name); } } - - diff --git a/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java b/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java index f558523864..353c0d39c2 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java @@ -7,9 +7,9 @@ * 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 @@ -24,9 +24,10 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; +import org.apache.log4j.Logger; + import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.framing.AMQShortString; -import org.apache.log4j.Logger; public class AMQBindingURL implements BindingURL { @@ -39,10 +40,9 @@ public class AMQBindingURL implements BindingURL AMQShortString _queueName; private HashMap _options; - public AMQBindingURL(String url) throws URLSyntaxException { - //format: + // format: // :///[]/[]?

      CRC Card + * Responsibilities Collaborations + * Define the set of AMQP status codes. + * Provide a factory to lookup constants by their code. + * + */ public final class AMQConstant { - private int _code; - - private AMQShortString _name; - + /** Defines a map from codes to constants. */ private static Map _codeMap = new HashMap(); - private AMQConstant(int code, String name, boolean map) - { - _code = code; - _name = new AMQShortString(name); - if (map) - { - _codeMap.put(new Integer(code), this); - } - } - - public String toString() - { - return _code + ": " + _name; - } - - public int getCode() - { - return _code; - } - - public AMQShortString getName() - { - return _name; - } - - public static final AMQConstant FRAME_MIN_SIZE = new AMQConstant(4096, "frame min size", true); + /** Indicates that the method completed successfully. */ + public static final AMQConstant REPLY_SUCCESS = new AMQConstant(200, "reply success", true); public static final AMQConstant FRAME_END = new AMQConstant(206, "frame end", true); - public static final AMQConstant REPLY_SUCCESS = new AMQConstant(200, "reply success", true); - + /** + * The client asked for a specific message that is no longer available. The message was delivered to another + * client, or was purged from the queue for some other reason. + */ public static final AMQConstant NOT_DELIVERED = new AMQConstant(310, "not delivered", true); + /** + * The client attempted to transfer content larger than the server could accept at the present time. The client + * may retry at a later time. + */ public static final AMQConstant MESSAGE_TOO_LARGE = new AMQConstant(311, "message too large", true); + /** + * When the exchange cannot route the result of a .Publish, most likely due to an invalid routing key. Only when + * the mandatory flag is set. + */ public static final AMQConstant NO_ROUTE = new AMQConstant(312, "no route", true); + /** + * When the exchange cannot deliver to a consumer when the immediate flag is set. As a result of pending data on + * the queue or the absence of any consumers of the queue. + */ public static final AMQConstant NO_CONSUMERS = new AMQConstant(313, "no consumers", true); + /** + * An operator intervened to close the connection for some reason. The client may retry at some later date. + */ public static final AMQConstant CONTEXT_IN_USE = new AMQConstant(320, "context in use", true); + /** The client tried to work with an unknown virtual host or cluster. */ public static final AMQConstant INVALID_PATH = new AMQConstant(402, "invalid path", true); + /** The client attempted to work with a server entity to which it has no access due to security settings. */ public static final AMQConstant ACCESS_REFUSED = new AMQConstant(403, "access refused", true); + /** The client attempted to work with a server entity that does not exist. */ public static final AMQConstant NOT_FOUND = new AMQConstant(404, "not found", true); + /** + * The client attempted to work with a server entity to which it has no access because another client is + * working with it. + */ public static final AMQConstant ALREADY_EXISTS = new AMQConstant(405, "Already exists", true); + /** The client requested a method that was not allowed because some precondition failed. */ public static final AMQConstant IN_USE = new AMQConstant(406, "In use", true); public static final AMQConstant INVALID_ROUTING_KEY = new AMQConstant(407, "routing key invalid", true); public static final AMQConstant REQUEST_TIMEOUT = new AMQConstant(408, "Request Timeout", true); - public static final AMQConstant INVALID_ARGUMENT = new AMQConstant(409, "argument invalid", true); + public static final AMQConstant INVALID_ARGUMENT = new AMQConstant(409, "argument invalid", true); + /** + * The client sent a malformed frame that the server could not decode. This strongly implies a programming error + * in the client. + */ public static final AMQConstant FRAME_ERROR = new AMQConstant(501, "frame error", true); + /** + * The client sent a frame that contained illegal values for one or more fields. This strongly implies a + * programming error in the client. + */ public static final AMQConstant SYNTAX_ERROR = new AMQConstant(502, "syntax error", true); + /** + * The client sent an invalid sequence of frames, attempting to perform an operation that was considered invalid + * by the server. This usually implies a programming error in the client. + */ public static final AMQConstant COMMAND_INVALID = new AMQConstant(503, "command invalid", true); + /** + * The client attempted to work with a channel that had not been correctly opened. This most likely indicates a + * fault in the client layer. + */ public static final AMQConstant CHANNEL_ERROR = new AMQConstant(504, "channel error", true); + /** + * The server could not complete the method because it lacked sufficient resources. This may be due to the client + * creating too many of some type of entity. + */ public static final AMQConstant RESOURCE_ERROR = new AMQConstant(506, "resource error", true); + /** + * The client tried to work with some entity in a manner that is prohibited by the server, due to security settings + * or by some other criteria. + */ public static final AMQConstant NOT_ALLOWED = new AMQConstant(530, "not allowed", true); + /** The client tried to use functionality that is not implemented in the server. */ public static final AMQConstant NOT_IMPLEMENTED = new AMQConstant(540, "not implemented", true); + /** + * The server could not complete the method because of an internal error. The server may require intervention by + * an operator in order to resume normal operations. + */ public static final AMQConstant INTERNAL_ERROR = new AMQConstant(541, "internal error", true); + public static final AMQConstant FRAME_MIN_SIZE = new AMQConstant(4096, "frame min size", true); + + /** The AMQP status code. */ + private int _code; + + /** A short description of the status code. */ + private AMQShortString _name; + + /** + * Creates a new AMQP status code. + * + * @param code The code. + * @param name A short description of the code. + * @param map true to register the code as a known code, false otherwise. + */ + private AMQConstant(int code, String name, boolean map) + { + _code = code; + _name = new AMQShortString(name); + if (map) + { + _codeMap.put(new Integer(code), this); + } + } + + /** + * Creates a constant for a status code by looking up the code in the map of known codes. If the code is not known + * a constant is still created for it, but it is marked as unknown. + * + * @param code The AMQP status code. + * + * @return The AMQP status code encapsulated as a constant. + */ public static AMQConstant getConstant(int code) { AMQConstant c = (AMQConstant) _codeMap.get(new Integer(code)); @@ -113,6 +191,37 @@ public final class AMQConstant { c = new AMQConstant(code, "unknown code", false); } + return c; } + + /** + * Gets the underlying AMQP status code. + * + * @return The AMQP status code. + */ + public int getCode() + { + return _code; + } + + /** + * Gets a short description of the status code. + * + * @return A short description of the status code. + */ + public AMQShortString getName() + { + return _name; + } + + /** + * Renders the constant as a string, mainly for debugging purposes. + * + * @return The status code and its description. + */ + public String toString() + { + return _code + ": " + _name; + } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java index ab36041cb8..fd6907a152 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodEvent.java @@ -7,9 +7,9 @@ * 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 @@ -23,43 +23,73 @@ package org.apache.qpid.protocol; import org.apache.qpid.framing.AMQMethodBody; /** - * An event that is passed to AMQMethodListeners describing a particular method. - * It supplies the: - *

      • channel id
      • + * AMQMethodEvent encapsulates an AMQP method call, and the channel on which that method call occurred. + * + *

        Supplies the: + *

          + *
        • channel id
        • *
        • protocol method
        • - * to listeners. This means that listeners do not need to be stateful. + *
        * - * In the StateAwareMethodListener, other useful objects such as the protocol session - * are made available. - * + *

        As the event contains the context in which it occurred, event listeners do not need to be statefull. + * to listeners. Events are often handled by {@link AMQMethodListener}s. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Encapsulate an AMQP method call and the channel as the context for the method call. + *
        */ public class AMQMethodEvent { + /** Holds the method call. */ private final M _method; + /** Holds the channel handle for the method call. */ private final int _channelId; + /** + * Creates a method event to encasulate a method call and channel. + * + * @param channelId The channel on which the method call occurred. + * @param method The method call. + */ public AMQMethodEvent(int channelId, M method) { _channelId = channelId; _method = method; } + /** + * Gets the method call. + * + * @return The method call. + */ public M getMethod() { return _method; } + /** + * Gets the channel handle for the method call. + * + * @return The channel handle for the method call. + */ public int getChannelId() { return _channelId; } + /** + * Prints the method call as a string, mainly for debugging purposes. + * + * @return The method call as a string, mainly for debugging purposes. + */ public String toString() { StringBuilder buf = new StringBuilder("Method event: "); buf.append("\nChannel id: ").append(_channelId); buf.append("\nMethod: ").append(_method); + return buf.toString(); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java index 85bbe50b11..808272e9ec 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java @@ -7,9 +7,9 @@ * 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 @@ -20,31 +20,52 @@ */ package org.apache.qpid.protocol; -import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQMethodBody; /** - * Interface that allows classes to register for interest in protocol method frames. - * + * AMQMethodListener is a listener that receives notifications of AMQP methods. The methods are packaged as events in + * {@link AMQMethodEvent}. + * + *

        An event listener may be associated with a particular context, usually an AMQP channel, and in addition to + * receiving method events will be notified of errors on that context. This enables listeners to perform any clean + * up that they need to do before the context is closed. + * + *

        + *
        CRC Card
        Responsibilities + *
        Accept notification of AMQP method events. {@link AMQMethodEvent} + *
        Accept notification of errors on the event context. + *
        + * + * @todo Document why the exception is passed to the error method. Is it so that the exception can be passed + * from the event handling thread to another thread and rethown from there? It is unusual to pass exceptions as + * method arguments, because they have their own mechanism for propagating through the call stack, so some + * explanation ought to be provided. */ public interface AMQMethodListener { /** - * Invoked when a method frame has been received - * @param evt the event that contains the method and channel - * @param protocolSession the protocol session associated with the event - * @return true if the handler has processed the method frame, false otherwise. Note - * that this does not prohibit the method event being delivered to subsequent listeners - * but can be used to determine if nobody has dealt with an incoming method frame. - * @throws AMQException if an error has occurred. This exception will be delivered - * to all registered listeners using the error() method (see below) allowing them to - * perform cleanup if necessary. + * Notifies the listener that an AMQP method event has occurred. + * + * @param evt The AMQP method event (contains the method and channel). + * + * @return true if the handler processes the method frame, false otherwise. Note that this does + * not prohibit the method event being delivered to subsequent listeners but can be used to determine if + * nobody has dealt with an incoming method frame. + * + * @throws Exception if an error has occurred. This exception may be delivered to all registered listeners using + * the error() method (see below) allowing them to perform cleanup if necessary. + * + * @todo Consider narrowing the exception. */ boolean methodReceived(AMQMethodEvent evt) throws Exception; /** - * Callback when an error has occurred. Allows listeners to clean up. - * @param e + * Notifies the listener of an error on the event context to which it is listening. The listener should perform + * any necessary clean-up for the context. + * + * @param e The underlying exception that is the source of the error. + * + * @todo Consider narrowing the exception, or wrapping it. */ void error(Exception e); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQProtocolWriter.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQProtocolWriter.java index bc06fc3e6f..65884e4950 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQProtocolWriter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQProtocolWriter.java @@ -22,11 +22,22 @@ package org.apache.qpid.protocol; import org.apache.qpid.framing.AMQDataBlock; +/** + * AMQProtocolWriter provides a method to write a frame of data 'to the wire', in the context of the object + * that implements the method, usually some sort of session. The block of data, encapsulated by {@link AMQDataBlock}, + * will be encoded as it is written. + * + *

        + *
        CRC Card
        Responsibilities + *
        Write an encoded block of data to the write, in the context of a session. + *
        + */ public interface AMQProtocolWriter { /** - * Write a datablock, encoding where necessary (e.g. into a sequence of bytes) - * @param frame the frame to be encoded and written + * Writes a frame to the wire, encoding it as necessary, for example, into a sequence of bytes. + * + * @param frame The frame to be encoded and written. */ - public void writeFrame(AMQDataBlock frame); + public void writeFrame(AMQDataBlock frame); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java index b57c26e496..7c1d6fdaa0 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java @@ -22,7 +22,25 @@ package org.apache.qpid.protocol; import org.apache.qpid.framing.VersionSpecificRegistry; +/** + * AMQVersionAwareProtocolSession is implemented by all AMQP session classes, that need to provide an awareness to + * callers of the version of the AMQP protocol that they are able to work with. + * + *

        + *
        CRC Card
        Responsibilities + *
        Provide the method registry for a specific version of the AMQP. + *
        + * + * @todo Why is this a seperate interface to {@link ProtocolVersionAware}, could they be combined into a single + * interface and one of them eliminated? Move getRegistry method to ProtocolVersionAware, make the sessions + * implement AMQProtocolWriter directly and drop this interface. + */ public interface AMQVersionAwareProtocolSession extends AMQProtocolWriter, ProtocolVersionAware { + /** + * Gets the method registry for a specific version of the AMQP. + * + * @return The method registry for a specific version of the AMQP. + */ public VersionSpecificRegistry getRegistry(); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java index 64db953bc2..60a7f30185 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java @@ -20,9 +20,28 @@ */ package org.apache.qpid.protocol; +/** + * ProtocolVersionAware is implemented by all AMQP handling classes, that need to provide an awareness to callers of + * the version of the AMQP protocol that they are able to handle. + * + *

        + *
        CRC Card
        Responsibilities + *
        Report the major and minor AMQP version handled. + *
        + */ public interface ProtocolVersionAware { + /** + * Reports the AMQP minor version, that the implementer can handle. + * + * @return The AMQP minor version. + */ public byte getProtocolMinorVersion(); + /** + * Reports the AMQP major version, that the implementer can handle. + * + * @return The AMQP major version. + */ public byte getProtocolMajorVersion(); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/MessageQueue.java b/qpid/java/common/src/main/java/org/apache/qpid/util/MessageQueue.java index 9cf3319374..b5efaa61b6 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/MessageQueue.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/MessageQueue.java @@ -14,17 +14,30 @@ * "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. + * under the License. + * * - * */ package org.apache.qpid.util; import java.util.Queue; +/** + * Defines a queue that has a push operation to add an element to the head of the queue. + * + * @todo Seems like this may be pointless, the implementation uses this method to increment the message count + * then calls offer. Why not simply override offer and drop this interface? + */ public interface MessageQueue extends Queue { - + /** + * Inserts the specified element into this queue, if possible. When using queues that may impose insertion + * restrictions (for example capacity bounds), method offer is generally preferable to method Collection.add(E), + * which can fail to insert an element only by throwing an exception. + * + * @param o The element to insert. + * + * @return true if it was possible to add the element to this queue, else false + */ boolean pushHead(E o); - } -- cgit v1.2.1 From 0d3e290f5cf129f7222b7a77481ade6086e372e1 Mon Sep 17 00:00:00 2001 From: Rupert Smith Date: Tue, 15 May 2007 16:32:10 +0000 Subject: Merged revisions 538109 via svnmerge from https://svn.apache.org/repos/asf/incubator/qpid/branches/M2 ........ r538109 | rupertlssmith | 2007-05-15 10:48:16 +0100 (Tue, 15 May 2007) | 1 line More Javadocing. ........ git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@538247 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/codec/AMQCodecFactory.java | 36 +++++++++-- .../java/org/apache/qpid/codec/AMQDecoder.java | 74 ++++++++++++++++++++-- .../java/org/apache/qpid/codec/AMQEncoder.java | 37 +++++++++-- .../java/org/apache/qpid/protocol/AMQConstant.java | 2 +- 4 files changed, 131 insertions(+), 18 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQCodecFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQCodecFactory.java index d7f1edbc30..4e3a46eb90 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQCodecFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQCodecFactory.java @@ -7,9 +7,9 @@ * 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 @@ -24,28 +24,52 @@ import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolEncoder; +/** + * AMQCodecFactory is a Mina codec factory. It supplies the encoders and decoders need to read and write the bytes to + * the wire. + * + *

        + *
        CRC Card
        Responsibilities Collaborations. + *
        Supply the protocol encoder. {@link AMQEncoder} + *
        Supply the protocol decoder. {@link AMQDecoder} + *
        + */ public class AMQCodecFactory implements ProtocolCodecFactory { + /** Holds the protocol encoder. */ private AMQEncoder _encoder = new AMQEncoder(); + /** Holds the protocol decoder. */ private AMQDecoder _frameDecoder; /** - * @param expectProtocolInitiation true if the first frame received is going to be - * a protocol initiation frame, false if it is going to be a standard AMQ data block. - * The former case is used for the broker, which always expects to received the - * protocol initiation first from a newly connected client. + * Creates a new codec factory, specifiying whether it is expected that the first frame of data should be an + * initiation. This is the case for the broker, which always expects to received the protocol initiation on a newly + * connected client. + * + * @param expectProtocolInitiation true if the first frame received is going to be a protocol initiation + * frame, false if it is going to be a standard AMQ data block. */ public AMQCodecFactory(boolean expectProtocolInitiation) { _frameDecoder = new AMQDecoder(expectProtocolInitiation); } + /** + * Gets the AMQP encoder. + * + * @return The AMQP encoder. + */ public ProtocolEncoder getEncoder() { return _encoder; } + /** + * Gets the AMQP decoder. + * + * @return The AMQP decoder. + */ public ProtocolDecoder getDecoder() { return _frameDecoder; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java index bb981a242f..02ae3cb089 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQDecoder.java @@ -7,9 +7,9 @@ * 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 @@ -24,28 +24,61 @@ import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; + import org.apache.qpid.framing.AMQDataBlockDecoder; import org.apache.qpid.framing.ProtocolInitiation; /** - * There is one instance of this class per session. Any changes or configuration done - * at run time to the encoders or decoders only affects decoding/encoding of the - * protocol session data to which is it bound. + * AMQDecoder delegates the decoding of AMQP either to a data block decoder, or in the case of new connections, to a + * protocol initiation decoder. It is a cumulative decoder, which means that it can accumulate data to decode in the + * buffer until there is enough data to decode. + * + *

        One instance of this class is created per session, so any changes or configuration done at run time to the + * decoder will only affect decoding of the protocol session data to which is it bound. * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Delegate protocol initiation to its decoder. {@link ProtocolInitiation.Decoder} + *
        Delegate AMQP data to its decoder. {@link AMQDataBlockDecoder} + *
        Accept notification that protocol initiation has completed. + *
        + * + * @todo If protocol initiation decoder not needed, then don't create it. Probably not a big deal, but it adds to the + * per-session overhead. */ public class AMQDecoder extends CumulativeProtocolDecoder { + /** Holds the 'normal' AMQP data decoder. */ private AMQDataBlockDecoder _dataBlockDecoder = new AMQDataBlockDecoder(); + /** Holds the protocol initiation decoder. */ private ProtocolInitiation.Decoder _piDecoder = new ProtocolInitiation.Decoder(); + /** Flag to indicate whether this decoder needs to handle protocol initiation. */ private boolean _expectProtocolInitiation; + /** + * Creates a new AMQP decoder. + * + * @param expectProtocolInitiation true if this decoder needs to handle protocol initiation. + */ public AMQDecoder(boolean expectProtocolInitiation) { _expectProtocolInitiation = expectProtocolInitiation; } + /** + * Delegates decoding AMQP from the data buffer that Mina has retrieved from the wire, to the data or protocol + * intiation decoders. + * + * @param session The Mina session. + * @param in The raw byte buffer. + * @param out The Mina object output gatherer to write decoded objects to. + * + * @return true if the data was decoded, false if more is needed and the data should accumulate. + * + * @throws Exception If the data cannot be decoded for any reason. + */ protected boolean doDecode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { if (_expectProtocolInitiation) @@ -58,6 +91,17 @@ public class AMQDecoder extends CumulativeProtocolDecoder } } + /** + * Decodes AMQP data, delegating the decoding to an {@link AMQDataBlockDecoder}. + * + * @param session The Mina session. + * @param in The raw byte buffer. + * @param out The Mina object output gatherer to write decoded objects to. + * + * @return true if the data was decoded, false if more is needed and the data should accumulate. + * + * @throws Exception If the data cannot be decoded for any reason. + */ protected boolean doDecodeDataBlock(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { int pos = in.position(); @@ -72,10 +116,22 @@ public class AMQDecoder extends CumulativeProtocolDecoder else { _dataBlockDecoder.decode(session, in, out); + return true; } } + /** + * Decodes an AMQP initiation, delegating the decoding to a {@link ProtocolInitiation.Decoder}. + * + * @param session The Mina session. + * @param in The raw byte buffer. + * @param out The Mina object output gatherer to write decoded objects to. + * + * @return true if the data was decoded, false if more is needed and the data should accumulate. + * + * @throws Exception If the data cannot be decoded for any reason. + */ private boolean doDecodePI(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { boolean enoughData = _piDecoder.decodable(session, in); @@ -88,10 +144,18 @@ public class AMQDecoder extends CumulativeProtocolDecoder else { _piDecoder.decode(session, in, out); + return true; } } + /** + * Sets the protocol initation flag, that determines whether decoding is handled by the data decoder of the protocol + * initation decoder. This method is expected to be called with false once protocol initation completes. + * + * @param expectProtocolInitiation true to use the protocol initiation decoder, false to use the + * data decoder. + */ public void setExpectProtocolInitiation(boolean expectProtocolInitiation) { _expectProtocolInitiation = expectProtocolInitiation; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQEncoder.java b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQEncoder.java index fdb2e60c62..53f48ae1c8 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQEncoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQEncoder.java @@ -7,9 +7,9 @@ * 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 @@ -23,19 +23,44 @@ package org.apache.qpid.codec; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderOutput; + import org.apache.qpid.framing.AMQDataBlockEncoder; +/** + * AMQEncoder delegates encoding of AMQP to a data encoder. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Delegate AMQP encoding. {@link AMQDataBlockEncoder} + *
        + * + * @todo This class just delegates to another, so seems to be pointless. Unless it is going to handle some + * responsibilities in the future, then drop it. + */ public class AMQEncoder implements ProtocolEncoder { + /** The data encoder that is delegated to. */ private AMQDataBlockEncoder _dataBlockEncoder = new AMQDataBlockEncoder(); + /** + * Encodes AMQP. + * + * @param session The Mina session. + * @param message The data object to encode. + * @param out The Mina writer to output the raw byte data to. + * + * @throws Exception If the data cannot be encoded for any reason. + */ public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { _dataBlockEncoder.encode(session, message, out); } - public void dispose(IoSession session) throws Exception - { - - } + /** + * Does nothing. Called by Mina to allow this to clean up resources when it is no longer needed. + * + * @param session The Mina session. + */ + public void dispose(IoSession session) + { } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java index fa75bd5fb3..375df2a45d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java @@ -30,7 +30,7 @@ import org.apache.qpid.framing.AMQShortString; * constant also defines a short human readable description of the constant. * * @todo Why would a constant be defined that is not in the map? Seems more natural that getConstant should raise an - * exception for an unknown constant. Or else provide an explanation of why this is so. Also their is no way for + * exception for an unknown constant. Or else provide an explanation of why this is so. Also, there is no way for * callers to determine the unknown status of a code except by comparing its name to "unknown code", which would * seem to render this scheme a little bit pointless? * -- cgit v1.2.1 From 6cdba172a3344d92a5593f2e02545b939f8db935 Mon Sep 17 00:00:00 2001 From: Rupert Smith Date: Thu, 17 May 2007 13:27:40 +0000 Subject: Merged revisions 538907 via svnmerge from https://svn.apache.org/repos/asf/incubator/qpid/branches/M2 ........ r538907 | rupertlssmith | 2007-05-17 14:17:59 +0100 (Thu, 17 May 2007) | 1 line Added to the Javadoc ........ git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@538914 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/common/AMQPFilterTypes.java | 23 +- .../org/apache/qpid/common/ClientProperties.java | 12 +- .../org/apache/qpid/common/QpidProperties.java | 85 +++++- .../org/apache/qpid/configuration/Configured.java | 6 +- .../qpid/configuration/PropertyException.java | 13 +- .../apache/qpid/configuration/PropertyUtils.java | 86 +++--- .../org/apache/qpid/exchange/ExchangeDefaults.java | 45 ++- .../src/main/java/org/apache/qpid/pool/Event.java | 80 +++-- .../src/main/java/org/apache/qpid/pool/Job.java | 100 +++++-- .../java/org/apache/qpid/pool/PoolingFilter.java | 325 +++++++++++++++++---- .../org/apache/qpid/pool/ReadWriteThreadModel.java | 59 +++- .../pool/ReferenceCountingExecutorService.java | 77 ++++- .../org/apache/qpid/util/CommandLineParser.java | 2 +- 13 files changed, 728 insertions(+), 185 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java b/qpid/java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java index d8aa9bf5ca..9ed915cc35 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java @@ -14,27 +14,46 @@ * "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. + * under the License. + * * - * */ package org.apache.qpid.common; import org.apache.qpid.framing.AMQShortString; +/** + * Specifies the different filter types for consumers that filter their messages. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represent different consumer filter types. + *
        + */ public enum AMQPFilterTypes { JMS_SELECTOR("x-filter-jms-selector"), NO_CONSUME("x-filter-no-consume"), AUTO_CLOSE("x-filter-auto-close"); + /** The identifying string for the filter type. */ private final AMQShortString _value; + /** + * Creates a new filter type from its identifying string. + * + * @param value The identifying string. + */ AMQPFilterTypes(String value) { _value = new AMQShortString(value); } + /** + * Gets the identifying string of the filter type. + * + * @return The identifying string of the filter type. + */ public AMQShortString getValue() { return _value; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java index 07371b5182..67f16e6a87 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java @@ -14,12 +14,20 @@ * "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. + * under the License. + * * - * */ package org.apache.qpid.common; +/** + * Specifies the available client property types that different clients can use to identify themselves with. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Specify the available client property types. + *
        + */ public enum ClientProperties { instance, diff --git a/qpid/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java index 80377ffdf5..5a357557ca 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java @@ -14,9 +14,9 @@ * "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. + * under the License. + * * - * */ package org.apache.qpid.common; @@ -27,23 +27,56 @@ import java.util.Properties; import org.apache.log4j.Logger; +/** + * QpidProperties captures the project name, version number, and source code repository revision number from a properties + * file which is generated as part of the build process. Normally, the name and version number are pulled from the module + * name and version number of the Maven build POM, but could come from other sources if the build system is changed. The + * idea behind this, is that every build has these values incorporated directly into its jar file, so that code in the + * wild can be identified, should its origination be forgotten. + * + *

        To get the build version of any Qpid code call the {@link #main} method. This version string is usually also + * printed to the console on broker start up. + * + *

        + *
        CRC Card
        Load build versioning information into the runtime, for code identification purposes. + *
        + * + * @todo Code to locate/load/log properties can be factored into a reusable properties utils class. Avoid having this + * same snippet of loading code scattered in many places. + * + * @todo Could also add a build number property for a sequential build number assigned by an automated build system, for + * build reproducability purposes. + */ public class QpidProperties { + /** Used for debugging purposes. */ private static final Logger _logger = Logger.getLogger(QpidProperties.class); - + + /** The name of the version properties file to load from the class path. */ public static final String VERSION_RESOURCE = "qpidversion.properties"; + /** Defines the name of the product property. */ public static final String PRODUCT_NAME_PROPERTY = "qpid.name"; + + /** Defines the name of the version property. */ public static final String RELEASE_VERSION_PROPERTY = "qpid.version"; + + /** Defines the name of the source code revision property. */ public static final String BUILD_VERSION_PROPERTY = "qpid.svnversion"; + /** Defines the default value for all properties that cannot be loaded. */ private static final String DEFAULT = "unknown"; + /** Holds the product name. */ private static String productName = DEFAULT; + + /** Holds the product version. */ private static String releaseVersion = DEFAULT; + + /** Holds the source code revision. */ private static String buildVersion = DEFAULT; - /** Loads the values from the version properties file. */ + // Loads the values from the version properties file. static { Properties props = new Properties(); @@ -62,16 +95,17 @@ public class QpidProperties if (_logger.isDebugEnabled()) { _logger.debug("Dumping QpidProperties"); - for (Map.Entry entry : props.entrySet()) + for (Map.Entry entry : props.entrySet()) { - _logger.debug("Property: " + entry.getKey() + " Value: "+ entry.getValue()); + _logger.debug("Property: " + entry.getKey() + " Value: " + entry.getValue()); } + _logger.debug("End of property dump"); } productName = readPropertyValue(props, PRODUCT_NAME_PROPERTY); releaseVersion = readPropertyValue(props, RELEASE_VERSION_PROPERTY); - buildVersion = readPropertyValue(props, BUILD_VERSION_PROPERTY); + buildVersion = readPropertyValue(props, BUILD_VERSION_PROPERTY); } } catch (IOException e) @@ -81,26 +115,56 @@ public class QpidProperties } } + /** + * Gets the product name. + * + * @return The product name. + */ public static String getProductName() { return productName; } + /** + * Gets the product version. + * + * @return The product version. + */ public static String getReleaseVersion() { return releaseVersion; } + /** + * Gets the source code revision. + * + * @return The source code revision. + */ public static String getBuildVersion() { return buildVersion; } + /** + * Extracts all of the version information as a printable string. + * + * @return All of the version information as a printable string. + */ public static String getVersionString() { return getProductName() + " - " + getReleaseVersion() + " build: " + getBuildVersion(); } + /** + * Helper method to extract a named property from properties. + * + * @param props The properties. + * @param propertyName The named property to extract. + * + * @return The extracted property or a default value if the properties do not contain the named property. + * + * @todo A bit pointless. + */ private static String readPropertyValue(Properties props, String propertyName) { String retVal = (String) props.get(propertyName); @@ -108,9 +172,16 @@ public class QpidProperties { retVal = DEFAULT; } + return retVal; } + /** + * Prints the versioning information to the console. This is extremely usefull for identifying Qpid code in the + * wild, where the origination of the code has been forgotten. + * + * @param args Does not require any arguments. + */ public static void main(String[] args) { System.out.println(getVersionString()); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/configuration/Configured.java b/qpid/java/common/src/main/java/org/apache/qpid/configuration/Configured.java index 7d2e7d3a5d..22903888fe 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/configuration/Configured.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/configuration/Configured.java @@ -7,9 +7,9 @@ * 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 @@ -26,7 +26,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Marks a field as being "configured" externally. + * Marks a field as having a "configured" value injected into it by a configurator. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) diff --git a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java index 022e7b8a76..76225778e3 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java @@ -24,7 +24,16 @@ import org.apache.qpid.AMQException; import org.apache.qpid.protocol.AMQConstant; /** - * Indicates an error parsing a property expansion. + * Indicates a failure to parse a property expansion. See {@link PropertyUtils} for the code that does property + * expansions. + * + *

        + *
        CRC Card
        Responsibilities Collaboration + *
        Represent failure to expand a property name into a value. + *
        + * + * @todo AMQException is to be reserved for protocol related conditions. This exception does not have a status code, so + * don't inherit from AMQException. */ public class PropertyException extends AMQException { @@ -33,6 +42,7 @@ public class PropertyException extends AMQException super(message); } + /* public PropertyException(String msg, Throwable t) { super(msg, t); @@ -47,4 +57,5 @@ public class PropertyException extends AMQException { super(errorCode, msg); } + */ } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java index 37d8af2501..b3c310d23c 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java @@ -7,9 +7,9 @@ * 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 @@ -24,24 +24,35 @@ import java.util.ArrayList; import java.util.Iterator; /** - * Based on code in Apache Ant, this utility class handles property expansion. This - * is most useful in config files and so on. + * PropertyUtils provides helper methods for dealing with Java properties. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Expand system properties into strings with named expansions. + *
        + * + * @todo Make the lookup method generic by passing in the properties to use for the expansion, rather than hard coding + * as system properties. The expansion code has greater potential for re-use that way. + * + * @todo Some more property related code could be added to this utils class, which might more appropriately reside under + * org.apache.qpid.util. For example standardised code to load properties from a resource name, currently found in + * QpidProperties and possibly other places could be moved here. */ public class PropertyUtils { /** - * Replaces ${xxx} style constructions in the given value - * with the string value of the corresponding data types. Replaces only system - * properties + * Given a string that contains substrings of the form ${xxx}, looks up the valuea of 'xxx' as a + * system properties and substitutes tham back into the original string, to provide a property value expanded + * string. * - * @param value The string to be scanned for property references. - * May be null, in which case this + * @param value The string to be scanned for property references. May be null, in which case this * method returns immediately with no effect. - * @return the original string with the properties replaced, or - * null if the original string is null. - * @throws PropertyException if the string contains an opening - * ${ without a closing - * } + * + * @return The original string with the properties replaced, or null if the original string is + * null. + * + * @throws PropertyException If the string contains an opening ${ without a balancing }, + * or if the property to expand does not exist as a system property. */ public static String replaceProperties(String value) throws PropertyException { @@ -69,11 +80,12 @@ public class PropertyUtils if (replacement == null) { - throw new PropertyException("Property ${" + propertyName + - "} has not been set"); + throw new PropertyException("Property ${" + propertyName + "} has not been set"); } + fragment = replacement; } + sb.append(fragment); } @@ -81,32 +93,30 @@ public class PropertyUtils } /** - * Default parsing method. Parses the supplied value for properties which are specified - * using ${foo} syntax. $X is left as is, and $$ specifies a single $. - * @param value the property string to parse - * @param fragments is populated with the string fragments. A null means "insert a - * property value here. The number of nulls in the list when populated is equal to the - * size of the propertyRefs list - * @param propertyRefs populated with the property names to be added into the final - * String. + * Parses the supplied value for properties which are specified using ${foo} syntax. $X is left as is, and $$ + * specifies a single $. + * + * @param value The property string to parse. + * @param fragments Is populated with the string fragments. A null means "insert a property value here. The number + * of nulls in the list when populated is equal to the size of the propertyRefs list. + * @param propertyRefs Populated with the property names to be added into the final string. */ - private static void parsePropertyString(String value, ArrayList fragments, - ArrayList propertyRefs) - throws PropertyException + private static void parsePropertyString(String value, ArrayList fragments, ArrayList propertyRefs) + throws PropertyException { int prev = 0; int pos; - //search for the next instance of $ from the 'prev' position + // search for the next instance of $ from the 'prev' position while ((pos = value.indexOf("$", prev)) >= 0) { - //if there was any text before this, add it as a fragment + // if there was any text before this, add it as a fragment if (pos > 0) { fragments.add(value.substring(prev, pos)); } - //if we are at the end of the string, we tack on a $ - //then move past it + // if we are at the end of the string, we tack on a $ + // then move past it if (pos == (value.length() - 1)) { fragments.add("$"); @@ -114,8 +124,8 @@ public class PropertyUtils } else if (value.charAt(pos + 1) != '{') { - //peek ahead to see if the next char is a property or not - //not a property: insert the char as a literal + // peek ahead to see if the next char is a property or not + // not a property: insert the char as a literal if (value.charAt(pos + 1) == '$') { // two $ map to one $ @@ -135,22 +145,20 @@ public class PropertyUtils int endName = value.indexOf('}', pos); if (endName < 0) { - throw new PropertyException("Syntax error in property: " + - value); + throw new PropertyException("Syntax error in property: " + value); } + String propertyName = value.substring(pos + 2, endName); fragments.add(null); propertyRefs.add(propertyName); prev = endName + 1; } } - //no more $ signs found - //if there is any tail to the file, append it + // no more $ signs found + // if there is any tail to the file, append it if (prev < value.length()) { fragments.add(value.substring(prev)); } } - - } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java b/qpid/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java index 9bb03c5df6..123901b577 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java @@ -7,9 +7,9 @@ * 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 @@ -22,25 +22,44 @@ package org.apache.qpid.exchange; import org.apache.qpid.framing.AMQShortString; +/** + * Defines the names of the standard AMQP exchanges that every AMQP broker should provide. These exchange names + * and type are given in the specification. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Defines the standard AMQP exchange names. + *
        Defines the standard AMQP exchange types. + *
        + * + * @todo A type safe enum, might be more appropriate for the exchange types. + */ public class ExchangeDefaults { - public final static AMQShortString DEFAULT_EXCHANGE_NAME = new AMQShortString("<>"); - - public final static AMQShortString TOPIC_EXCHANGE_NAME = new AMQShortString("amq.topic"); - - public final static AMQShortString TOPIC_EXCHANGE_CLASS = new AMQShortString("topic"); + /** The default direct exchange, which is a special internal exchange that cannot be explicitly bound to. */ + public static final AMQShortString DEFAULT_EXCHANGE_NAME = new AMQShortString("<>"); - public final static AMQShortString DIRECT_EXCHANGE_NAME = new AMQShortString("amq.direct"); + /** The pre-defined topic exchange, the broker SHOULD provide this. */ + public static final AMQShortString TOPIC_EXCHANGE_NAME = new AMQShortString("amq.topic"); - public final static AMQShortString DIRECT_EXCHANGE_CLASS = new AMQShortString("direct"); + /** Defines the identifying type name of topic exchanges. */ + public static final AMQShortString TOPIC_EXCHANGE_CLASS = new AMQShortString("topic"); - public final static AMQShortString HEADERS_EXCHANGE_NAME = new AMQShortString("amq.match"); + /** The pre-defined direct exchange, the broker MUST provide this. */ + public static final AMQShortString DIRECT_EXCHANGE_NAME = new AMQShortString("amq.direct"); - public final static AMQShortString HEADERS_EXCHANGE_CLASS = new AMQShortString("headers"); + /** Defines the identifying type name of direct exchanges. */ + public static final AMQShortString DIRECT_EXCHANGE_CLASS = new AMQShortString("direct"); - public final static AMQShortString FANOUT_EXCHANGE_NAME = new AMQShortString("amq.fanout"); + /** The pre-defined headers exchange, the specification does not say this needs to be provided. */ + public static final AMQShortString HEADERS_EXCHANGE_NAME = new AMQShortString("amq.match"); - public final static AMQShortString FANOUT_EXCHANGE_CLASS = new AMQShortString("fanout"); + /** Defines the identifying type name of headers exchanges. */ + public static final AMQShortString HEADERS_EXCHANGE_CLASS = new AMQShortString("headers"); + /** The pre-defined fanout exchange, the boker MUST provide this. */ + public static final AMQShortString FANOUT_EXCHANGE_NAME = new AMQShortString("amq.fanout"); + /** Defines the identifying type name of fanout exchanges. */ + public static final AMQShortString FANOUT_EXCHANGE_CLASS = new AMQShortString("fanout"); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/Event.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/Event.java index 7300ec8c3f..5996cbf89c 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/Event.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/Event.java @@ -7,9 +7,9 @@ * 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 @@ -23,18 +23,51 @@ package org.apache.qpid.pool; import org.apache.mina.common.IoFilter; import org.apache.mina.common.IoSession; - -abstract public class Event +/** + * An Event is a continuation, which is used to break a Mina filter chain and save the current point in the chain + * for later processing. It is an abstract class, with different implementations for continuations of different kinds + * of Mina events. + * + *

        These continuations are typically batched by {@link Job} for processing by a worker thread pool. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Process a continuation in the context of a Mina session. + *
        + * + * @todo Pull up _nextFilter and getNextFilter into Event, as all events use it. Inner classes need to be non-static + * to use instance variables in the parent. Consequently they need to be non-inner to be instantiable outside of + * the context of the outer Event class. The inner class construction used here is preventing common code re-use + * (though not by a huge amount), but makes for an inelegent way of handling inheritance and doesn't seem like + * a justifiable use of inner classes. Move the inner classes out into their own files. + * + * @todo Could make Event implement Runnable, FutureTask, or a custom Continuation interface, to clarify its status as + * a continuation. Job is also a continuation, as is the job completion handler. Or, as Event is totally abstract, + * it is really an interface, so could just drop it and use the continuation interface instead. + */ +public abstract class Event { - + /** + * Creates a continuation. + */ public Event() - { - } - - - abstract public void process(IoSession session); - - + { } + + /** + * Processes the continuation in the context of a Mina session. + * + * @param session The Mina session. + */ + public abstract void process(IoSession session); + + /** + * A continuation ({@link Event}) that takes a Mina messageReceived event, and passes it to a NextFilter. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Pass a Mina messageReceived event to a NextFilter. {@link IoFilter.NextFilter}, {@link IoSession} + *
        + */ public static final class ReceivedEvent extends Event { private final Object _data; @@ -59,7 +92,15 @@ abstract public class Event } } - + /** + * A continuation ({@link Event}) that takes a Mina filterWrite event, and passes it to a NextFilter. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Pass a Mina filterWrite event to a NextFilter. + * {@link IoFilter.NextFilter}, {@link IoFilter.WriteRequest}, {@link IoSession} + *
        + */ public static final class WriteEvent extends Event { private final IoFilter.WriteRequest _data; @@ -72,7 +113,6 @@ abstract public class Event _data = data; } - public void process(IoSession session) { _nextFilter.filterWrite(session, _data); @@ -84,8 +124,14 @@ abstract public class Event } } - - + /** + * A continuation ({@link Event}) that takes a Mina sessionClosed event, and passes it to a NextFilter. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Pass a Mina sessionClosed event to a NextFilter. {@link IoFilter.NextFilter}, {@link IoSession} + *
        + */ public static final class CloseEvent extends Event { private final IoFilter.NextFilter _nextFilter; @@ -96,7 +142,6 @@ abstract public class Event _nextFilter = nextFilter; } - public void process(IoSession session) { _nextFilter.sessionClosed(session); @@ -107,5 +152,4 @@ abstract public class Event return _nextFilter; } } - } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java index 1dafdaf4fd..ba3c5d03fa 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/Job.java @@ -7,9 +7,9 @@ * 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 @@ -26,48 +26,77 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.mina.common.IoSession; /** - * Holds events for a session that will be processed asynchronously by - * the thread pool in PoolingFilter. + * A Job is a continuation that batches together other continuations, specifically {@link Event}s, into one continuation. + * The {@link Event}s themselves provide methods to process themselves, so processing a job simply consists of sequentially + * processing all of its aggregated events. + * + * The constructor accepts a maximum number of events for the job, and only runs up to that maximum number when + * processing the job, but the add method does not enforce this maximum. In other words, not all the enqueued events + * may be processed in each run of the job, several runs may be required to clear the queue. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Aggregate many coninuations together into a single continuation. + *
        Sequentially process aggregated continuations. {@link Event} + *
        Provide running and completion status of the aggregate continuation. + *
        Execute a terminal continuation upon job completion. {@link JobCompletionHandler} + *
        + * + * @todo Could make Job implement Runnable, FutureTask, or a custom Continuation interface, to clarify its status as a + * continuation. Job is a continuation that aggregates other continuations and as such is a usefull re-usable + * piece of code. There may be other palces than the mina filter chain where continuation batching is used within + * qpid, so abstracting this out could provide a usefull building block. This also opens the way to different + * kinds of job with a common interface, e.g. parallel or sequential jobs etc. + * + * @todo For better re-usability could make the completion handler optional. Only run it when one is set. */ public class Job implements Runnable { + /** The maximum number of events to process per run of the job. More events than this may be queued in the job. */ private final int _maxEvents; + + /** The Mina session. */ private final IoSession _session; + + /** Holds the queue of events that make up the job. */ private final java.util.Queue _eventQueue = new ConcurrentLinkedQueue(); + + /** Holds a status flag, that indicates when the job is actively running. */ private final AtomicBoolean _active = new AtomicBoolean(); - //private final AtomicInteger _refCount = new AtomicInteger(); + + /** Holds the completion continuation, called upon completion of a run of the job. */ private final JobCompletionHandler _completionHandler; + /** + * Creates a new job that aggregates many continuations together. + * + * @param session The Mina session. + * @param completionHandler The per job run, terminal continuation. + * @param maxEvents The maximum number of aggregated continuations to process per run of the job. + */ Job(IoSession session, JobCompletionHandler completionHandler, int maxEvents) { _session = session; _completionHandler = completionHandler; _maxEvents = maxEvents; } -// -// void acquire() -// { -// _refCount.incrementAndGet(); -// } -// -// void release() -// { -// _refCount.decrementAndGet(); -// } -// -// boolean isReferenced() -// { -// return _refCount.get() > 0; -// } + /** + * Enqueus a continuation for sequential processing by this job. + * + * @param evt The continuation to enqueue. + */ void add(Event evt) { _eventQueue.add(evt); } + /** + * Sequentially processes, up to the maximum number per job, the aggregated continuations in enqueued in this job. + */ void processAll() { - //limit the number of events processed in one run + // limit the number of events processed in one run for (int i = 0; i < _maxEvents; i++) { Event e = _eventQueue.poll(); @@ -82,21 +111,37 @@ public class Job implements Runnable } } - boolean isComplete() + /** + * Tests if there are no more enqueued continuations to process. + * + * @return true if there are no enqueued continuations in this job, false otherwise. + */ + public boolean isComplete() { return _eventQueue.peek() == null; } - boolean activate() + /** + * Marks this job as active if it is inactive. This method is thread safe. + * + * @return true if this job was inactive and has now been marked as active, false otherwise. + */ + public boolean activate() { return _active.compareAndSet(false, true); } - void deactivate() + /** + * Marks this job as inactive. This method is thread safe. + */ + public void deactivate() { _active.set(false); } + /** + * Processes a batch of aggregated continuations, marks this job as inactive and call the terminal continuation. + */ public void run() { processAll(); @@ -104,7 +149,12 @@ public class Job implements Runnable _completionHandler.completed(_session, this); } - + /** + * Another interface for a continuation. + * + * @todo Get rid of this interface as there are other interfaces that could be used instead, such as FutureTask, + * Runnable or a custom Continuation interface. + */ static interface JobCompletionHandler { public void completed(IoSession session, Job job); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java index c9c96925cb..90c09ea99e 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java @@ -31,22 +31,131 @@ import org.apache.mina.common.IoSession; import org.apache.qpid.pool.Event.CloseEvent; -public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionHandler +/** + * PoolingFilter, is a no-op pass through filter that hands all events down the Mina filter chain by default. As it + * adds no behaviour by default to the filter chain, it is abstract. + * + *

        PoolingFilter provides a capability, available to sub-classes, to handle events in the chain asynchronously, by + * adding them to a job. If a job is not active, adding an event to it activates it. If it is active, the event is + * added to the job, which will run to completion and eventually process the event. The queue on the job itself acts as + * a buffer between stages of the pipeline. + * + *

        There are two convenience methods, {@link #createAynschReadPoolingFilter} and + * {@link #createAynschWritePoolingFilter}, for obtaining pooling filters that handle 'messageReceived' and + * 'filterWrite' events, making it possible to process these event streams seperately. + * + *

        Pooling filters have a name, in order to distinguish different filter types. They set up a {@link Job} on the + * Mina session they are working with, and store it in the session against their identifying name. This allows different + * filters with different names to be set up on the same filter chain, on the same Mina session, that batch their + * workloads in different jobs. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Implement default, pass through filter. + *
        Create pooling filters and a specific thread pool. {@link ReferenceCountingExecutorService} + *
        Provide the ability to batch Mina events for asynchronous processing. {@link Job}, {@link Event} + *
        Provide a terminal continuation to keep jobs running till empty. + * {@link Job}, {@link Job.JobCompletionHandler} + *
        + * + * @todo This seems a bit bizarre. ReadWriteThreadModel creates seperate pooling filters for read and write events. + * The pooling filters themselves batch read and write events into jobs, but hand these jobs to a common thread + * pool for execution. So the same thread pool ends up handling read and write events, albeit with many threads + * so there is concurrency. But why go to the trouble of seperating out the read and write events in that case? + * Why not just batch them into jobs together? Perhaps its so that seperate thread pools could be used for these + * stages. + * + * @todo Why set an event limit of 10 on the Job? This also seems bizarre, as the job can have more than 10 events in + * it. Its just that it runs them 10 at a time, but the completion hander here checks if there are more to run + * and trips off another batch of 10 until they are all done. Why not just have a straight forward + * consumer/producer queue scenario without the batches of 10? + * + * @todo The static helper methods are pointless. Could just call new. + */ +public abstract class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionHandler { + /** Used for debugging purposes. */ private static final Logger _logger = Logger.getLogger(PoolingFilter.class); + /** Holds a mapping from Mina sessions to batched jobs for execution. */ private final ConcurrentMap _jobs = new ConcurrentHashMap(); + + /** Holds the managed reference to obtain the executor for the batched jobs. */ private final ReferenceCountingExecutorService _poolReference; + /** Used to hold a name for identifying differeny pooling filter types. */ private final String _name; + + /** Defines the maximum number of events that will be batched into a single job. */ private final int _maxEvents = Integer.getInteger("amqj.server.read_write_pool.max_events", 10); + /** + * Creates a named pooling filter, on the specified shared thread pool. + * + * @param refCountingPool The thread pool reference. + * @param name The identifying name of the filter type. + */ public PoolingFilter(ReferenceCountingExecutorService refCountingPool, String name) { _poolReference = refCountingPool; _name = name; } + /** + * Helper method to get an instance of a pooling filter that handles read events asynchronously. + * + * @param refCountingPool A managed reference to the thread pool. + * @param name The filter types identifying name. + * + * @return A pooling filter for asynchronous read events. + */ + public static PoolingFilter createAynschReadPoolingFilter(ReferenceCountingExecutorService refCountingPool, String name) + { + return new AsynchReadPoolingFilter(refCountingPool, name); + } + + /** + * Helper method to get an instance of a pooling filter that handles write events asynchronously. + * + * @param refCountingPool A managed reference to the thread pool. + * @param name The filter types identifying name. + * + * @return A pooling filter for asynchronous write events. + */ + public static PoolingFilter createAynschWritePoolingFilter(ReferenceCountingExecutorService refCountingPool, String name) + { + return new AsynchWritePoolingFilter(refCountingPool, name); + } + + /** + * Called by Mina to initialize this filter. Takes a reference to the thread pool. + */ + public void init() + { + _logger.info("Init called on PoolingFilter " + toString()); + + // Called when the filter is initialised in the chain. If the reference count is + // zero this acquire will initialise the pool. + _poolReference.acquireExecutorService(); + } + + /** + * Called by Mina to clean up this filter. Releases the reference to the thread pool. + */ + public void destroy() + { + _logger.info("Destroy called on PoolingFilter " + toString()); + + // When the reference count gets to zero we release the executor service. + _poolReference.releaseExecutorService(); + } + + /** + * Adds an {@link Event} to a {@link Job}, triggering the execution of the job if it is not already running. + * + * @param session The Mina session to work in. + * @param event The event to hand off asynchronously. + */ void fireAsynchEvent(IoSession session, Event event) { Job job = getJobForSession(session); @@ -62,31 +171,50 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH } + /** + * Creates a Job on the Mina session, identified by this filters name, in which this filter places asynchronously + * handled events. + * + * @param session The Mina session. + */ public void createNewJobForSession(IoSession session) { Job job = new Job(session, this, _maxEvents); session.setAttribute(_name, job); } + /** + * Retrieves this filters Job, by this filters name, from the Mina session. + * + * @param session The Mina session. + * + * @return The Job for this filter to place asynchronous events into. + */ private Job getJobForSession(IoSession session) { return (Job) session.getAttribute(_name); } - private Job createJobForSession(IoSession session) + /*private Job createJobForSession(IoSession session) { return addJobForSession(session, new Job(session, this, _maxEvents)); - } + }*/ - private Job addJobForSession(IoSession session, Job job) + /*private Job addJobForSession(IoSession session, Job job) { // atomic so ensures all threads agree on the same job Job existing = _jobs.putIfAbsent(session, job); return (existing == null) ? job : existing; - } - - // Job.JobCompletionHandler + }*/ + + /** + * Implements a terminal continuation for the {@link Job} for this filter. Whenever the Job completes its processing + * of a batch of events this is called. This method simply re-activates the job, if it has more events to process. + * + * @param session The Mina session to work in. + * @param job The job that completed. + */ public void completed(IoSession session, Job job) { // if (job.isComplete()) @@ -109,129 +237,228 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH } } - // IoFilter methods that are processed by threads on the pool - + /** + * No-op pass through filter to the next filter in the chain. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + * + * @throws Exception This method does not throw any exceptions, but has Exception in its signature to allow + * overriding sub-classes the ability to. + */ public void sessionOpened(final NextFilter nextFilter, final IoSession session) throws Exception { nextFilter.sessionOpened(session); } + /** + * No-op pass through filter to the next filter in the chain. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + * + * @throws Exception This method does not throw any exceptions, but has Exception in its signature to allow + * overriding sub-classes the ability to. + */ public void sessionClosed(final NextFilter nextFilter, final IoSession session) throws Exception { nextFilter.sessionClosed(session); } + /** + * No-op pass through filter to the next filter in the chain. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + * @param status The session idle status. + * + * @throws Exception This method does not throw any exceptions, but has Exception in its signature to allow + * overriding sub-classes the ability to. + */ public void sessionIdle(final NextFilter nextFilter, final IoSession session, final IdleStatus status) throws Exception { nextFilter.sessionIdle(session, status); } + /** + * No-op pass through filter to the next filter in the chain. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + * @param cause The underlying exception. + * + * @throws Exception This method does not throw any exceptions, but has Exception in its signature to allow + * overriding sub-classes the ability to. + */ public void exceptionCaught(final NextFilter nextFilter, final IoSession session, final Throwable cause) throws Exception { nextFilter.exceptionCaught(session, cause); } + /** + * No-op pass through filter to the next filter in the chain. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + * @param message The message received. + * + * @throws Exception This method does not throw any exceptions, but has Exception in its signature to allow + * overriding sub-classes the ability to. + */ public void messageReceived(final NextFilter nextFilter, final IoSession session, final Object message) throws Exception { nextFilter.messageReceived(session, message); } + /** + * No-op pass through filter to the next filter in the chain. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + * @param message The message sent. + * + * @throws Exception This method does not throw any exceptions, but has Exception in its signature to allow + * overriding sub-classes the ability to. + */ public void messageSent(final NextFilter nextFilter, final IoSession session, final Object message) throws Exception { nextFilter.messageSent(session, message); } + /** + * No-op pass through filter to the next filter in the chain. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + * @param writeRequest The write request event. + * + * @throws Exception This method does not throw any exceptions, but has Exception in its signature to allow + * overriding sub-classes the ability to. + */ public void filterWrite(final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest) throws Exception { nextFilter.filterWrite(session, writeRequest); } - // IoFilter methods that are processed on current thread (NOT on pooled thread) - + /** + * No-op pass through filter to the next filter in the chain. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + * + * @throws Exception This method does not throw any exceptions, but has Exception in its signature to allow + * overriding sub-classes the ability to. + */ public void filterClose(NextFilter nextFilter, IoSession session) throws Exception { nextFilter.filterClose(session); } - public void sessionCreated(NextFilter nextFilter, IoSession session) + /** + * No-op pass through filter to the next filter in the chain. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + * + * @throws Exception This method does not throw any exceptions, but has Exception in its signature to allow + * overriding sub-classes the ability to. + */ + public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception { nextFilter.sessionCreated(session); } + /** + * Prints the filter types identifying name to a string, mainly for debugging purposes. + * + * @return The filter types identifying name. + */ public String toString() { return _name; } - // LifeCycle methods - - public void init() - { - _logger.info("Init called on PoolingFilter " + toString()); - // called when the filter is initialised in the chain. If the reference count is - // zero this acquire will initialise the pool - _poolReference.acquireExecutorService(); - } - - public void destroy() - { - _logger.info("Destroy called on PoolingFilter " + toString()); - // when the reference count gets to zero we release the executor service - _poolReference.releaseExecutorService(); - } - + /** + * AsynchReadPoolingFilter is a pooling filter that handles 'messageReceived' and 'sessionClosed' events + * asynchronously. + */ public static class AsynchReadPoolingFilter extends PoolingFilter { - + /** + * Creates a pooling filter that handles read events asynchronously. + * + * @param refCountingPool A managed reference to the thread pool. + * @param name The filter types identifying name. + */ public AsynchReadPoolingFilter(ReferenceCountingExecutorService refCountingPool, String name) { super(refCountingPool, name); } - public void messageReceived(final NextFilter nextFilter, final IoSession session, final Object message) - throws Exception + /** + * Hands off this event for asynchronous execution. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + * @param message The message received. + */ + public void messageReceived(NextFilter nextFilter, final IoSession session, Object message) { fireAsynchEvent(session, new Event.ReceivedEvent(nextFilter, message)); } - public void sessionClosed(final NextFilter nextFilter, final IoSession session) throws Exception + /** + * Hands off this event for asynchronous execution. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + */ + public void sessionClosed(final NextFilter nextFilter, final IoSession session) { fireAsynchEvent(session, new CloseEvent(nextFilter)); } - } + /** + * AsynchWritePoolingFilter is a pooling filter that handles 'filterWrite' and 'sessionClosed' events + * asynchronously. + */ public static class AsynchWritePoolingFilter extends PoolingFilter { - + /** + * Creates a pooling filter that handles write events asynchronously. + * + * @param refCountingPool A managed reference to the thread pool. + * @param name The filter types identifying name. + */ public AsynchWritePoolingFilter(ReferenceCountingExecutorService refCountingPool, String name) { super(refCountingPool, name); } + /** + * Hands off this event for asynchronous execution. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + * @param writeRequest The write request event. + */ public void filterWrite(final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest) - throws Exception { fireAsynchEvent(session, new Event.WriteEvent(nextFilter, writeRequest)); } - public void sessionClosed(final NextFilter nextFilter, final IoSession session) throws Exception + /** + * Hands off this event for asynchronous execution. + * + * @param nextFilter The next filter in the chain. + * @param session The Mina session. + */ + public void sessionClosed(final NextFilter nextFilter, final IoSession session) { fireAsynchEvent(session, new CloseEvent(nextFilter)); } - - } - - public static PoolingFilter createAynschReadPoolingFilter(ReferenceCountingExecutorService refCountingPool, String name) - { - return new AsynchReadPoolingFilter(refCountingPool, name); - } - - public static PoolingFilter createAynschWritePoolingFilter(ReferenceCountingExecutorService refCountingPool, String name) - { - return new AsynchWritePoolingFilter(refCountingPool, name); } - } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java index 278a569715..8cea70e597 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java @@ -7,9 +7,9 @@ * 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 @@ -24,14 +24,34 @@ import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.ThreadModel; import org.apache.mina.filter.ReferenceCountingIoFilter; +/** + * ReadWriteThreadModel is a Mina i/o filter chain factory, which creates a filter chain with seperate filters to + * handle read and write events. The seperate filters are {@link PoolingFilter}s, which have thread pools to handle + * these events. The effect of this is that reading and writing may happen concurrently. + * + *

        Socket i/o will only happen with concurrent reads and writes if Mina has seperate selector threads for each. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Create a filter chain with seperate read and write thread pools for read/write Mina events. + * {@link PoolingFilter} + *
        + */ public class ReadWriteThreadModel implements ThreadModel { - + /** Holds the singleton instance of this factory. */ private static final ReadWriteThreadModel _instance = new ReadWriteThreadModel(); + /** Holds the thread pooling filter for reads. */ private final PoolingFilter _asynchronousReadFilter; + + /** Holds the thread pooloing filter for writes. */ private final PoolingFilter _asynchronousWriteFilter; + /** + * Creates a new factory for concurrent i/o, thread pooling filter chain construction. This is private, so that + * only a singleton instance of the factory is ever created. + */ private ReadWriteThreadModel() { final ReferenceCountingExecutorService executor = ReferenceCountingExecutorService.getInstance(); @@ -39,25 +59,44 @@ public class ReadWriteThreadModel implements ThreadModel _asynchronousWriteFilter = PoolingFilter.createAynschWritePoolingFilter(executor, "AsynchronousWriteFilter"); } + /** + * Gets the singleton instance of this filter chain factory. + * + * @return The singleton instance of this filter chain factory. + */ + public static ReadWriteThreadModel getInstance() + { + return _instance; + } + + /** + * Gets the read filter. + * + * @return The read filter. + */ public PoolingFilter getAsynchronousReadFilter() { return _asynchronousReadFilter; } + /** + * Gets the write filter. + * + * @return The write filter. + */ public PoolingFilter getAsynchronousWriteFilter() { return _asynchronousWriteFilter; } - public void buildFilterChain(IoFilterChain chain) throws Exception + /** + * Adds the concurrent read and write filters to a filter chain. + * + * @param chain The Mina filter chain to add to. + */ + public void buildFilterChain(IoFilterChain chain) { - chain.addFirst("AsynchronousReadFilter", new ReferenceCountingIoFilter(_asynchronousReadFilter)); chain.addLast("AsynchronousWriteFilter", new ReferenceCountingIoFilter(_asynchronousWriteFilter)); } - - public static ReadWriteThreadModel getInstance() - { - return _instance; - } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/ReferenceCountingExecutorService.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/ReferenceCountingExecutorService.java index 637464f247..84c9e1f465 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/ReferenceCountingExecutorService.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/ReferenceCountingExecutorService.java @@ -7,9 +7,9 @@ * 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 @@ -24,44 +24,87 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** - * We share the executor service among several PoolingFilters. This class reference counts - * how many filter chains are using the executor service and destroys the service, thus - * freeing up its threads, when the count reaches zero. It recreates the service when - * the count is incremented. + * ReferenceCountingExecutorService wraps an ExecutorService in order to provide shared reference to it. It counts + * the references taken, instantiating the service on the first reference, and shutting it down when the last + * reference is released. + * + *

        It is important to ensure that an executor service is correctly shut down as failing to do so prevents the JVM + * from terminating due to the existence of non-daemon threads. + * + *

        null if none has been instantiated yet. */ public ExecutorService getPool() { diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java b/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java index 165c912422..61955160be 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java @@ -36,7 +36,7 @@ import java.util.regex.*; * that they take a default value when not set. Options may be mandatory in wich case it is an error not to specify * them on the command line. Flags are never mandatory because they are implicitly set to false when not specified. * - *

        Some examples command line are: + *

        Some example command lines are: * *

          *
        • This one has two options that expect arguments: -- cgit v1.2.1 From d99f53fb5ef7970a63e150af0a22347c42767dd5 Mon Sep 17 00:00:00 2001 From: Rupert Smith Date: Mon, 21 May 2007 11:26:55 +0000 Subject: Merged revisions 540107 via svnmerge from https://svn.apache.org/repos/asf/incubator/qpid/branches/M2 ........ r540107 | rupertlssmith | 2007-05-21 11:57:30 +0100 (Mon, 21 May 2007) | 1 line Documented all exception. ........ git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@540119 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/AMQChannelClosedException.java | 15 +++++++++----- .../java/org/apache/qpid/AMQChannelException.java | 10 +++++++++ .../apache/qpid/AMQConnectionClosedException.java | 15 +++++++++----- .../org/apache/qpid/AMQConnectionException.java | 23 ++++++++++++++------- .../apache/qpid/AMQConnectionFailureException.java | 10 +++++++++ .../org/apache/qpid/AMQDisconnectedException.java | 15 +++++++++----- .../main/java/org/apache/qpid/AMQException.java | 4 ++-- .../apache/qpid/AMQInvalidArgumentException.java | 12 +++++++++-- .../apache/qpid/AMQInvalidRoutingKeyException.java | 8 ++++++++ .../java/org/apache/qpid/AMQTimeoutException.java | 12 +++++++++-- .../org/apache/qpid/AMQUndeliveredException.java | 14 +++++++------ .../org/apache/qpid/AMQUnknownExchangeType.java | 13 ++++++++++++ .../apache/qpid/AMQUnresolvedAddressException.java | 19 ++++++++++++++--- .../qpid/configuration/PropertyException.java | 3 +-- .../qpid/framing/AMQFrameDecodingException.java | 14 ++++++++----- .../qpid/framing/AMQProtocolClassException.java | 24 +++++++++++++++------- .../qpid/framing/AMQProtocolHeaderException.java | 22 ++++++++++++++------ .../qpid/framing/AMQProtocolInstanceException.java | 22 ++++++++++++++------ .../qpid/framing/AMQProtocolVersionException.java | 20 +++++++++++------- .../java/org/apache/qpid/pool/PoolingFilter.java | 8 +++++++- 20 files changed, 212 insertions(+), 71 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelClosedException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelClosedException.java index 272933ca04..251e91c1b9 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelClosedException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelClosedException.java @@ -7,9 +7,9 @@ * 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 @@ -23,7 +23,14 @@ package org.apache.qpid; import org.apache.qpid.protocol.AMQConstant; /** - * AMQ channel closed exception. + * AMQChannelClosedException indicates that an operation cannot be performed becauase a channel has been closed. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents a failed operation on a closed channel. + *
        + * + * @todo Does this duplicate AMQChannelException? */ public class AMQChannelClosedException extends AMQException { @@ -32,5 +39,3 @@ public class AMQChannelClosedException extends AMQException super(errorCode, msg); } } - - diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java index d8c9b287bd..9efd271e4d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java @@ -25,6 +25,16 @@ import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.ChannelCloseBody; import org.apache.qpid.protocol.AMQConstant; +/** + * AMQChannelException indicates that an error that requires the channel to be closed has occurred. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents an error that rquires the channel to be closed. + *
        + * + * @todo Does this duplicate AMQChannelClosedException? + */ public class AMQChannelException extends AMQException { private final int _classId; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java index e0ed16a9f0..931c6cd87a 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java @@ -7,9 +7,9 @@ * 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 @@ -23,7 +23,14 @@ package org.apache.qpid; import org.apache.qpid.protocol.AMQConstant; /** - * AMQ channel closed exception. + * AMQConnectionClosedException indicates that an operation cannot be performed becauase a connection has been closed. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents a failed operation on a closed conneciton. + *
        + * + * @todo Does this duplicate AMQConnectionException? */ public class AMQConnectionClosedException extends AMQException { @@ -32,5 +39,3 @@ public class AMQConnectionClosedException extends AMQException super(errorCode, msg); } } - - diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java index c4f80191a3..7edfa648ed 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java @@ -7,9 +7,9 @@ * 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 @@ -26,6 +26,16 @@ import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.ConnectionCloseBody; import org.apache.qpid.protocol.AMQConstant; +/** + * AMQConnectionException indicates that an error that requires the channel to be closed has occurred. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents an error that rquires the channel to be closed. + *
        + * + * @todo Does this duplicate AMQChannelClosedException? + */ public class AMQConnectionException extends AMQException { private final int _classId; @@ -35,7 +45,8 @@ public class AMQConnectionException extends AMQException private final byte minor; boolean _closeConnetion; - public AMQConnectionException(AMQConstant errorCode, String msg, int classId, int methodId, byte major, byte minor, Throwable t) + public AMQConnectionException(AMQConstant errorCode, String msg, int classId, int methodId, byte major, byte minor, + Throwable t) { super(errorCode, msg, t); _classId = classId; @@ -53,12 +64,10 @@ public class AMQConnectionException extends AMQException this.minor = minor; } - - public AMQFrame getCloseFrame(int channel) { - return ConnectionCloseBody.createAMQFrame(channel, major, minor, _classId, _methodId, getErrorCode().getCode(), new AMQShortString(getMessage())); + return ConnectionCloseBody.createAMQFrame(channel, major, minor, _classId, _methodId, getErrorCode().getCode(), + new AMQShortString(getMessage())); } - } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java index 9513cfc468..72fa2ae984 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java @@ -1,5 +1,15 @@ package org.apache.qpid; +/** + * AMQConnectionFailureException indicates that a connection to a broker could not be formed. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents failure to connect to a broker. + *
        + * + * @todo Not an AMQP exception as no status code. + */ public class AMQConnectionFailureException extends AMQException { public AMQConnectionFailureException(String message) diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQDisconnectedException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQDisconnectedException.java index b142eea73c..e62b2c10a2 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQDisconnectedException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQDisconnectedException.java @@ -7,9 +7,9 @@ * 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 @@ -21,7 +21,14 @@ package org.apache.qpid; /** - * AMQ disconnected exception. + * AMQDisconnectedException indicates that a broker disconnected without failover. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents disconnection without failover by the broker. + *
        + * + * @todo Not an AMQP exception as no status code. */ public class AMQDisconnectedException extends AMQException { @@ -30,5 +37,3 @@ public class AMQDisconnectedException extends AMQException super(msg); } } - - diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java index 2f04a01f53..41599ed880 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java @@ -24,11 +24,11 @@ import org.apache.qpid.protocol.AMQConstant; /** * AMQException forms the root exception of all exceptions relating to the AMQ protocol. It provides space to associate - * an AMQ error code with the exception, which is a numberic value, with a meaning defined by the protocol. + * a required AMQ error code with the exception, which is a numeric value, with a meaning defined by the protocol. * *

        *
        CRC Card
        Responsibilities Collaborations - *
        Represents an exception condition associated with an AMQ protocol error code. + *
        Represents an exception condition associated with an AMQ protocol status code. *
        * * @todo This exception class is also used as a generic exception throughout Qpid code. This usage may not be strictly diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidArgumentException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidArgumentException.java index 9406921d88..278128f924 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidArgumentException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidArgumentException.java @@ -14,14 +14,22 @@ * "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. + * under the License. + * * - * */ package org.apache.qpid; import org.apache.qpid.protocol.AMQConstant; +/** + * AMQInvalidArgumentException indicates that an invalid argument has been passed to an AMQP method. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents an error due to an invalid argument being passed to an AMQP method. + *
        + */ public class AMQInvalidArgumentException extends AMQException { public AMQInvalidArgumentException(String message) diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidRoutingKeyException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidRoutingKeyException.java index caf8f3a572..b5ec9845d6 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidRoutingKeyException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidRoutingKeyException.java @@ -22,6 +22,14 @@ package org.apache.qpid; import org.apache.qpid.protocol.AMQConstant; +/** + * AMQInvalidRoutingKeyException indicates an error with a routing key having an invalid format. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents a format error in a routing key. + *
        + */ public class AMQInvalidRoutingKeyException extends AMQException { public AMQInvalidRoutingKeyException(String message) diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java index f1f973542d..0f8d9c47db 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java @@ -14,14 +14,22 @@ * "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. + * under the License. + * * - * */ package org.apache.qpid; import org.apache.qpid.protocol.AMQConstant; +/** + * AMQTimeoutException indicates that an expected response from a broker took too long. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Indicates that an expected response from a broker took too long. + *
        + */ public class AMQTimeoutException extends AMQException { public AMQTimeoutException(String message) diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQUndeliveredException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQUndeliveredException.java index ad5aff7bb6..03220cc95e 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQUndeliveredException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQUndeliveredException.java @@ -7,9 +7,9 @@ * 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 @@ -23,7 +23,12 @@ package org.apache.qpid; import org.apache.qpid.protocol.AMQConstant; /** - * Generic AMQ exception. + * AMQUndeliveredException indicates that a message, marked immediate or mandatory, could not be delivered. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents failure to delivery a message that must be delivered. + *
        */ public class AMQUndeliveredException extends AMQException { @@ -40,7 +45,4 @@ public class AMQUndeliveredException extends AMQException { return _bounced; } - } - - diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java index ed1d2e8beb..c4aa992a01 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java @@ -1,5 +1,18 @@ package org.apache.qpid; +/** + * AMQUnknownExchangeType represents coding error where unknown exchange type requested from exchange factory. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents unknown exchange type request. + *
        + * + * @todo Not an AMQP exception as no status code. + * + * @todo Represent coding error, where unknown exchange type is requested by passing a string parameter. Use a type safe + * enum for the exchange type, or replace with IllegalArgumentException. Should be runtime. + */ public class AMQUnknownExchangeType extends AMQException { public AMQUnknownExchangeType(String message) diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQUnresolvedAddressException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQUnresolvedAddressException.java index 2201903ded..6cc9c3fe00 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQUnresolvedAddressException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQUnresolvedAddressException.java @@ -7,9 +7,9 @@ * 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 @@ -20,6 +20,19 @@ */ package org.apache.qpid; +/** + * AMQUnresolvedAddressException indicates failure to resolve a socket address. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents failre to resolve a socket address. + *
        + * + * @todo Not an AMQP exception as no status code. + * + * @todo Why replace java.nio.UnresolvedAddressException with this? This is checked, which may explain why, but it + * doesn't wrap the underlying exception. + */ public class AMQUnresolvedAddressException extends AMQException { String _broker; @@ -32,6 +45,6 @@ public class AMQUnresolvedAddressException extends AMQException public String toString() { - return super.toString() + " Broker, \"" + _broker +"\""; + return super.toString() + " Broker, \"" + _broker + "\""; } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java index 76225778e3..1e5cc57fff 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java @@ -32,8 +32,7 @@ import org.apache.qpid.protocol.AMQConstant; *

        Represent failure to expand a property name into a value. *
        * - * @todo AMQException is to be reserved for protocol related conditions. This exception does not have a status code, so - * don't inherit from AMQException. + * @todo Not an AMQP exception as no status code. */ public class PropertyException extends AMQException { diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java index 171da76771..cd5ccf8e04 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java @@ -23,13 +23,17 @@ package org.apache.qpid.framing; import org.apache.qpid.AMQException; import org.apache.qpid.protocol.AMQConstant; +/** + * AMQFrameDecodingException indicates that an AMQP frame cannot be decoded because it does not have the correct + * format as defined by the protocol. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents a format error in a protocol frame. + *
        + */ public class AMQFrameDecodingException extends AMQException { - /*public AMQFrameDecodingException(String message) - { - super(message); - }*/ - public AMQFrameDecodingException(AMQConstant errorCode, String message, Throwable t) { super(errorCode, message, t); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolClassException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolClassException.java index e6acad502f..e48fd2e7f9 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolClassException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolClassException.java @@ -7,9 +7,9 @@ * 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 @@ -20,10 +20,20 @@ */ package org.apache.qpid.framing; +/** + * AMQProtocolInstanceException indicates that the protocol class is incorrect in a header. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represent incorrect protocol class in frame header. + *
        + * + * @todo Not an AMQP exception as no status code. + */ public class AMQProtocolClassException extends AMQProtocolHeaderException { - public AMQProtocolClassException(String message) - { - super(message); - } -} \ No newline at end of file + public AMQProtocolClassException(String message) + { + super(message); + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolHeaderException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolHeaderException.java index 888ed14faf..1ce49aba83 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolHeaderException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolHeaderException.java @@ -7,9 +7,9 @@ * 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 @@ -22,10 +22,20 @@ package org.apache.qpid.framing; import org.apache.qpid.AMQException; +/** + * AMQProtocolHeaderException indicates a format error in an AMQP frame header. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represent format error in frame header. + *
        + * + * @todo Not an AMQP exception as no status code. + */ public class AMQProtocolHeaderException extends AMQException { - public AMQProtocolHeaderException(String message) - { - super(message); - } + public AMQProtocolHeaderException(String message) + { + super(message); + } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolInstanceException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolInstanceException.java index c58979f876..9049eace2a 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolInstanceException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolInstanceException.java @@ -7,9 +7,9 @@ * 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 @@ -20,10 +20,20 @@ */ package org.apache.qpid.framing; +/** + * AMQProtocolInstanceException indicates that the protocol instance is incorrect in a header. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represent incorrect protocol instance in frame header. + *
        + * + * @todo Not an AMQP exception as no status code. + */ public class AMQProtocolInstanceException extends AMQProtocolHeaderException { - public AMQProtocolInstanceException(String message) - { - super(message); - } + public AMQProtocolInstanceException(String message) + { + super(message); + } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolVersionException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolVersionException.java index 7b326a0dc4..9074931617 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolVersionException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolVersionException.java @@ -7,9 +7,9 @@ * 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 @@ -21,13 +21,19 @@ package org.apache.qpid.framing; /** - * Exception that is thrown when the client and server differ on expected protocol version (header) information. + * AMQProtocolInstanceException indicates that the client and server differ on expected protocol version in a header. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represent incorrect protocol version in frame header. + *
        * + * @todo Not an AMQP exception as no status code. */ public class AMQProtocolVersionException extends AMQProtocolHeaderException { - public AMQProtocolVersionException(String message) - { - super(message); - } + public AMQProtocolVersionException(String message) + { + super(message); + } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java index 90c09ea99e..ffc8f1643a 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java @@ -68,7 +68,13 @@ import org.apache.qpid.pool.Event.CloseEvent; * @todo Why set an event limit of 10 on the Job? This also seems bizarre, as the job can have more than 10 events in * it. Its just that it runs them 10 at a time, but the completion hander here checks if there are more to run * and trips off another batch of 10 until they are all done. Why not just have a straight forward - * consumer/producer queue scenario without the batches of 10? + * consumer/producer queue scenario without the batches of 10? So instead of having many jobs with batches of 10 + * in them, just have one queue of events and worker threads taking the next event. There will be coordination + * between worker threads and new events arriving on the job anyway, so the simpler scenario may have the same + * amount of contention. I can see that the batches of 10 is done, so that no job is allowed to hog the worker + * pool for too long. I'm not convinced this fairly complex scheme will actually add anything, and it might be + * better to encapsulate it under a Queue interface anyway, so that different queue implementations can easily + * be substituted in. * * @todo The static helper methods are pointless. Could just call new. */ -- cgit v1.2.1 From eaa113f7b7640bddf8328f3e8cc24ce72fb9b52c Mon Sep 17 00:00:00 2001 From: Rupert Smith Date: Mon, 21 May 2007 15:11:23 +0000 Subject: Refactored exceptions to have single constructors and made room for wrapped causes. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@540165 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/AMQChannelClosedException.java | 4 +- .../java/org/apache/qpid/AMQChannelException.java | 26 ++++++------- .../apache/qpid/AMQConnectionClosedException.java | 4 +- .../org/apache/qpid/AMQConnectionException.java | 20 ++++------ .../apache/qpid/AMQConnectionFailureException.java | 4 +- .../org/apache/qpid/AMQDisconnectedException.java | 4 +- .../main/java/org/apache/qpid/AMQException.java | 43 ++-------------------- .../apache/qpid/AMQInvalidArgumentException.java | 4 +- .../apache/qpid/AMQInvalidRoutingKeyException.java | 4 +- .../java/org/apache/qpid/AMQTimeoutException.java | 4 +- .../org/apache/qpid/AMQUndeliveredException.java | 4 +- .../org/apache/qpid/AMQUnknownExchangeType.java | 4 +- .../apache/qpid/AMQUnresolvedAddressException.java | 4 +- .../qpid/configuration/PropertyException.java | 21 +---------- .../apache/qpid/configuration/PropertyUtils.java | 4 +- .../qpid/framing/AMQFrameDecodingException.java | 4 +- .../org/apache/qpid/framing/AMQMethodBody.java | 4 +- .../qpid/framing/AMQProtocolClassException.java | 4 +- .../qpid/framing/AMQProtocolHeaderException.java | 4 +- .../qpid/framing/AMQProtocolInstanceException.java | 4 +- .../qpid/framing/AMQProtocolVersionException.java | 4 +- .../apache/qpid/framing/ProtocolInitiation.java | 10 ++--- 22 files changed, 62 insertions(+), 126 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelClosedException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelClosedException.java index 251e91c1b9..1b2eabdc86 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelClosedException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelClosedException.java @@ -34,8 +34,8 @@ import org.apache.qpid.protocol.AMQConstant; */ public class AMQChannelClosedException extends AMQException { - public AMQChannelClosedException(AMQConstant errorCode, String msg) + public AMQChannelClosedException(AMQConstant errorCode, String msg, Throwable cause) { - super(errorCode, msg); + super(errorCode, msg, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java index 9efd271e4d..9d8672f433 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQChannelException.java @@ -7,9 +7,9 @@ * 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 @@ -39,22 +39,17 @@ public class AMQChannelException extends AMQException { private final int _classId; private final int _methodId; - /* AMQP version for which exception ocurred */ + + /** AMQP version for which exception ocurred, major code. */ private final byte major; - private final byte minor; - public AMQChannelException(AMQConstant errorCode, String msg, int classId, int methodId, byte major, byte minor, Throwable t) - { - super(errorCode, msg, t); - _classId = classId; - _methodId = methodId; - this.major = major; - this.minor = minor; - } + /** AMQP version for which exception ocurred, minor code. */ + private final byte minor; - public AMQChannelException(AMQConstant errorCode, String msg, int classId, int methodId, byte major, byte minor) + public AMQChannelException(AMQConstant errorCode, String msg, int classId, int methodId, byte major, byte minor, + Throwable cause) { - super(errorCode, msg); + super(errorCode, msg, cause); _classId = classId; _methodId = methodId; this.major = major; @@ -63,6 +58,7 @@ public class AMQChannelException extends AMQException public AMQFrame getCloseFrame(int channel) { - return ChannelCloseBody.createAMQFrame(channel, major, minor, _classId, _methodId, getErrorCode().getCode(), new AMQShortString(getMessage())); + return ChannelCloseBody.createAMQFrame(channel, major, minor, _classId, _methodId, getErrorCode().getCode(), + new AMQShortString(getMessage())); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java index 931c6cd87a..e95e805e9f 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java @@ -34,8 +34,8 @@ import org.apache.qpid.protocol.AMQConstant; */ public class AMQConnectionClosedException extends AMQException { - public AMQConnectionClosedException(AMQConstant errorCode, String msg) + public AMQConnectionClosedException(AMQConstant errorCode, String msg, Throwable cause) { - super(errorCode, msg); + super(errorCode, msg, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java index 7edfa648ed..ba9f69a05c 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java @@ -40,24 +40,19 @@ public class AMQConnectionException extends AMQException { private final int _classId; private final int _methodId; - /* AMQP version for which exception ocurred */ + + /** AMQP version for which exception ocurred, major code. */ private final byte major; + + /** AMQP version for which exception ocurred, minor code. */ private final byte minor; + boolean _closeConnetion; public AMQConnectionException(AMQConstant errorCode, String msg, int classId, int methodId, byte major, byte minor, - Throwable t) + Throwable cause) { - super(errorCode, msg, t); - _classId = classId; - _methodId = methodId; - this.major = major; - this.minor = minor; - } - - public AMQConnectionException(AMQConstant errorCode, String msg, int classId, int methodId, byte major, byte minor) - { - super(errorCode, msg); + super(errorCode, msg, cause); _classId = classId; _methodId = methodId; this.major = major; @@ -69,5 +64,4 @@ public class AMQConnectionException extends AMQException return ConnectionCloseBody.createAMQFrame(channel, major, minor, _classId, _methodId, getErrorCode().getCode(), new AMQShortString(getMessage())); } - } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java index 72fa2ae984..c043a00836 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java @@ -12,8 +12,8 @@ package org.apache.qpid; */ public class AMQConnectionFailureException extends AMQException { - public AMQConnectionFailureException(String message) + public AMQConnectionFailureException(String message, Throwable cause) { - super(message); + super(null, message, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQDisconnectedException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQDisconnectedException.java index e62b2c10a2..5ec5c42ab9 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQDisconnectedException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQDisconnectedException.java @@ -32,8 +32,8 @@ package org.apache.qpid; */ public class AMQDisconnectedException extends AMQException { - public AMQDisconnectedException(String msg) + public AMQDisconnectedException(String msg, Throwable cause) { - super(msg); + super(null, msg, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java index 41599ed880..6cbb98fd86 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQException.java @@ -44,48 +44,11 @@ public class AMQException extends Exception * * @param errorCode The error code. May be null if not to be set. * @param msg The exception message. May be null if not to be set. - * @param t The underlying cause of the exception. May be null if not to be set. + * @param cause The underlying cause of the exception. May be null if not to be set. */ - public AMQException(AMQConstant errorCode, String msg, Throwable t) + public AMQException(AMQConstant errorCode, String msg, Throwable cause) { - super(((msg == null) ? "" : msg) + ((errorCode == null) ? "" : (" [error code " + errorCode + "]")), t); - _errorCode = errorCode; - } - - /** - * @param message - * - * @deprecated Use {@link #AMQException(org.apache.qpid.protocol.AMQConstant, String, Throwable)} instead. - */ - public AMQException(String message) - { - super(message); - // fixme This method needs removed and all AMQExceptions need a valid error code - _errorCode = AMQConstant.getConstant(-1); - } - - /** - * @param msg - * @param t - * - * @deprecated Use {@link #AMQException(org.apache.qpid.protocol.AMQConstant, String, Throwable)} instead. - */ - public AMQException(String msg, Throwable t) - { - super(msg, t); - // fixme This method needs removed and all AMQExceptions need a valid error code - _errorCode = AMQConstant.getConstant(-1); - } - - /** - * @param errorCode - * @param msg - * - * @deprecated Use {@link #AMQException(org.apache.qpid.protocol.AMQConstant, String, Throwable)} instead. - */ - public AMQException(AMQConstant errorCode, String msg) - { - super(msg + " [error code " + errorCode + ']'); + super(((msg == null) ? "" : msg) + ((errorCode == null) ? "" : (" [error code " + errorCode + "]")), cause); _errorCode = errorCode; } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidArgumentException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidArgumentException.java index 278128f924..15c8bea0a4 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidArgumentException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidArgumentException.java @@ -32,8 +32,8 @@ import org.apache.qpid.protocol.AMQConstant; */ public class AMQInvalidArgumentException extends AMQException { - public AMQInvalidArgumentException(String message) + public AMQInvalidArgumentException(String message, Throwable cause) { - super(AMQConstant.INVALID_ARGUMENT, message); + super(AMQConstant.INVALID_ARGUMENT, message, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidRoutingKeyException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidRoutingKeyException.java index b5ec9845d6..c117968a29 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidRoutingKeyException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQInvalidRoutingKeyException.java @@ -32,8 +32,8 @@ import org.apache.qpid.protocol.AMQConstant; */ public class AMQInvalidRoutingKeyException extends AMQException { - public AMQInvalidRoutingKeyException(String message) + public AMQInvalidRoutingKeyException(String message, Throwable cause) { - super(AMQConstant.INVALID_ROUTING_KEY, message); + super(AMQConstant.INVALID_ROUTING_KEY, message, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java index 0f8d9c47db..4ae8282af5 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java @@ -32,8 +32,8 @@ import org.apache.qpid.protocol.AMQConstant; */ public class AMQTimeoutException extends AMQException { - public AMQTimeoutException(String message) + public AMQTimeoutException(String message, Throwable cause) { - super(AMQConstant.REQUEST_TIMEOUT, message); + super(AMQConstant.REQUEST_TIMEOUT, message, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQUndeliveredException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQUndeliveredException.java index 03220cc95e..1502c0efc5 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQUndeliveredException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQUndeliveredException.java @@ -34,9 +34,9 @@ public class AMQUndeliveredException extends AMQException { private Object _bounced; - public AMQUndeliveredException(AMQConstant errorCode, String msg, Object bounced) + public AMQUndeliveredException(AMQConstant errorCode, String msg, Object bounced, Throwable cause) { - super(errorCode, msg); + super(errorCode, msg, cause); _bounced = bounced; } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java index c4aa992a01..f483b9947b 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java @@ -15,8 +15,8 @@ package org.apache.qpid; */ public class AMQUnknownExchangeType extends AMQException { - public AMQUnknownExchangeType(String message) + public AMQUnknownExchangeType(String message, Throwable cause) { - super(message); + super(null, message, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQUnresolvedAddressException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQUnresolvedAddressException.java index 6cc9c3fe00..eee3e6afcf 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQUnresolvedAddressException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQUnresolvedAddressException.java @@ -37,9 +37,9 @@ public class AMQUnresolvedAddressException extends AMQException { String _broker; - public AMQUnresolvedAddressException(String message, String broker) + public AMQUnresolvedAddressException(String message, String broker, Throwable cause) { - super(message); + super(null, message, cause); _broker = broker; } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java index 1e5cc57fff..73a336321c 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyException.java @@ -36,25 +36,8 @@ import org.apache.qpid.protocol.AMQConstant; */ public class PropertyException extends AMQException { - public PropertyException(String message) + public PropertyException(String message, Throwable cause) { - super(message); + super(null, message, cause); } - - /* - public PropertyException(String msg, Throwable t) - { - super(msg, t); - } - - public PropertyException(AMQConstant errorCode, String msg, Throwable t) - { - super(errorCode, msg, t); - } - - public PropertyException(AMQConstant errorCode, String msg) - { - super(errorCode, msg); - } - */ } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java index b3c310d23c..6e2b25fb2c 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java @@ -80,7 +80,7 @@ public class PropertyUtils if (replacement == null) { - throw new PropertyException("Property ${" + propertyName + "} has not been set"); + throw new PropertyException("Property ${" + propertyName + "} has not been set", null); } fragment = replacement; @@ -145,7 +145,7 @@ public class PropertyUtils int endName = value.indexOf('}', pos); if (endName < 0) { - throw new PropertyException("Syntax error in property: " + value); + throw new PropertyException("Syntax error in property: " + value, null); } String propertyName = value.substring(pos + 2, endName); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java index cd5ccf8e04..843b6a1e8c 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQFrameDecodingException.java @@ -34,8 +34,8 @@ import org.apache.qpid.protocol.AMQConstant; */ public class AMQFrameDecodingException extends AMQException { - public AMQFrameDecodingException(AMQConstant errorCode, String message, Throwable t) + public AMQFrameDecodingException(AMQConstant errorCode, String message, Throwable cause) { - super(errorCode, message, t); + super(errorCode, message, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java index 23a1ce367e..0982847aac 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java @@ -111,7 +111,7 @@ public abstract class AMQMethodBody extends AMQBody public AMQChannelException getChannelException(AMQConstant code, String message) { - return new AMQChannelException(code, message, getClazz(), getMethod(), major, minor); + return new AMQChannelException(code, message, getClazz(), getMethod(), major, minor, null); } public AMQChannelException getChannelException(AMQConstant code, String message, Throwable cause) @@ -121,7 +121,7 @@ public abstract class AMQMethodBody extends AMQBody public AMQConnectionException getConnectionException(AMQConstant code, String message) { - return new AMQConnectionException(code, message, getClazz(), getMethod(), major, minor); + return new AMQConnectionException(code, message, getClazz(), getMethod(), major, minor, null); } public AMQConnectionException getConnectionException(AMQConstant code, String message, Throwable cause) diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolClassException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolClassException.java index e48fd2e7f9..ab09c1de6d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolClassException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolClassException.java @@ -32,8 +32,8 @@ package org.apache.qpid.framing; */ public class AMQProtocolClassException extends AMQProtocolHeaderException { - public AMQProtocolClassException(String message) + public AMQProtocolClassException(String message, Throwable cause) { - super(message); + super(message, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolHeaderException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolHeaderException.java index 1ce49aba83..6b819364da 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolHeaderException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolHeaderException.java @@ -34,8 +34,8 @@ import org.apache.qpid.AMQException; */ public class AMQProtocolHeaderException extends AMQException { - public AMQProtocolHeaderException(String message) + public AMQProtocolHeaderException(String message, Throwable cause) { - super(message); + super(null, message, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolInstanceException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolInstanceException.java index 9049eace2a..3165c373a9 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolInstanceException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolInstanceException.java @@ -32,8 +32,8 @@ package org.apache.qpid.framing; */ public class AMQProtocolInstanceException extends AMQProtocolHeaderException { - public AMQProtocolInstanceException(String message) + public AMQProtocolInstanceException(String message, Throwable cause) { - super(message); + super(message, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolVersionException.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolVersionException.java index 9074931617..c9b0973ea6 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolVersionException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQProtocolVersionException.java @@ -32,8 +32,8 @@ package org.apache.qpid.framing; */ public class AMQProtocolVersionException extends AMQProtocolHeaderException { - public AMQProtocolVersionException(String message) + public AMQProtocolVersionException(String message, Throwable cause) { - super(message); + super(message, cause); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java index 8b40fe72eb..4c253b9973 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java @@ -144,7 +144,7 @@ public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQData if(_protocolHeader.length != 4) { - throw new AMQProtocolHeaderException("Protocol header should have exactly four octets"); + throw new AMQProtocolHeaderException("Protocol header should have exactly four octets", null); } for(int i = 0; i < 4; i++) { @@ -152,7 +152,7 @@ public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQData { try { - throw new AMQProtocolHeaderException("Protocol header is not correct: Got " + new String(_protocolHeader,"ISO-8859-1") + " should be: " + new String(AMQP_HEADER, "ISO-8859-1")); + throw new AMQProtocolHeaderException("Protocol header is not correct: Got " + new String(_protocolHeader,"ISO-8859-1") + " should be: " + new String(AMQP_HEADER, "ISO-8859-1"), null); } catch (UnsupportedEncodingException e) { @@ -163,12 +163,12 @@ public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQData if (_protocolClass != CURRENT_PROTOCOL_CLASS) { throw new AMQProtocolClassException("Protocol class " + CURRENT_PROTOCOL_CLASS + " was expected; received " + - _protocolClass); + _protocolClass, null); } if (_protocolInstance != TCP_PROTOCOL_INSTANCE) { throw new AMQProtocolInstanceException("Protocol instance " + TCP_PROTOCOL_INSTANCE + " was expected; received " + - _protocolInstance); + _protocolInstance, null); } ProtocolVersion pv = new ProtocolVersion(_protocolMajor, _protocolMinor); @@ -178,7 +178,7 @@ public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQData { // TODO: add list of available versions in list to msg... throw new AMQProtocolVersionException("Protocol version " + - _protocolMajor + "." + _protocolMinor + " not suppoerted by this version of the Qpid broker."); + _protocolMajor + "." + _protocolMinor + " not suppoerted by this version of the Qpid broker.", null); } } -- cgit v1.2.1 From 729cfb9a6f82124a06ba417e7f768811d5cacb8e Mon Sep 17 00:00:00 2001 From: Rupert Smith Date: Tue, 22 May 2007 11:35:10 +0000 Subject: Added batch synched queue implementation. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@540533 13f79535-47bb-0310-9956-ffa450edef68 --- .../util/concurrent/AlreadyUnblockedException.java | 13 + .../qpid/util/concurrent/BatchSynchQueue.java | 101 +++ .../qpid/util/concurrent/BatchSynchQueueBase.java | 816 +++++++++++++++++++++ .../apache/qpid/util/concurrent/BooleanLatch.java | 107 +++ .../org/apache/qpid/util/concurrent/Capacity.java | 14 + .../apache/qpid/util/concurrent/SynchBuffer.java | 29 + .../qpid/util/concurrent/SynchException.java | 31 + .../apache/qpid/util/concurrent/SynchQueue.java | 27 + .../apache/qpid/util/concurrent/SynchRecord.java | 53 ++ .../org/apache/qpid/util/concurrent/SynchRef.java | 30 + 10 files changed, 1221 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/AlreadyUnblockedException.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueue.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/Capacity.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchBuffer.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchException.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchQueue.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRecord.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRef.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/AlreadyUnblockedException.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/AlreadyUnblockedException.java new file mode 100644 index 0000000000..4acea0e2ec --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/AlreadyUnblockedException.java @@ -0,0 +1,13 @@ +package org.apache.qpid.util.concurrent; + +/** + * Used to signal that a data element and its producer cannot be requeued or sent an error message when using a + * {@link BatchSynchQueue} because the producer has already been unblocked by an unblocking take on the queue. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Signal that an unblocking take has already occurred. + *
        + */ +public class AlreadyUnblockedException extends RuntimeException +{ } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueue.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueue.java new file mode 100644 index 0000000000..cf2abfffb8 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueue.java @@ -0,0 +1,101 @@ +package org.apache.qpid.util.concurrent; + +import java.util.Collection; +import java.util.concurrent.BlockingQueue; + +/** + * BatchSynchQueue is an abstraction of the classic producer/consumer buffer pattern for thread interaction. In this + * pattern threads can deposit data onto a buffer whilst other threads take data from the buffer and perform usefull + * work with it. A BatchSynchQueue adds to this the possibility that producers can be blocked until their data is + * consumed or until a consumer chooses to release the producer some time after consuming the data from the queue. + * + *

        There are a number of possible advantages to using this technique when compared with having the producers + * processing their own data: + * + *

          + *
        • Data may be deposited asynchronously in the buffer allowing the producers to continue running.
        • + *
        • Data may be deposited synchronously in the buffer so that producers wait until their data has been processed + * before being allowed to continue.
        • + *
        • Variable rates of production/consumption can be smoothed over by the buffer as it provides space in memory to + * hold data between production and consumption.
        • + *
        • Consumers may be able to batch data as they consume it leading to more efficient consumption over + * individual data item consumption where latency associated with the consume operation can be ammortized. + * For example, it may be possibly to ammortize the cost of a disk seek over many producers.
        • + *
        • Data from seperate threads can be combined together in the buffer, providing a convenient way of spreading work + * amongst many workers and gathering the results together again.
        • + *
        • Different types of queue can be used to hold the buffer, resulting in different processing orders. For example, + * lifo, fifo, priority heap, etc.
        • + *
        + * + *

        The asynchronous type of producer/consumer buffers is already well supported by the java.util.concurrent package + * (in Java 5) and there is also a synchronous queue implementation available there too. This interface extends the + * blocking queue with some more methods for controlling a synchronous blocking queue. In particular it adds additional + * take methods that can be used to take data from a queue without releasing producers, so that consumers have an + * opportunity to confirm correct processing of the data before producers are released. It also adds a put method with + * exceptions so that consumers can signal exception cases back to producers where there are errors in the data. + * + *

        This type of queue is usefull in situations where consumers can obtain an efficiency gain by batching data + * from many threads but where synchronous handling of that data is neccessary because producers need to know that + * their data has been processed before they continue. For example, sending a bundle of messages together, or writing + * many records to disk at once, may result in improved performance but the originators of the messages or disk records + * need confirmation that their data has really been sent or saved to disk. + * + *

        The consumer can put an element back onto the queue or send an error message to the elements producer using the + * {@link SynchRecord} interface. + * + *

        The {@link #take()}, {@link #drainTo(java.util.Collection)} and + * {@link #drainTo(java.util.Collection, int)} methods from {@link BlockingQueue} should behave as if they + * have been called with unblock set to false. That is they take elements from the queue but leave the producers + * blocked. These methods do not return collections of {@link SynchRecord}s so they do not supply an interface through + * which errors or re-queuings can be applied. If these methods are used then the consumer must succesfully process + * all the records it takes. + * + *

        The {@link #put} method should silently swallow any exceptions that consumers attempt to return to the caller. + * In order to handle exceptions the {@link #tryPut} method must be used. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Handle synchronous puts, with possible exceptions. + *
        Allow consumers to take many records from a queue in a batch. + *
        Allow consumers to decide when to unblock synchronous producers. + *
        + */ +public interface BatchSynchQueue extends BlockingQueue +{ + /** + * Tries a synchronous put into the queue. If a consumer encounters an exception condition whilst processing the + * data that is put, then this is returned to the caller wrapped inside a {@link SynchException}. + * + * @param e The data element to put into the queue. + * + * @throws InterruptedException If the thread is interrupted whilst waiting to write to the queue or whilst waiting + * on its entry in the queue being consumed. + * @throws SynchException If a consumer encounters an error whilst processing the data element. + */ + public void tryPut(E e) throws InterruptedException, SynchException; + + /** + * Takes all available data items from the queue or blocks until some become available. The returned items + * are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their + * producers, where the producers are still blocked. + * + * @param c The collection to drain the data items into. + * @param unblock If set to true the producers for the taken items will be immediately unblocked. + * + * @return A count of the number of elements that were drained from the queue. + */ + public SynchRef drainTo(Collection> c, boolean unblock); + + /** + * Takes up to maxElements available data items from the queue or blocks until some become available. The returned + * items are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their + * producers, where the producers are still blocked. + * + * @param c The collection to drain the data items into. + * @param maxElements The maximum number of elements to drain. + * @param unblock If set to true the producers for the taken items will be immediately unblocked. + * + * @return A count of the number of elements that were drained from the queue. + */ + public SynchRef drainTo(Collection> c, int maxElements, boolean unblock); +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java new file mode 100644 index 0000000000..521c341ca3 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java @@ -0,0 +1,816 @@ +package org.apache.qpid.util.concurrent; + +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; + +import org.apache.log4j.Logger; + +/** + * Synchronous/Asynchronous puts. Asynchronous is easiest, just wait till can write to queue and deposit data. + * Synchronous is harder. Deposit data, but then must wait until deposited element/elements are taken before being + * allowed to unblock and continue. Consumer needs some options here too. Can just get the data from the buffer and + * allow any producers unblocked as a result to continue, or can get data but continue blocking while the data is + * processed before sending a message to do the unblocking. Synch/Asynch mode to be controlled by a switch. + * Unblocking/not unblocking during consumer processing to be controlled by the consumers calls. + * + *

        Implementing sub-classes only need to supply an implementation of a queue to produce a valid concrete + * implementation of this. This queue is only accessed through the methods {@link #insert}, {@link #extract}, + * {@link #getBufferCapacity()}, {@link #peekAtBufferHead()}. An implementation can override these methods to implement + * the buffer other than by a queue, for example, by using an array. + * + *

        Normal queue methods to work asynchronously. + *

        Put, take and drain methods from the BlockingQueue interface work synchronously but unblock producers immediately + * when their data is taken. + *

        The additional put, take and drain methods from the BatchSynchQueue interface work synchronously and provide the + * option to keep producers blocked until the consumer decides to release them. + * + *

        Removed take method that keeps producers blocked as it is pointless. Essentially it reduces this class to + * synchronous processing of individual data items, which negates the point of the hand-off design. The efficiency + * gain of the hand off design comes in being able to batch consume requests, ammortizing latency (such as caused by io) + * accross many producers. The only advantage of the single blocking take method is that it did take advantage of the + * queue ordering, which ma be usefull, for example to apply a priority ordering amongst producers. This is also an + * advantage over the java.util.concurrent.SynchronousQueue which doesn't have a backing queue which can be used to + * apply orderings. If a single item take is really needed can just use the drainTo method with a maximum of one item. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        + * + * @todo To create zero garbage collecting implemention will need to adapt the queue element containers + * (SynchRefImpl) in such a way that one is needed per array element, they can be taken from/put back/cleared in + * the queue without actually being moved from the array and they implement a way of forming them into a + * collection (or Iterable) to pass to consumers (using a linked list scheme?). May not be worth the trouble. + */ +public abstract class BatchSynchQueueBase extends AbstractQueue implements BatchSynchQueue +{ + /** Used for logging. */ + private static final Logger log = Logger.getLogger(BatchSynchQueueBase.class); + + /** Holds a reference to the queue implementation that holds the buffer. */ + Queue> buffer; + + /** Holds the number of items in the queue */ + private int count; + + /** Main lock guarding all access */ + private ReentrantLock lock; + + /** Condition for waiting takes */ + private Condition notEmpty; + + /** Condition for waiting puts */ + private Condition notFull; + + /** + * Creates a batch synch queue without fair thread scheduling. + */ + public BatchSynchQueueBase() + { + this(false); + } + + /** + * Ensures that the underlying buffer implementation is created. + * + * @param fair true if fairness is to be applied to threads waiting to access the buffer. + */ + public BatchSynchQueueBase(boolean fair) + { + buffer = this.createQueue(); + + // Create the buffer lock with the fairness flag set accordingly. + lock = new ReentrantLock(fair); + + // Create the non-empty and non-full condition monitors on the buffer lock. + notEmpty = lock.newCondition(); + notFull = lock.newCondition(); + } + + /** + * Returns an iterator over the elements contained in this collection. + * + * @return An iterator over the elements contained in this collection. + */ + public Iterator iterator() + { + throw new RuntimeException("Not implemented."); + } + + /** + * Returns the number of elements in this collection. If the collection contains more than + * Integer.MAX_VALUE elements, returns Integer.MAX_VALUE. + * + * @return The number of elements in this collection. + */ + public int size() + { + final ReentrantLock lock = this.lock; + lock.lock(); + + try + { + return count; + } + finally + { + lock.unlock(); + } + } + + /** + * Inserts the specified element into this queue, if possible. When using queues that may impose insertion + * restrictions (for example capacity bounds), method offer is generally preferable to method + * {@link java.util.Collection#add}, which can fail to insert an element only by throwing an exception. + * + * @param e The element to insert. + * + * @return true if it was possible to add the element to this queue, else false + */ + public boolean offer(E e) + { + if (e == null) + { + throw new NullPointerException(); + } + + final ReentrantLock lock = this.lock; + lock.lock(); + + try + { + return insert(e, false); + } + finally + { + lock.unlock(); + } + } + + /** + * Inserts the specified element into this queue, waiting if necessary up to the specified wait time for space to + * become available. + * + * @param e The element to add. + * @param timeout How long to wait before giving up, in units of unit + * @param unit A TimeUnit determining how to interpret the timeout parameter. + * + * @return true if successful, or false if the specified waiting time elapses before space is + * available. + * + * @throws InterruptedException If interrupted while waiting. + * @throws NullPointerException If the specified element is null. + */ + public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException + { + if (e == null) + { + throw new NullPointerException(); + } + + final ReentrantLock lock = this.lock; + lock.lockInterruptibly(); + + long nanos = unit.toNanos(timeout); + + try + { + do + { + if (insert(e, false)) + { + return true; + } + + try + { + nanos = notFull.awaitNanos(nanos); + } + catch (InterruptedException ie) + { + notFull.signal(); // propagate to non-interrupted thread + throw ie; + } + } + while (nanos > 0); + + return false; + } + finally + { + lock.unlock(); + } + } + + /** + * Retrieves and removes the head of this queue, or null if this queue is empty. + * + * @return The head of this queue, or null if this queue is empty. + */ + public E poll() + { + final ReentrantLock lock = this.lock; + + lock.lock(); + try + { + if (count == 0) + { + return null; + } + + E x = extract(true, true).getElement(); + + return x; + } + finally + { + lock.unlock(); + } + } + + /** + * Retrieves and removes the head of this queue, waiting if necessary up to the specified wait time if no elements + * are present on this queue. + * + * @param timeout How long to wait before giving up, in units of unit. + * @param unit A TimeUnit determining how to interpret the timeout parameter. + * + * @return The head of this queue, or null if the specified waiting time elapses before an element is present. + * + * @throws InterruptedException If interrupted while waiting. + */ + public E poll(long timeout, TimeUnit unit) throws InterruptedException + { + final ReentrantLock lock = this.lock; + lock.lockInterruptibly(); + try + { + long nanos = unit.toNanos(timeout); + + do + { + if (count != 0) + { + E x = extract(true, true).getElement(); + + return x; + } + + try + { + nanos = notEmpty.awaitNanos(nanos); + } + catch (InterruptedException ie) + { + notEmpty.signal(); // propagate to non-interrupted thread + throw ie; + } + } + while (nanos > 0); + + return null; + } + finally + { + lock.unlock(); + } + } + + /** + * Retrieves, but does not remove, the head of this queue, returning null if this queue is empty. + * + * @return The head of this queue, or null if this queue is empty. + */ + public E peek() + { + final ReentrantLock lock = this.lock; + lock.lock(); + + try + { + return peekAtBufferHead(); + } + finally + { + lock.unlock(); + } + } + + /** + * Returns the number of elements that this queue can ideally (in the absence of memory or resource constraints) + * accept without blocking, or Integer.MAX_VALUE if there is no intrinsic limit. + * + *

        Note that you cannot always tell if an attempt to add an element will succeed by + * inspecting remainingCapacity because it may be the case that another thread is about to put + * or take an element. + * + * @return The remaining capacity. + */ + public int remainingCapacity() + { + final ReentrantLock lock = this.lock; + lock.lock(); + + try + { + return getBufferCapacity() - count; + } + finally + { + lock.unlock(); + } + } + + /** + * Adds the specified element to this queue, waiting if necessary for space to become available. + * + *

        This method delegated to {@link #tryPut} which can raise {@link SynchException}s. If any are raised + * this method silently ignores them. Use the {@link #tryPut} method directly if you want to catch these + * exceptions. + * + * @param e The element to add. + * + * @throws InterruptedException If interrupted while waiting. + */ + public void put(E e) throws InterruptedException + { + try + { + tryPut(e); + } + catch (SynchException ex) + { + // This exception is deliberately ignored. See the method comment for information about this. + } + } + + /** + * Tries a synchronous put into the queue. If a consumer encounters an exception condition whilst processing the + * data that is put, then this is returned to the caller wrapped inside a {@link SynchException}. + * + * @param e The data element to put into the queue. + * + * @throws InterruptedException If the thread is interrupted whilst waiting to write to the queue or whilst waiting + * on its entry in the queue being consumed. + * @throws SynchException If a consumer encounters an error whilst processing the data element. + */ + public void tryPut(E e) throws InterruptedException, SynchException + { + if (e == null) + { + throw new NullPointerException(); + } + + // final Queue items = this.buffer; + final ReentrantLock lock = this.lock; + lock.lockInterruptibly(); + + try + { + while (count == getBufferCapacity()) + { + // Release the lock and wait until the queue is not full. + notFull.await(); + } + } + catch (InterruptedException ie) + { + notFull.signal(); // propagate to non-interrupted thread + throw ie; + } + + // There is room in the queue so insert must succeed. Insert into the queu, release the lock and block + // the producer until its data is taken. + insert(e, true); + } + + /** + * Retrieves and removes the head of this queue, waiting if no elements are present on this queue. + * Any producer that has its data element taken by this call will be immediately unblocked. To keep the + * producer blocked whilst taking just a single item, use the + * {@link #drainTo(java.util.Collection>, int, boolean)} + * method. There is no take method to do that because there is not usually any advantage in a synchronous hand + * off design that consumes data one item at a time. It is normal to consume data in chunks to ammortize consumption + * latencies accross many producers where possible. + * + * @return The head of this queue. + * + * @throws InterruptedException if interrupted while waiting. + */ + public E take() throws InterruptedException + { + final ReentrantLock lock = this.lock; + lock.lockInterruptibly(); + + try + { + try + { + while (count == 0) + { + // Release the lock and wait until the queue becomes non-empty. + notEmpty.await(); + } + } + catch (InterruptedException ie) + { + notEmpty.signal(); // propagate to non-interrupted thread + throw ie; + } + + // There is data in the queue so extraction must succeed. Notify any waiting threads that the queue is + // not full, and unblock the producer that owns the data item that is taken. + E x = extract(true, true).getElement(); + + return x; + } + finally + { + lock.unlock(); + } + } + + /** + * Removes all available elements from this queue and adds them into the given collection. This operation may be + * more efficient than repeatedly polling this queue. A failure encountered while attempting to add elements + * to collection c may result in elements being in neither, either or both collections when the associated + * exception is thrown. Attempts to drain a queue to itself result in IllegalArgumentException. Further, + * the behavior of this operation is undefined if the specified collection is modified while the operation is in + * progress. + * + * @param objects The collection to transfer elements into. + * + * @return The number of elements transferred. + * + * @throws NullPointerException If objects is null. + * @throws IllegalArgumentException If objects is this queue. + */ + public int drainTo(Collection objects) + { + return drainTo(objects, -1); + } + + /** + * Removes at most the given number of available elements from this queue and adds them into the given collection. + * A failure encountered while attempting to add elements to collection c may result in elements + * being in neither, either or both collections when the associated exception is thrown. Attempts to drain a queue + * to itself result in IllegalArgumentException. Further, the behavior of this operation is undefined if + * the specified collection is modified while the operation is in progress. + * + * @param objects The collection to transfer elements into. + * @param maxElements The maximum number of elements to transfer. If this is -1 then that is interpreted as meaning + * all elements. + * + * @return The number of elements transferred. + * + * @throws NullPointerException If c is null. + * @throws IllegalArgumentException If c is this queue. + */ + public int drainTo(Collection objects, int maxElements) + { + if (objects == null) + { + throw new NullPointerException(); + } + + if (objects == this) + { + throw new IllegalArgumentException(); + } + + // final Queue items = this.buffer; + final ReentrantLock lock = this.lock; + lock.lock(); + + try + { + int n = 0; + + for (int max = ((maxElements >= count) || (maxElements < 0)) ? count : maxElements; n < max; n++) + { + // Take items from the queue, do unblock the producers, but don't send not full signals yet. + objects.add(extract(true, false).getElement()); + } + + if (n > 0) + { + // count -= n; + notFull.signalAll(); + } + + return n; + } + finally + { + lock.unlock(); + } + } + + /** + * Takes all available data items from the queue or blocks until some become available. The returned items + * are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their + * producers, where the producers are still blocked. + * + * @param c The collection to drain the data items into. + * @param unblock If set to true the producers for the taken items will be immediately unblocked. + * + * @return A count of the number of elements that were drained from the queue. + */ + public SynchRef drainTo(Collection> c, boolean unblock) + { + return drainTo(c, -1, unblock); + } + + /** + * Takes up to maxElements available data items from the queue or blocks until some become available. The returned + * items are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their + * producers, where the producers are still blocked. + * + * @param coll The collection to drain the data items into. + * @param maxElements The maximum number of elements to drain. + * @param unblock If set to true the producers for the taken items will be immediately unblocked. + * + * @return A count of the number of elements that were drained from the queue. + */ + public SynchRef drainTo(Collection> coll, int maxElements, boolean unblock) + { + if (coll == null) + { + throw new NullPointerException(); + } + + // final Queue items = this.buffer; + final ReentrantLock lock = this.lock; + lock.lock(); + + try + { + int n = 0; + + for (int max = ((maxElements >= count) || (maxElements < 0)) ? count : maxElements; n < max; n++) + { + // Extract the next record from the queue, don't signall the not full condition yet and release + // producers depending on whether the caller wants to or not. + coll.add(extract(false, unblock)); + } + + if (n > 0) + { + // count -= n; + notFull.signalAll(); + } + + return new SynchRefImpl(n, coll); + } + finally + { + lock.unlock(); + } + } + + /** + * This abstract method should be overriden to return an empty queue. Different implementations of producer + * consumer buffers can control the order in which data is accessed using different queue implementations. + * This method allows the type of queue to be abstracted out of this class and to be supplied by concrete + * implementations. + * + * @return An empty queue. + */ + protected abstract Queue createQueue(); + + /** + * Insert element into the queue, then possibly signal that the queue is not empty and block the producer + * on the element until permission to procede is given. + * + *

        If the producer is to be blocked then the lock must be released first, otherwise no other process + * will be able to get access to the queue. Hence, unlock and block are always set together. + * + *

        Call only when holding the global lock. + * + * @param unlockAndBlock trueIf the global queue lock should be released and the producer should be blocked. + * + * @return true if the operation succeeded, false otherwise. If the result is true this + * method may not return straight away, but only after the producer is unblocked by having its data + * consumed if the unlockAndBlock flag is set. In the false case the method will return straight away, no + * matter what value the unlockAndBlock flag has, leaving the global lock on. + */ + protected boolean insert(E x, boolean unlockAndBlock) + { + // Create a new record for the data item. + SynchRecordImpl record = new SynchRecordImpl(x); + + boolean result = buffer.offer(record); + + if (result) + { + count++; + + // Tell any waiting consumers that the queue is not empty. + notEmpty.signal(); + + if (unlockAndBlock) + { + // Allow other threads to read/write the queue. + lock.unlock(); + + // Wait until a consumer takes this data item. + record.waitForConsumer(); + } + + return true; + } + else + { + return false; + } + } + + /** + * Extract element at current take position, advance, and signal. + * + *

        Call only when holding lock. + */ + protected SynchRecordImpl extract(boolean unblock, boolean signal) + { + SynchRecordImpl result = buffer.remove(); + count--; + + if (signal) + { + notFull.signal(); + } + + if (unblock) + { + result.releaseImmediately(); + } + + return result; + } + + /** + * Get the capacity of the buffer. If the buffer has no maximum capacity then Integer.MAX_VALUE is returned. + * + *

        Call only when holding lock. + * + * @return The maximum capacity of the buffer. + */ + protected int getBufferCapacity() + { + if (buffer instanceof Capacity) + { + return ((Capacity) buffer).getCapacity(); + } + else + { + return Integer.MAX_VALUE; + } + } + + /** + * Return the head element from the buffer. + * + *

        Call only when holding lock. + * + * @return The head element from the buffer. + */ + protected E peekAtBufferHead() + { + return buffer.peek().getElement(); + } + + public class SynchRefImpl implements SynchRef + { + /** Holds the number of synch records associated with this reference. */ + int numRecords; + + /** Holds a reference to the collection of synch records managed by this. */ + Collection> records; + + public SynchRefImpl(int n, Collection> records) + { + this.numRecords = n; + this.records = records; + } + + public int getNumRecords() + { + return numRecords; + } + + /** + * Any producers that have had their data elements taken from the queue but have not been unblocked are unblocked + * when this method is called. The exception to this is producers that have had their data put back onto the queue + * by a consumer. Producers that have had exceptions for their data items registered by consumers will be unblocked + * but will not return from their put call normally, but with an exception instead. + */ + public void unblockProducers() + { + log.debug("public void unblockProducers(): called"); + + if (records != null) + { + for (SynchRecord record : records) + { + // This call takes account of items that have already been released, are to be requeued or are in + // error. + record.releaseImmediately(); + } + } + + records = null; + } + } + + /** + * A SynchRecordImpl is used by a {@link BatchSynchQueue} to pair together a producer with its data. This allows + * the producer of data to be identified so that it can be unblocked when its data is consumed or sent errors when + * its data cannot be consumed. + */ + public class SynchRecordImpl implements SynchRecord + { + /** A boolean latch that determines when the producer for this data item will be allowed to continue. */ + BooleanLatch latch = new BooleanLatch(); + + /** The data element associated with this item. */ + E element; + + /** + * Create a new synch record. + * + * @param e The data element that the record encapsulates. + */ + public SynchRecordImpl(E e) + { + // Keep the data element. + element = e; + } + + /** + * Waits until the producer is given permission to proceded by a consumer. + */ + public void waitForConsumer() + { + latch.await(); + } + + /** + * Gets the data element contained by this record. + * + * @return The data element contained by this record. + */ + public E getElement() + { + return element; + } + + /** + * Immediately releases the producer of this data record. Consumers can bring the synchronization time of + * producers to a minimum by using this method to release them at the earliest possible moment when batch + * consuming records from sychronized producers. + */ + public void releaseImmediately() + { + // Check that the record has not already been released, is in error or is to be requeued. + latch.signal(); + + // Propagate errors to the producer. + + // Requeue items to be requeued. + } + + /** + * Tells the synch queue to put this element back onto the queue instead of releasing its producer. + * The element is not requeued immediately but upon calling the {@link SynchRef#unblockProducers()} method or + * the {@link #releaseImmediately()} method. + * + *

        This method will raise a runtime exception {@link AlreadyUnblockedException} if the producer for this + * element has already been unblocked. + */ + public void reQueue() + { + throw new RuntimeException("Not implemented."); + } + + /** + * Tells the synch queue to raise an exception with this elements producer. The exception is not raised + * immediately but upon calling the {@link SynchRef#unblockProducers()} method or the + * {@link #releaseImmediately()} method. The exception will be wrapped in a {@link SynchException} before it is + * raised on the producer. + * + *

        This method is unusual in that it accepts an exception as an argument. This is non-standard but is used + * because the exception is to be passed onto a different thread. + * + *

        This method will raise a runtime exception {@link AlreadyUnblockedException} if the producer for this + * element has already been unblocked. + * + * @param e The exception to raise on the producer. + */ + public void inError(Exception e) + { + throw new RuntimeException("Not implemented."); + } + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java new file mode 100644 index 0000000000..2a5b0d0c3e --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java @@ -0,0 +1,107 @@ +package org.apache.qpid.util.concurrent; + +import java.util.concurrent.locks.AbstractQueuedSynchronizer; + +/** + * A BooleanLatch is like a set of traffic lights, where threads can wait at a red light until another thread gives + * the green light. When threads arrive at the latch it is initially red. They queue up until the green signal is + * given, at which point they can all acquire the latch in shared mode and continue to run concurrently. Once the latch + * is signalled it cannot be reset to red again. + * + *

        The latch uses a {@link java.util.concurrent.locks.AbstractQueuedSynchronizer} to implement its synchronization. + * This has two internal states, 0 which means that the latch is blocked, and 1 which means that the latch is open. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Block threads until a go signal is given. + *
        + * + * @todo Might be better to use a countdown latch to count down from 1. Its await method can throw interrupted + * exception which makes the possibility of interruption more explicit, and provides a reminder to recheck the + * latch condition before continuing. + */ +public class BooleanLatch +{ + /** Holds the synchronizer that provides the thread queueing synchronization. */ + private final Sync sync = new Sync(); + + /** + * Tests whether or not the latch has been signalled, that is to say that, the light is green. + * + *

        This method is non-blocking. + * + * @return true if the latch may be acquired; the light is green. + */ + public boolean isSignalled() + { + return sync.isSignalled(); + } + + /** + * Waits on the latch until the signal is given and the light is green. If the light is already green then the + * latch will be acquired and the thread will not have to wait. + * + *

        This method will block until the go signal is given or the thread is otherwise interrupted. Before carrying + * out any processing threads that return from this method should confirm that the go signal has really been given + * on this latch by calling the {@link #isSignalled()} method. + */ + public void await() + { + sync.acquireShared(1); + } + + /** + * Releases any threads currently waiting on the latch. This flips the light to green allowing any threads that + * were waiting for this condition to now run. + * + *

        This method is non-blocking. + */ + public void signal() + { + sync.releaseShared(1); + } + + /** + * Implements a thread queued synchronizer. The internal state 0 means that the queue is blocked and the internl + * state 1 means that the queue is released and that all waiting threads can acquire the synchronizer in shared + * mode. + */ + private static class Sync extends AbstractQueuedSynchronizer + { + /** + * Attempts to acquire this synchronizer in shared mode. It may be acquired once it has been released. + * + * @param ignore This parameter is ignored. + * + * @return 1 if the shared acquisition succeeds and -1 if it fails. + */ + protected int tryAcquireShared(int ignore) + { + return isSignalled() ? 1 : -1; + } + + /** + * Releases the synchronizer, setting its internal state to 1. + * + * @param ignore This parameter is ignored. + * + * @return true always. + */ + protected boolean tryReleaseShared(int ignore) + { + setState(1); + + return true; + } + + /** + * Tests if the synchronizer is signalled. It is signalled when its internal state it 1. + * + * @return true if the internal state is 1, false otherwise. + */ + boolean isSignalled() + { + return getState() != 0; + } + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/Capacity.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/Capacity.java new file mode 100644 index 0000000000..2b4a5f28a9 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/Capacity.java @@ -0,0 +1,14 @@ +package org.apache.qpid.util.concurrent; + +/** + * An interface exposed by data structures that have a maximum capacity. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Report the maximum capacity. + *
        + */ +public interface Capacity +{ + public int getCapacity(); +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchBuffer.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchBuffer.java new file mode 100644 index 0000000000..8f682ec462 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchBuffer.java @@ -0,0 +1,29 @@ +package org.apache.qpid.util.concurrent; + +import java.util.Queue; + +/** + * SynchBuffer completes the {@link BatchSynchQueueBase} abstract class by providing an implementation of the underlying + * queue as an array. This uses FIFO ordering for the queue but restricts the maximum size of the queue to a fixed + * amount. It also has the advantage that, as the buffer does not grow and shrink dynamically, memory for the buffer + * is allocated up front and does not create garbage during the operation of the queue. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Provide array based FIFO queue to create a batch synched queue around. + *
        + * + * @todo Write an array based buffer implementation that implements Queue. + */ +public class SynchBuffer extends BatchSynchQueueBase +{ + /** + * Returns an empty queue, implemented as an array. + * + * @return An empty queue, implemented as an array. + */ + protected Queue createQueue() + { + throw new RuntimeException("Not implemented."); + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchException.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchException.java new file mode 100644 index 0000000000..c6edff6320 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchException.java @@ -0,0 +1,31 @@ +package org.apache.qpid.util.concurrent; + +/** + * SynchException is used to encapsulate exceptions with the data elements that caused them in order to send exceptions + * back from the consumers of a {@link BatchSynchQueue} to producers. The underlying exception should be retrieved from + * the {@link #getCause} method. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Encapsulate a data element and exception. + *
        + */ +public class SynchException extends Exception +{ + /** Holds the data element that is in error. */ + Object element; + + /** + * Creates a new BaseApplicationException object. + * + * @param message The exception message. + * @param cause The underlying throwable cause. This may be null. + */ + public SynchException(String message, Throwable cause, Object element) + { + super(message, cause); + + // Keep the data element that was in error. + this.element = element; + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchQueue.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchQueue.java new file mode 100644 index 0000000000..df3f2b849a --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchQueue.java @@ -0,0 +1,27 @@ +package org.apache.qpid.util.concurrent; + +import java.util.LinkedList; +import java.util.Queue; + +/** + * SynchQueue completes the {@link BatchSynchQueueBase} abstract class by providing an implementation of the underlying + * queue as a linked list. This uses FIFO ordering for the queue and allows the queue to grow to accomodate more + * elements as needed. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Provide linked list FIFO queue to create a batch synched queue around. + *
        + */ +public class SynchQueue extends BatchSynchQueueBase +{ + /** + * Returns an empty queue, implemented as a linked list. + * + * @return An empty queue, implemented as a linked list. + */ + protected Queue createQueue() + { + return new LinkedList(); + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRecord.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRecord.java new file mode 100644 index 0000000000..cacef472d6 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRecord.java @@ -0,0 +1,53 @@ +package org.apache.qpid.util.concurrent; + +/** + * SynchRecord associates a data item from a {@link BatchSynchQueue} with its producer. This enables the data item data + * item to be put back on the queue without unblocking its producer, or to send exceptions to the producer. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Get the underlying data element. + *
        Put the data element back on the queue without unblocking its producer. + *
        Send and exception to the data elements producer. + *
        + */ +public interface SynchRecord +{ + /** + * Gets the data element contained by this record. + * + * @return The data element contained by this record. + */ + public E getElement(); + + /** + * Tells the synch queue to put this element back onto the queue instead of releasing its producer. + * The element is not requeued immediately but upon calling the {@link SynchRef#unblockProducers()} method. + * + *

        This method will raise a runtime exception {@link AlreadyUnblockedException} if the producer for this element + * has already been unblocked. + */ + public void reQueue(); + + /** + * Immediately releases the producer of this data record. Consumers can bring the synchronization time of + * producers to a minimum by using this method to release them at the earliest possible moment when batch + * consuming records from sychronized producers. + */ + public void releaseImmediately(); + + /** + * Tells the synch queue to raise an exception with this elements producer. The exception is not raised immediately + * but upon calling the {@link SynchRef#unblockProducers()} method. The exception will be wrapped in a + * {@link SynchException} before it is raised on the producer. + * + *

        This method is unusual in that it accepts an exception as an argument. This is non-standard but is used + * because the exception is to be passed onto a different thread. + * + *

        This method will raise a runtime exception {@link AlreadyUnblockedException} if the producer for this element + * has already been unblocked. + * + * @param e The exception to raise on the producer. + */ + public void inError(Exception e); +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRef.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRef.java new file mode 100644 index 0000000000..c044ed0a60 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRef.java @@ -0,0 +1,30 @@ +package org.apache.qpid.util.concurrent; + +/** + * A SynchRef is an interface which is returned from the synchronous take and drain methods of {@link BatchSynchQueue}, + * allowing call-backs to be made against the synchronizing strucutre. It allows the consumer to communicate when it + * wants producers that have their data taken to be unblocked. + * + *

        + *
        CRC Card
        Responsibilities + *
        Report number of records returned by a taking operation. + *
        Provide call-back to release producers of taken records. + *
        + */ +public interface SynchRef +{ + /** + * Reports the number of records taken by the take or drain operation. + * + * @return The number of records taken by the take or drain operation. + */ + public int getNumRecords(); + + /** + * Any producers that have had their data elements taken from the queue but have not been unblocked are + * unblocked when this method is called. The exception to this is producers that have had their data put back + * onto the queue by a consumer. Producers that have had exceptions for their data items registered by consumers + * will be unblocked but will not return from their put call normally, but with an exception instead. + */ + public void unblockProducers(); +} -- cgit v1.2.1 From b699d6aa15aba59a9c6ae1651ff7be1f3bf577e8 Mon Sep 17 00:00:00 2001 From: Rupert Smith Date: Tue, 22 May 2007 13:45:50 +0000 Subject: Eliminated catch/rethrow where underlying cause was discarded. All causes now wrapped. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@540584 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/util/concurrent/BatchSynchQueueBase.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java index 521c341ca3..08b5745b19 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java @@ -37,11 +37,6 @@ import org.apache.log4j.Logger; *

        *
        CRC Card
        Responsibilities Collaborations *
        - * - * @todo To create zero garbage collecting implemention will need to adapt the queue element containers - * (SynchRefImpl) in such a way that one is needed per array element, they can be taken from/put back/cleared in - * the queue without actually being moved from the array and they implement a way of forming them into a - * collection (or Iterable) to pass to consumers (using a linked list scheme?). May not be worth the trouble. */ public abstract class BatchSynchQueueBase extends AbstractQueue implements BatchSynchQueue { @@ -350,7 +345,7 @@ public abstract class BatchSynchQueueBase extends AbstractQueue implements * Tries a synchronous put into the queue. If a consumer encounters an exception condition whilst processing the * data that is put, then this is returned to the caller wrapped inside a {@link SynchException}. * - * @param e The data element to put into the queue. + * @param e The data element to put into the queue. Cannot be null. * * @throws InterruptedException If the thread is interrupted whilst waiting to write to the queue or whilst waiting * on its entry in the queue being consumed. @@ -390,7 +385,7 @@ public abstract class BatchSynchQueueBase extends AbstractQueue implements * Retrieves and removes the head of this queue, waiting if no elements are present on this queue. * Any producer that has its data element taken by this call will be immediately unblocked. To keep the * producer blocked whilst taking just a single item, use the - * {@link #drainTo(java.util.Collection>, int, boolean)} + * {@link #drainTo(java.util.Collection>, int, boolean)} * method. There is no take method to do that because there is not usually any advantage in a synchronous hand * off design that consumes data one item at a time. It is normal to consume data in chunks to ammortize consumption * latencies accross many producers where possible. -- cgit v1.2.1 From f9e83f70ff57ca31d0849926ecc6271673404b0b Mon Sep 17 00:00:00 2001 From: Rupert Smith Date: Tue, 29 May 2007 10:19:25 +0000 Subject: Added to the Javadoc git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@542476 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/pool/PoolingFilter.java | 25 ---------------------- .../org/apache/qpid/util/CommandLineParser.java | 13 +++++++++-- 2 files changed, 11 insertions(+), 27 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java index ffc8f1643a..7f6b1d40ac 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java @@ -22,13 +22,10 @@ package org.apache.qpid.pool; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; - import org.apache.log4j.Logger; - import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoSession; - import org.apache.qpid.pool.Event.CloseEvent; /** @@ -201,19 +198,6 @@ public abstract class PoolingFilter extends IoFilterAdapter implements Job.JobCo return (Job) session.getAttribute(_name); } - /*private Job createJobForSession(IoSession session) - { - return addJobForSession(session, new Job(session, this, _maxEvents)); - }*/ - - /*private Job addJobForSession(IoSession session, Job job) - { - // atomic so ensures all threads agree on the same job - Job existing = _jobs.putIfAbsent(session, job); - - return (existing == null) ? job : existing; - }*/ - /** * Implements a terminal continuation for the {@link Job} for this filter. Whenever the Job completes its processing * of a batch of events this is called. This method simply re-activates the job, if it has more events to process. @@ -223,15 +207,6 @@ public abstract class PoolingFilter extends IoFilterAdapter implements Job.JobCo */ public void completed(IoSession session, Job job) { - // if (job.isComplete()) - // { - // job.release(); - // if (!job.isReferenced()) - // { - // _jobs.remove(session); - // } - // } - // else if (!job.isComplete()) { // ritchiem : 2006-12-13 Do we need to perform the additional checks here? diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java b/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java index 61955160be..9bb4a6635f 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java @@ -603,12 +603,21 @@ public class CommandLineParser } /** - * Extracts all name=value pairs from the command line, sets them all as system properties and also returns - * a map of properties containing them. + * Parses the command line arguments against the specified command line format, printing errors and usage + * instrucitons and calling System.exit on errors. Extracts all trailing name=value pairs from the command line, + * and sets them all as system properties and also returns a map of properties containing them. * * @param args The command line. * * @return A set of properties containing all name=value pairs from the command line. + * + * @todo Replace the call to System.exit with throwing an exception. Gives caller the option to decide how to + * handle the error. + * + * @todo Pass in the location to write the usage to as an argument, instead of hard-coding System.out. + * + * @todo Allow the Properties to add trailing options to be specified as an argument rather than hard coding + * system properties. Again, gives the caller the option to decide. */ public static Properties processCommandLine(String[] args, CommandLineParser commandLine) { -- cgit v1.2.1 From 1d23b9ec5e7296aecefe94a532a9f22dfb5fa5bb Mon Sep 17 00:00:00 2001 From: Martin Ritchie Date: Fri, 15 Jun 2007 16:28:46 +0000 Subject: Merged revisions 439476-447993,447995-448007,448009-448141,448143-448157,448161-448194,448196-448210,448212-448218,448220-448223,448225-448233,448235,448237-448241,448243-448596,448598-448623,448625-448850,448852-448880,448882-448982,448984-449635,449637-449639,449641-449642,449644-449645,449647-449674,449676-449719,449721-449749,449751-449762,449764-449933,449935-449941,449943-450383,450385,450387-450400,450402-450433,450435-450503,450505-450555,450557-450860,450862-451024,451026-451149,451151-451316,451318-451931,451933-452139,452141-452162,452164-452320,452322,452324-452325,452327-452333,452335-452429,452431-452528,452530-452545,452547-453192,453194-453195,453197-453536,453538,453540-453656,453658-454676,454678-454735,454737,454739-454781,454783-462728,462730-462819,462821-462833,462835-462839,462841-463071,463073-463178,463180-463308,463310-463362,463364-463375,463377-463396,463398-463402,463404-463409,463411-463661,463663-463670,463672-463673,463675-464493,464495-464502,464504-464576,464578-464613,464615-464628,464630,464632-464866,464868-464899,464901-464942,464944-464949,464951-465004,465006-465016,465018-465053,465055-465165,465167-465321,465323-465406,465408-465427,465429-465431,465433-465548,465550-466044,466047-466075,466077,466079-466081,466083-466099,466101-466112,466114-466126,466128-466240,466242-466971,466973-466978,466980-467309,467311-467312,467316-467328,467330-467485,467487-467588,467590-467604,467606-467699,467701-467706,467708-467749,467751-468069,468071-468537,468539-469241,469244-469246,469248-469318,469320-469421,469423,469425-469429,469431-469435,469437-469462,469464-469469,469472-469477,469479-469490,469492-469503,469505-469529,469531-469598,469600-469624,469626-469737,469739-469752,469754-469806,469808-469928,469930-469953,469955-470011,470013-470109,470111-470335,470338-470339,470341-470379,470381,470383-470399,470401-470446,470448-470741,470743-470758,470760-470809,470811-470817,470819-470993,470995-471001,471003-471788,471790-471792,471794-472028,472030-472032,472034-472036,472038,472040,472043,472045-472059,472061,472063,472065-472066,472068,472070-472072,472074-472080,472082,472084-472092,472094-472107,472109-472123,472125-472158,472160-472165,472167-472172,472174-472457,472459-472460,472462-472464,472466-472470,472472-472483,472486-472491,472493-472494,472496-472497,472499,472501-472503,472505-472512,472514-472544,472546-472556,472558-472560,472562-472572,472574-472587,472589-472591,472593-472605,472607,472609-472731,472733-472786,472788-472843,472845-472849,472851-472859,472861-472878,472880-472903,472905,472907-472988,472990-472991,472993-473071,473073-473086,473088-473090,473093,473095-473096,473098-473106,473108-473110,473112-473185,473187-473260,473262,473268-473270,473275-473279,473281,473284-473287,473289-473295,473297-473306,473308-473330,473332-473335,473337,473339-473344,473346-473351,473353-473355,473357-473358,473361-473471,473473-473497,473499-473535,473537-473567,473569-473888,473890-474451,474454-474492,474494-474563,474565-474843,474845-474865,474867-474932,474934-475035,475037-475144,475146-475180,475182-475265,475267-475285,475287,475289-475293,475295-475296,475298-475302,475304-475631,475633-475649,475651-475748,475750-475752,475754-476107,476109-476302,476304-476413,476415-476430,476432-476700,476702-476868,476870-477147,477149-477213,477215-477263,477265-477340,477342-477635,477637-477789,477791-477825,477827-477841,477843,477846-477852,477854,477856,477858-477865,477867-477894,477896-478022,478024-478182,478184-478211,478213-478233,478235-478236,478238-478241,478243-478252,478254-478259,478261-478263,478265,478267-478269,478271-478286,478288-478342,478344-478379,478381-478412,478414-478443,478445-478636,478639-478658,478660-478821,478823-478853,478855-478922,478924-478962,478965-478974,478976-479029,479031-479049,479051-479210,479212-479214,479216-479407,479409-479415,479417-479425,479427-479559,479561-479639,479641-479676,479678-479685,479687-480030,480033-480086,480091-480093,480095-480118,480120-480139,480141,480143-480148,480150-480156,480158-480163,480165-480177,480179-480189,480191-480193,480195-480198,480200-480220,480222-480282,480284-480292,480294-480308,480310-480317,480320-480422,480424,480426-480581,480583-480656,480658-480692,480695-480702,480704,480706-480710,480712-480910,480913-480933,480935-480945,480947-480972,480974-480993,480995-481034,481036-481158,481161-481174,481176-481220,481222-481234,481236-481260,481263-481264,481266-481296,481298-481304,481306-481311,481313-481332,481334,481336-481380,481382-481441,481443-482144,482146-482180,482182-482193,482195-482232,482234-482236,482239,482241-482242,482244-482247,482250-482251,482253,482256-482261,482264-482288,482290-482364,482366,482368,482370-482554,482556,482558-482569,482572-482636,482638,482640-482696,482698-482722,482724-482732,482734-482771,482774-482957,482959-483045,483047-483105,483108,483110-483115,483117,483119-483127,483130-483134,483136-483148,483150-483158,483160-483164,483166-483178,483180-483391,483393-483400,483402-483403,483405-483418,483420-483421,483425-483436,483438-483470,483472-483502,483504-483558,483560-483599,483601-483637,483639-483644,483646-483659,483661-483670,483672-483878,483880-483910,483912-483915,483917-483940,483942,483944-483968,483970-483972,483974-483976,483978,483980-484612,484614-484657,484659-484693,484695-484718,484720-484842,484844-484847,484849-484986,484988-485019,485021-485489,485491-485544,485546-485591,485593,485595-485697,485699-485729,485731-485734,485736-485779,485781-485787,485789-485851,485853,485855-486007,486009,486011-486020,486022-486083,486085-486097,486099-486117,486120-486131,486133-486148,486150-486161,486163-486164,486166-486197,486199-486205,486208-486247,486249-486253,486256-486427,486429-486431,486433-486554,486556-486573,486575-486593,486595,486597-486609,486611-486619,486622,486625,486627-486641,486643-486645,486649-486687,486689-486721,486723-486730,486732-486746,486748-486759,486761,486763-486777,486779-486782,486784-486788,486790,486792,486794-486796,486798-487175,487178,487180-487213,487215,487217-487267,487269-487284,487286-487298,487300-487358,487360-487367,487369-487382,487384-487434,487436-487480,487482-487547,487549-487561,487563-487565,487567-487578,487580-487615,487617-487622,487624,487626,487628,487630-487635,487637-487703,487705-487777,487780-487781,487783-487800,487802-487803,487805-487820,487822-487848,487850-487902,487904-488103,488105-488133,488135-488158,488160-488163,488165-488187,488189-488216,488218-488248,488250-488278,488280,488282-488303,488305-488313,488315-488342,488344-488351,488353-488376,488378-488449,488451-488593,488595,488597-488623,488625-488700,488702-488704,488706-488710,488714,488716-488725,488727-488744,488746-488770,488772-488798,488800,488802-488807,488809,488811-488829,488831-488843,488845-488851,488853-489069,489071-489077,489079-489081,489084-489102,489104-489105,489107-489109,489111-489112,489114-489139,489141-489178,489181-489203,489205-489211,489213,489216-489329,489332-489402,489404-489417,489419-489421,489423-489643,489645-489690,489692-489703,489705-489714,489716-489747,489749-489753,489755-489803,489805-489904,489906-490372,490374-490504,490506-490604,490606-490707,490710-490733,490735-490871,490873-490984,490986-491028,491030,491032-491071,491073-491119,491121-491576,491578-491672,491674-491800,491802-491838,491840-491878,491880-492183,492185-492279,492281-492317,492319-492513,492515-492584,492586-492587,492589-492601,492603-492635,492637-492640,492642-492717,492719-492723,492725-492729,492731-492755,492757-492901,492903-492955,492957-492962,492964-492997,492999-493002,493004-493041,493043-493059,493062-493063,493065-493086,493088-493125,493127-493139,493141-493150,493152-493871,493873-494017,494019-494030,494032-494041,494043-494091,494093-494120,494122-494354,494356-494436,494438-494539,494541-494552,494554-494586,494588-494649,494651,494653-494654,494656-494657,494659-494764,494766-494768,494770-494796,494798-494799,494802,494804-494860,494862-494903,494905-494906,494908-495019,495021-495160,495162-495168,495171-495188,495190-495229,495231-495254,495256-495303,495305-495313,495315-495336,495338-495372,495374-495379,495381-495454,495457-495459,495462-495516,495518-495524,495526-495531,495533-495548,495551-495553,495555,495557-495558,495560,495562-495573,495575-495583,495585-495594,495596-495628,495630-495638,495640-495651,495653-495660,495662-495753,495755-496259,496261-496262,496264-496269,496271-496275,496277-496301,496303-496316,496318-496383,496385-496413,496415-496495,496497-496625,496627-496636,496638-496640,496642-496647,496650-496657,496659-496660,496663-496664,496666-496677,496679-496681,496683-496730,496732-496750,496752,496754-496784,496786-496832,496834-496840,496842-496990,496992-496995,496997-497340,497343-497351,497353-497403,497405-497424,497426-497438,497440-497481,497483-497497,497499-497765,497767-497769,497771-497775,497777-497778,497780,497782-497783,497785,497787-497812,497814-497871,497873-497877,497879-498573,498575-498588,498590,498592,498594-498636,498638-498669,498671-498686,498688-498689,498691-498719,498721-498964,498966-498969,498971-498973,498975-498982,498985-499035,499037-499040,499042,499044-499048,499050-499082,499084-499086,499088-499164,499167-499169,499171-499355,499357-499370,499372-499373,499375-499391,499393,499395-499425,499428,499430-499445,499447-499455,499457-499460,499462-499465,499467,499469-499489,499491-499492,499494-499531,499533-499562,499566-499627,499629-499715,499717-499732,499734-499755,499758-499763,499765-499780,499782-499795,499797-499802,499804-499844,499846,499848-499850,499852-499863,499865-499873,499875-499974,499976-499978,499980-500263,500265-500283,500285-500309,500311-501000,501002,501012-501057,501059-501095,501097-501390,501392-501410,501413-501447,501449-501454,501456,501458-501464,501466-501471,501473-501803,501805-501913,501915-501916,501918-501919,501921-501944,501946-502171,502173-502177,502181,502183-502247,502250-502252,502254-502260,502262-502267,502270,502272,502274-502575,502577-502609,502611-502619,502621-502626,502628-502654,502656-503592,503594-503603,503605-503608,503610-503636,503638-503645,503647-503705,503707-503789,503791-504024,504026-504111,504113-504506,504508-504735,504737-504863,504865-504867,504869-504914,504916-505241,505243-505254,505257-505267,505269-505354,505356-505891,505893-505971,505973-506400,506402-506404,506407-506438,506440-506516,506518-506541,506543-506966,506968-506971,506973-507095,507097-507108,507111-507454,507456,507459-507471,507473-507556,507558,507560-507581,507585-507594,507597,507599-507608,507610-507728,507730-507893,507895-507937,507940-508234,508236-508350,508352-508365,508367-508380,508383,508386-508415,508417-508648,508650-508941,508943-509146,509148-509171,509173-509175,509179-509201,509203-509207,509209-509215,509217-509222,509224-509477,509480-509627,509629-509634,509636-509641,509643-509736,509738-509931,509933-510059,510061-510075,510077-510158,510161-510896,510898-510938,510940-511388,511390-511922,511924-512287,512289-512698,512702-512813,512815-512817,512819-513359,513361-513370,513372-514702,514704-514886,514888-514902,514904-515126,515129-515141,515143-515516,515518-515534,515536-515538,515540-515648,515650-515651,515653-516070,516072-516411,516413-516448,516450,516452-517637,517639-517647,517649-517659,517661-517663,517665-517677,517679-517682,517684-517744,517746-518085,518087-518175,518177-518558,518560-518568,518571-518666,518668,518670-518699,518701-518987,518990-518992,518994-519908,519910-519932,519934-520414,520416-520842,520844-520937,520939-521362,521364-521681,521683-521704,521706-521709,521711-521714,521716-521781,521783-521792,521794-522462,522464-522527,522529-522534,522536-522566,522568-522958,522960,522962-522966,522968-522976,522978-522980,522982-522988,522992-522993,522995-523244,523246-523746,523748-524049,524051-524738,524741-524742,524744-524762,524764,524766,524768-525486,525488-525530,525532,525534,525537-525552,525554-525765,525767-525776,525778-525784,525789-525803,525805-525816,525818-525828,525830-525861,525863-525866,525868-526090,526092-526112,526114-526116,526119-526121,526123-526149,526151-526153,526155-526156,526160-526165,526167-526186,526188-526193,526196-526197,526200-526665,526667-526682,526686-526690,526693,526695-526708,526710-526713,526715-526775,526777-526802,526804-526806,526808-527048,527051-527052,527054-527181,527183-527486,527488-527492,527494-527498,527500-527508,527510-527517,527519-527536,527538-527555,527559-527802,527804-527842,527844-527847,527849-527875,527877-527940,527942-527958,527960-527971,527973-528002,528004,528006-528423,528425-529232,529234-529245,529247-529296,529298-529634,529636-529658,529660-529665,529667-529668,529670-530033,530035-530036,530038-530040,530045-530046,530050-530051,530053-530431,530433-530436,530439-530440,530443,530445-530446,530448,530450-530682,530684,530687-530696,530698-530733,530735-530776,530778-530795,530799,530801-530811,530813-530818,530820-530837,530839-531436,531438-531455,531457,531459-531511,531514,531516,531519-531523,531525,531528-531858,531860-531864,531866-531907,531909-531916,531918-531936,531938-531988,531990-532001,532003-532371,532373-532465,532467-532727,532729-532765,532767-532785,532788-532790,532792-532793,532795-533064,533066-533074,533076,533080-533130,533132-533139,533142-533703,533705-533720,533722-533763,533766-533818,533820-533839,533841-533859,533862-534035,534037-534112,534114-534116,534118-534472,534474-534477,534479-534762,534764-534896,534898-534902,534904-535253,535255-535308,535310-535808,535810-535873,535875-536007,536009-536140,536142-536162,536165-536242,536244-536252,536254-536278,536280-536338,536340-536448,536450-536479,536481-536482,536484-536485,536487-536495,536497,536500-536505,536507-536561,536563-536570,536572,536574-536583,536586-536823,536825-537014,537016-537018,537020-537025,537027-537028,537030-537160,537162-537170,537172-537672,537674-537781,537783-537833,537836-537840,537842-537844,537846-537953,537955-538034,538036-538078,538080-538083,538085-538097,538099-538108,538110-538239,538241-538881,538883-538906,538908-538911,538913-538921,538923-539177,539179-539190,539192-539475,539477-539500,539502-539593,539595-539782,539784-539787,539789-540106,540108-540168,540170-540510,540512-541919,541921-544507,544509-544865,544867-545145,545147-547177,547179-547627 via svnmerge from https://svn.apache.org/repos/asf/incubator/qpid/branches/M2 ........ r539470 | ritchiem | 2007-05-18 14:50:59 +0100 (Fri, 18 May 2007) | 1 line QPID-401 Integrated python tests with maven tested on windows CMD.exe and linux FC5 ........ r539481 | ritchiem | 2007-05-18 15:30:06 +0100 (Fri, 18 May 2007) | 1 line QPID-401 Update to allow -Dskip-python-tests to disable python checking ........ r539484 | ritchiem | 2007-05-18 15:35:13 +0100 (Fri, 18 May 2007) | 1 line QPID-401 Update to allow -Dskip-python-tests to disable python checking ........ r541247 | rgodfrey | 2007-05-24 10:57:00 +0100 (Thu, 24 May 2007) | 1 line QPID-482 : Small performance tweaks ........ r542484 | rupertlssmith | 2007-05-29 11:52:29 +0100 (Tue, 29 May 2007) | 1 line Can now pass property to skip python tests, set in settings.xml ........ r542789 | ritchiem | 2007-05-30 11:09:28 +0100 (Wed, 30 May 2007) | 1 line Update to ensure fastinstall profile skips the broker python tests. ........ r543496 | rupertlssmith | 2007-06-01 15:33:07 +0100 (Fri, 01 Jun 2007) | 1 line QPID-402: FailoverException falling through to client. All blocking operations now wrapped in failover support wrappers. ........ r544109 | ritchiem | 2007-06-04 10:47:53 +0100 (Mon, 04 Jun 2007) | 7 lines Addition of a sustained test client. This is currently setup for running a pub/sub test. The test allows for multiple clients to connect and participate in testing the broker throughput. A single producer continually sends messages to a topic which the clients then send batched results back about. The producer uses the timings in the reports to update the rate at which it sends messages. Ideally reaching a steady state where all messages produced are received by everyone within a specified time frame. ........ r544422 | ritchiem | 2007-06-05 09:50:54 +0100 (Tue, 05 Jun 2007) | 1 line Added documentation on how to run the sustained tests. ........ r546096 | rupertlssmith | 2007-06-11 12:23:08 +0100 (Mon, 11 Jun 2007) | 1 line Set up top dir location and path to parent pom. Needed in preparation for deploy and release plugins. ........ r546190 | rupertlssmith | 2007-06-11 17:43:57 +0100 (Mon, 11 Jun 2007) | 1 line Removed log4j dependency from client. Using slf4j instead, end-user to supply logging implementation as desired. Log4j used for tests. ........ r546441 | rupertlssmith | 2007-06-12 10:52:29 +0100 (Tue, 12 Jun 2007) | 1 line QPID-465, now throws UnsupportedOperationException when sending to a null queue in QueueSender. ........ r546458 | ritchiem | 2007-06-12 12:41:17 +0100 (Tue, 12 Jun 2007) | 1 line Added repository info for running mvn rat:check ........ r547627 | ritchiem | 2007-06-15 12:21:40 +0100 (Fri, 15 Jun 2007) | 1 line QPID-511 adjusted to use the ReadWriteThreadModel rather than setting editing the filterChain directly which could cause problems when using an InVM transport due to the way the InVM transport alters the filter chain during a connect call. ........ git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@547730 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/qpid/AMQConnectionClosedException.java | 9 +- .../org/apache/qpid/AMQPInvalidClassException.java | 15 +- .../org/apache/qpid/codec/AMQCodecFactory.java | 4 +- .../org/apache/qpid/common/QpidProperties.java | 7 +- .../java/org/apache/qpid/framing/AMQDataBlock.java | 10 + .../apache/qpid/framing/AMQDataBlockDecoder.java | 46 ++- .../apache/qpid/framing/AMQDataBlockEncoder.java | 26 +- .../apache/qpid/framing/AMQMethodBodyFactory.java | 16 +- .../org/apache/qpid/framing/AMQShortString.java | 125 ++++---- .../qpid/framing/BasicContentHeaderProperties.java | 152 ++++++---- .../framing/CommonContentHeaderProperties.java | 5 - .../apache/qpid/framing/ContentBodyFactory.java | 11 +- .../qpid/framing/ContentHeaderBodyFactory.java | 14 +- .../org/apache/qpid/framing/EncodingUtils.java | 11 +- .../java/org/apache/qpid/framing/FieldTable.java | 187 ++++++------ .../qpid/framing/VersionSpecificRegistry.java | 23 +- .../java/org/apache/qpid/pool/PoolingFilter.java | 11 +- .../apache/qpid/protocol/AMQMethodListener.java | 4 +- .../java/org/apache/qpid/url/AMQBindingURL.java | 13 +- .../ConcurrentLinkedMessageQueueAtomicSize.java | 94 +++--- .../main/java/org/apache/qpid/util/FileUtils.java | 2 - .../org/apache/qpid/util/PrettyPrintingUtils.java | 2 + .../java/org/apache/qpid/util/PropertiesUtils.java | 7 +- .../qpid/framing/PropertyFieldTableTest.java | 326 ++++++++++----------- .../apache/qpid/util/CommandLineParserTest.java | 19 +- 25 files changed, 600 insertions(+), 539 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java index e95e805e9f..b2ce3c1b32 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionClosedException.java @@ -23,14 +23,17 @@ package org.apache.qpid; import org.apache.qpid.protocol.AMQConstant; /** - * AMQConnectionClosedException indicates that an operation cannot be performed becauase a connection has been closed. + * AMQConnectionClosedException indicates that a connection has been closed. + * + *

        This exception is really used as an event, in order that the method handler that raises it creates an event + * which is propagated to the io handler, in order to notify it of the connection closure. * *

        *
        CRC Card
        Responsibilities Collaborations - *
        Represents a failed operation on a closed conneciton. + *
        Represents a the closure of a connection. *
        * - * @todo Does this duplicate AMQConnectionException? + * @todo Should review where exceptions-as-events */ public class AMQConnectionClosedException extends AMQException { diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQPInvalidClassException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQPInvalidClassException.java index 883e13e5e6..a0574efa72 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQPInvalidClassException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQPInvalidClassException.java @@ -14,13 +14,22 @@ * "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. + * under the License. + * * - * */ package org.apache.qpid; - +/** + * AMQPInvalidClassException indicates an error when trying to store an illegally typed argument in a field table. + * + *

        + *
        CRC Card
        Responsibilities Collaborations + *
        Represents illegal argument type for field table values. + *
        + * + * @todo Could just re-use an exising exception like IllegalArgumentException or ClassCastException. + */ public class AMQPInvalidClassException extends RuntimeException { public AMQPInvalidClassException(String s) diff --git a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQCodecFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQCodecFactory.java index 4e3a46eb90..fa890d0ebb 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQCodecFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/codec/AMQCodecFactory.java @@ -37,10 +37,10 @@ import org.apache.mina.filter.codec.ProtocolEncoder; public class AMQCodecFactory implements ProtocolCodecFactory { /** Holds the protocol encoder. */ - private AMQEncoder _encoder = new AMQEncoder(); + private final AMQEncoder _encoder = new AMQEncoder(); /** Holds the protocol decoder. */ - private AMQDecoder _frameDecoder; + private final AMQDecoder _frameDecoder; /** * Creates a new codec factory, specifiying whether it is expected that the first frame of data should be an diff --git a/qpid/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java index 5a357557ca..2c783aeaa4 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/common/QpidProperties.java @@ -20,13 +20,14 @@ */ package org.apache.qpid.common; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Properties; -import org.apache.log4j.Logger; - /** * QpidProperties captures the project name, version number, and source code repository revision number from a properties * file which is generated as part of the build process. Normally, the name and version number are pulled from the module @@ -50,7 +51,7 @@ import org.apache.log4j.Logger; public class QpidProperties { /** Used for debugging purposes. */ - private static final Logger _logger = Logger.getLogger(QpidProperties.class); + private static final Logger _logger = LoggerFactory.getLogger(QpidProperties.class); /** The name of the version properties file to load from the class path. */ public static final String VERSION_RESOURCE = "qpidversion.properties"; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlock.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlock.java index 9155c4024f..903b5bfa7a 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlock.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlock.java @@ -40,4 +40,14 @@ public abstract class AMQDataBlock implements EncodableAMQDataBlock * @param buffer */ public abstract void writePayload(ByteBuffer buffer); + + public ByteBuffer toByteBuffer() + { + final ByteBuffer buffer = ByteBuffer.allocate((int)getSize()); + + writePayload(buffer); + buffer.flip(); + return buffer; + } + } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java index 9f36448986..82ffc60802 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java @@ -7,9 +7,9 @@ * 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 @@ -20,12 +20,15 @@ */ package org.apache.qpid.framing; -import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolDecoderOutput; + import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class AMQDataBlockDecoder { private static final String SESSION_METHOD_BODY_FACTORY = "QPID_SESSION_METHOD_BODY_FACTORY"; @@ -39,14 +42,10 @@ public class AMQDataBlockDecoder _bodiesSupported[HeartbeatBody.TYPE] = new HeartbeatBodyFactory(); } - - Logger _logger = Logger.getLogger(AMQDataBlockDecoder.class); - - + Logger _logger = LoggerFactory.getLogger(AMQDataBlockDecoder.class); public AMQDataBlockDecoder() - { - } + { } public boolean decodable(IoSession session, ByteBuffer in) throws AMQFrameDecodingException { @@ -56,26 +55,24 @@ public class AMQDataBlockDecoder { return false; } + in.skip(1 + 2); final long bodySize = in.getUnsignedInt(); - - return (remainingAfterAttributes >= bodySize); } - protected Object createAndPopulateFrame(IoSession session, ByteBuffer in) - throws AMQFrameDecodingException, AMQProtocolVersionException + throws AMQFrameDecodingException, AMQProtocolVersionException { final byte type = in.get(); BodyFactory bodyFactory; - if(type == AMQMethodBody.TYPE) + if (type == AMQMethodBody.TYPE) { bodyFactory = (BodyFactory) session.getAttribute(SESSION_METHOD_BODY_FACTORY); - if(bodyFactory == null) + if (bodyFactory == null) { AMQVersionAwareProtocolSession protocolSession = (AMQVersionAwareProtocolSession) session.getAttachment(); bodyFactory = new AMQMethodBodyFactory(protocolSession); @@ -89,10 +86,7 @@ public class AMQDataBlockDecoder bodyFactory = _bodiesSupported[type]; } - - - - if(bodyFactory == null) + if (bodyFactory == null) { throw new AMQFrameDecodingException(null, "Unsupported frame type: " + type, null); } @@ -101,25 +95,25 @@ public class AMQDataBlockDecoder final long bodySize = in.getUnsignedInt(); // bodySize can be zero - if (channel < 0 || bodySize < 0) + if ((channel < 0) || (bodySize < 0)) { - throw new AMQFrameDecodingException(null, "Undecodable frame: type = " + type + " channel = " + channel + - " bodySize = " + bodySize, null); + throw new AMQFrameDecodingException(null, "Undecodable frame: type = " + type + " channel = " + channel + + " bodySize = " + bodySize, null); } AMQFrame frame = new AMQFrame(in, channel, bodySize, bodyFactory); - byte marker = in.get(); if ((marker & 0xFF) != 0xCE) { - throw new AMQFrameDecodingException(null, "End of frame marker not found. Read " + marker + " length=" + bodySize + " type=" + type, null); + throw new AMQFrameDecodingException(null, "End of frame marker not found. Read " + marker + " length=" + bodySize + + " type=" + type, null); } + return frame; } - public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) - throws Exception + public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { out.write(createAndPopulateFrame(session, in)); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java index aedea6dd89..05fd2bb480 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java @@ -7,9 +7,9 @@ * 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 @@ -20,39 +20,37 @@ */ package org.apache.qpid.framing; -import java.util.Collections; -import java.util.Set; - -import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; import org.apache.mina.common.IoSession; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import org.apache.mina.filter.codec.demux.MessageEncoder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collections; +import java.util.Set; + public final class AMQDataBlockEncoder implements MessageEncoder { - private static final Logger _logger = Logger.getLogger(AMQDataBlockEncoder.class); + private static final Logger _logger = LoggerFactory.getLogger(AMQDataBlockEncoder.class); private final Set _messageTypes = Collections.singleton(EncodableAMQDataBlock.class); public AMQDataBlockEncoder() - { - } + { } public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { final AMQDataBlock frame = (AMQDataBlock) message; - int frameSize = (int)frame.getSize(); - final ByteBuffer buffer = ByteBuffer.allocate(frameSize); - //buffer.setAutoExpand(true); - frame.writePayload(buffer); + + final ByteBuffer buffer = frame.toByteBuffer(); if (_logger.isDebugEnabled()) { _logger.debug("Encoded frame byte-buffer is '" + EncodingUtils.convertToHexString(buffer) + "'"); } - buffer.flip(); out.write(buffer); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java index 5293c00379..cf85bdab31 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java @@ -7,9 +7,9 @@ * 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 @@ -20,16 +20,19 @@ */ package org.apache.qpid.framing; -import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; + import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class AMQMethodBodyFactory implements BodyFactory { - private static final Logger _log = Logger.getLogger(AMQMethodBodyFactory.class); + private static final Logger _log = LoggerFactory.getLogger(AMQMethodBodyFactory.class); private final AMQVersionAwareProtocolSession _protocolSession; - + public AMQMethodBodyFactory(AMQVersionAwareProtocolSession protocolSession) { _protocolSession = protocolSession; @@ -37,6 +40,7 @@ public class AMQMethodBodyFactory implements BodyFactory public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException { - return _protocolSession.getRegistry().get((short)in.getUnsignedShort(), (short)in.getUnsignedShort(), in, bodySize); + return _protocolSession.getRegistry().get((short) in.getUnsignedShort(), (short) in.getUnsignedShort(), in, + bodySize); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java index 3f6ef73781..ee7abd55c0 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java @@ -1,8 +1,10 @@ package org.apache.qpid.framing; -import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * A short string is a representation of an AMQ Short String * Short strings differ from the Java String class by being limited to on ASCII characters (0-127) @@ -11,11 +13,11 @@ import org.apache.mina.common.ByteBuffer; */ public final class AMQShortString implements CharSequence, Comparable { - private static final Logger _logger = Logger.getLogger(AMQShortString.class); + private static final Logger _logger = LoggerFactory.getLogger(AMQShortString.class); private final ByteBuffer _data; private int _hashCode; - final int _length; + private final int _length; private static final char[] EMPTY_CHAR_ARRAY = new char[0]; public AMQShortString(byte[] data) @@ -25,22 +27,25 @@ public final class AMQShortString implements CharSequence, Comparable n) return 1; + if (d < n) + { + return -1; + } + + if (d > n) + { + return 1; + } } - return length() == name.length() ? 0 : -1; + return (length() == name.length()) ? 0 : -1; } } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java index 4424fc1def..61f2f891e5 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java @@ -7,9 +7,9 @@ * 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 @@ -20,13 +20,14 @@ */ package org.apache.qpid.framing; -import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class BasicContentHeaderProperties implements CommonContentHeaderProperties { - private static final Logger _logger = Logger.getLogger(BasicContentHeaderProperties.class); + private static final Logger _logger = LoggerFactory.getLogger(BasicContentHeaderProperties.class); private static final AMQShortString ZERO_STRING = null; @@ -96,8 +97,7 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti private static final int CLUSTER_ID_MASK = 1 << 2; public BasicContentHeaderProperties() - { - } + { } public int getPropertyListSize() { @@ -113,30 +113,37 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti { size += EncodingUtils.encodedShortStringLength(_contentType); } + if ((_propertyFlags & ENCONDING_MASK) > 0) { size += EncodingUtils.encodedShortStringLength(_encoding); } + if ((_propertyFlags & HEADERS_MASK) > 0) { size += EncodingUtils.encodedFieldTableLength(_headers); } + if ((_propertyFlags & DELIVERY_MODE_MASK) > 0) { size += 1; } + if ((_propertyFlags & PROPRITY_MASK) > 0) { size += 1; } + if ((_propertyFlags & CORRELATION_ID_MASK) > 0) { size += EncodingUtils.encodedShortStringLength(_correlationId); } + if ((_propertyFlags & REPLY_TO_MASK) > 0) { size += EncodingUtils.encodedShortStringLength(_replyTo); } + if ((_propertyFlags & EXPIRATION_MASK) > 0) { if (_expiration == 0L) @@ -148,40 +155,48 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti size += EncodingUtils.encodedShortStringLength(_expiration); } } + if ((_propertyFlags & MESSAGE_ID_MASK) > 0) { size += EncodingUtils.encodedShortStringLength(_messageId); } + if ((_propertyFlags & TIMESTAMP_MASK) > 0) { size += 8; } + if ((_propertyFlags & TYPE_MASK) > 0) { size += EncodingUtils.encodedShortStringLength(_type); } + if ((_propertyFlags & USER_ID_MASK) > 0) { size += EncodingUtils.encodedShortStringLength(_userId); } + if ((_propertyFlags & APPLICATION_ID_MASK) > 0) { size += EncodingUtils.encodedShortStringLength(_appId); } + if ((_propertyFlags & CLUSTER_ID_MASK) > 0) { size += EncodingUtils.encodedShortStringLength(_clusterId); } + return size; } } private void clearEncodedForm() { - if (!_decoded && _encodedForm != null) + if (!_decoded && (_encodedForm != null)) { - //decode(); + // decode(); } + _encodedForm = null; } @@ -208,30 +223,37 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti { EncodingUtils.writeShortStringBytes(buffer, _contentType); } + if ((_propertyFlags & ENCONDING_MASK) != 0) { EncodingUtils.writeShortStringBytes(buffer, _encoding); } + if ((_propertyFlags & HEADERS_MASK) != 0) { EncodingUtils.writeFieldTableBytes(buffer, _headers); } + if ((_propertyFlags & DELIVERY_MODE_MASK) != 0) { buffer.put(_deliveryMode); } + if ((_propertyFlags & PROPRITY_MASK) != 0) { buffer.put(_priority); } + if ((_propertyFlags & CORRELATION_ID_MASK) != 0) { EncodingUtils.writeShortStringBytes(buffer, _correlationId); } + if ((_propertyFlags & REPLY_TO_MASK) != 0) { EncodingUtils.writeShortStringBytes(buffer, _replyTo); } + if ((_propertyFlags & EXPIRATION_MASK) != 0) { if (_expiration == 0L) @@ -243,26 +265,32 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti EncodingUtils.writeShortStringBytes(buffer, String.valueOf(_expiration)); } } + if ((_propertyFlags & MESSAGE_ID_MASK) != 0) { EncodingUtils.writeShortStringBytes(buffer, _messageId); } + if ((_propertyFlags & TIMESTAMP_MASK) != 0) { EncodingUtils.writeTimestamp(buffer, _timestamp); } + if ((_propertyFlags & TYPE_MASK) != 0) { EncodingUtils.writeShortStringBytes(buffer, _type); } + if ((_propertyFlags & USER_ID_MASK) != 0) { EncodingUtils.writeShortStringBytes(buffer, _userId); } + if ((_propertyFlags & APPLICATION_ID_MASK) != 0) { EncodingUtils.writeShortStringBytes(buffer, _appId); } + if ((_propertyFlags & CLUSTER_ID_MASK) != 0) { EncodingUtils.writeShortStringBytes(buffer, _clusterId); @@ -270,8 +298,7 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti } } - public void populatePropertiesFromBuffer(ByteBuffer buffer, int propertyFlags, int size) - throws AMQFrameDecodingException + public void populatePropertiesFromBuffer(ByteBuffer buffer, int propertyFlags, int size) throws AMQFrameDecodingException { _propertyFlags = propertyFlags; @@ -279,6 +306,7 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti { _logger.debug("Property flags: " + _propertyFlags); } + decode(buffer); /*_encodedForm = new byte[size]; buffer.get(_encodedForm, 0, size); @@ -289,7 +317,7 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti private void decode(ByteBuffer buffer) { - //ByteBuffer buffer = ByteBuffer.wrap(_encodedForm); + // ByteBuffer buffer = ByteBuffer.wrap(_encodedForm); int pos = buffer.position(); try { @@ -297,54 +325,67 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti { _contentType = EncodingUtils.readAMQShortString(buffer); } + if ((_propertyFlags & ENCONDING_MASK) != 0) { _encoding = EncodingUtils.readAMQShortString(buffer); } + if ((_propertyFlags & HEADERS_MASK) != 0) { _headers = EncodingUtils.readFieldTable(buffer); } + if ((_propertyFlags & DELIVERY_MODE_MASK) != 0) { _deliveryMode = buffer.get(); } + if ((_propertyFlags & PROPRITY_MASK) != 0) { _priority = buffer.get(); } + if ((_propertyFlags & CORRELATION_ID_MASK) != 0) { _correlationId = EncodingUtils.readAMQShortString(buffer); } + if ((_propertyFlags & REPLY_TO_MASK) != 0) { _replyTo = EncodingUtils.readAMQShortString(buffer); } + if ((_propertyFlags & EXPIRATION_MASK) != 0) { _expiration = EncodingUtils.readLongAsShortString(buffer); } + if ((_propertyFlags & MESSAGE_ID_MASK) != 0) { _messageId = EncodingUtils.readAMQShortString(buffer); } + if ((_propertyFlags & TIMESTAMP_MASK) != 0) { _timestamp = EncodingUtils.readTimestamp(buffer); } + if ((_propertyFlags & TYPE_MASK) != 0) { _type = EncodingUtils.readAMQShortString(buffer); } + if ((_propertyFlags & USER_ID_MASK) != 0) { _userId = EncodingUtils.readAMQShortString(buffer); } + if ((_propertyFlags & APPLICATION_ID_MASK) != 0) { _appId = EncodingUtils.readAMQShortString(buffer); } + if ((_propertyFlags & CLUSTER_ID_MASK) != 0) { _clusterId = EncodingUtils.readAMQShortString(buffer); @@ -367,7 +408,6 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti _decoded = true; } - private void decodeUpToHeaders() { ByteBuffer buffer = ByteBuffer.wrap(_encodedForm); @@ -378,16 +418,19 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti byte length = buffer.get(); buffer.skip(length); } + if ((_propertyFlags & ENCONDING_MASK) != 0) { byte length = buffer.get(); buffer.skip(length); } + if ((_propertyFlags & HEADERS_MASK) != 0) { _headers = EncodingUtils.readFieldTable(buffer); } + _decodedHeaders = true; } catch (AMQFrameDecodingException e) @@ -412,7 +455,7 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti { if (!_decoded) { - //decode(); + // decode(); } } @@ -435,14 +478,15 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti public AMQShortString getContentType() { decodeContentTypeIfNecessary(); + return _contentType; } - public String getContentTypeAsString() { decodeContentTypeIfNecessary(); - return _contentType == null ? null : _contentType.toString(); + + return (_contentType == null) ? null : _contentType.toString(); } public void setContentType(AMQShortString contentType) @@ -452,21 +496,21 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti _contentType = contentType; } - public void setContentType(String contentType) { - setContentType(contentType == null ? null : new AMQShortString(contentType)); + setContentType((contentType == null) ? null : new AMQShortString(contentType)); } public String getEncodingAsString() { - return getEncoding() == null ? null : getEncoding().toString(); + return (getEncoding() == null) ? null : getEncoding().toString(); } public AMQShortString getEncoding() { decodeIfNecessary(); + return _encoding; } @@ -474,7 +518,7 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti { clearEncodedForm(); _propertyFlags |= ENCONDING_MASK; - _encoding = encoding == null ? null : new AMQShortString(encoding); + _encoding = (encoding == null) ? null : new AMQShortString(encoding); } public void setEncoding(AMQShortString encoding) @@ -484,7 +528,6 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti _encoding = encoding; } - public FieldTable getHeaders() { decodeHeadersIfNecessary(); @@ -504,10 +547,10 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti _headers = headers; } - public byte getDeliveryMode() { decodeIfNecessary(); + return _deliveryMode; } @@ -521,6 +564,7 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti public byte getPriority() { decodeIfNecessary(); + return _priority; } @@ -534,18 +578,20 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti public AMQShortString getCorrelationId() { decodeIfNecessary(); + return _correlationId; } public String getCorrelationIdAsString() { decodeIfNecessary(); - return _correlationId == null ? null : _correlationId.toString(); + + return (_correlationId == null) ? null : _correlationId.toString(); } public void setCorrelationId(String correlationId) { - setCorrelationId(correlationId == null ? null : new AMQShortString(correlationId)); + setCorrelationId((correlationId == null) ? null : new AMQShortString(correlationId)); } public void setCorrelationId(AMQShortString correlationId) @@ -558,19 +604,20 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti public String getReplyToAsString() { decodeIfNecessary(); - return _replyTo == null ? null : _replyTo.toString(); + + return (_replyTo == null) ? null : _replyTo.toString(); } public AMQShortString getReplyTo() { decodeIfNecessary(); + return _replyTo; } - public void setReplyTo(String replyTo) { - setReplyTo(replyTo == null ? null : new AMQShortString(replyTo)); + setReplyTo((replyTo == null) ? null : new AMQShortString(replyTo)); } public void setReplyTo(AMQShortString replyTo) @@ -584,6 +631,7 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti public long getExpiration() { decodeIfNecessary(); + return _expiration; } @@ -594,24 +642,25 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti _expiration = expiration; } - public AMQShortString getMessageId() { decodeIfNecessary(); + return _messageId; } public String getMessageIdAsString() { decodeIfNecessary(); - return _messageId == null ? null : _messageId.toString(); + + return (_messageId == null) ? null : _messageId.toString(); } public void setMessageId(String messageId) { clearEncodedForm(); _propertyFlags |= MESSAGE_ID_MASK; - _messageId = messageId == null ? null : new AMQShortString(messageId); + _messageId = (messageId == null) ? null : new AMQShortString(messageId); } public void setMessageId(AMQShortString messageId) @@ -621,10 +670,10 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti _messageId = messageId; } - public long getTimestamp() { decodeIfNecessary(); + return _timestamp; } @@ -638,20 +687,20 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti public String getTypeAsString() { decodeIfNecessary(); - return _type == null ? null : _type.toString(); - } + return (_type == null) ? null : _type.toString(); + } public AMQShortString getType() { decodeIfNecessary(); + return _type; } - public void setType(String type) { - setType(type == null ? null : new AMQShortString(type)); + setType((type == null) ? null : new AMQShortString(type)); } public void setType(AMQShortString type) @@ -664,18 +713,20 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti public String getUserIdAsString() { decodeIfNecessary(); - return _userId == null ? null : _userId.toString(); + + return (_userId == null) ? null : _userId.toString(); } public AMQShortString getUserId() { decodeIfNecessary(); + return _userId; } public void setUserId(String userId) { - setUserId(userId == null ? null : new AMQShortString(userId)); + setUserId((userId == null) ? null : new AMQShortString(userId)); } public void setUserId(AMQShortString userId) @@ -688,18 +739,20 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti public String getAppIdAsString() { decodeIfNecessary(); - return _appId == null ? null : _appId.toString(); + + return (_appId == null) ? null : _appId.toString(); } public AMQShortString getAppId() { decodeIfNecessary(); + return _appId; } public void setAppId(String appId) { - setAppId(appId == null ? null : new AMQShortString(appId)); + setAppId((appId == null) ? null : new AMQShortString(appId)); } public void setAppId(AMQShortString appId) @@ -712,18 +765,20 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti public String getClusterIdAsString() { decodeIfNecessary(); - return _clusterId == null ? null : _clusterId.toString(); + + return (_clusterId == null) ? null : _clusterId.toString(); } public AMQShortString getClusterId() { decodeIfNecessary(); + return _clusterId; } public void setClusterId(String clusterId) { - setClusterId(clusterId == null ? null : new AMQShortString(clusterId)); + setClusterId((clusterId == null) ? null : new AMQShortString(clusterId)); } public void setClusterId(AMQShortString clusterId) @@ -735,19 +790,10 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti public String toString() { - return "reply-to = " + _replyTo + - ",propertyFlags = " + _propertyFlags + - ",ApplicationID = " + _appId + - ",ClusterID = " + _clusterId + - ",UserId = " + _userId + - ",JMSMessageID = " + _messageId + - ",JMSCorrelationID = " + _correlationId + - ",JMSDeliveryMode = " + _deliveryMode + - ",JMSExpiration = " + _expiration + - ",JMSPriority = " + _priority + - ",JMSTimestamp = " + _timestamp + - ",JMSType = " + _type; + return "reply-to = " + _replyTo + ",propertyFlags = " + _propertyFlags + ",ApplicationID = " + _appId + + ",ClusterID = " + _clusterId + ",UserId = " + _userId + ",JMSMessageID = " + _messageId + + ",JMSCorrelationID = " + _correlationId + ",JMSDeliveryMode = " + _deliveryMode + ",JMSExpiration = " + + _expiration + ",JMSPriority = " + _priority + ",JMSTimestamp = " + _timestamp + ",JMSType = " + _type; } - } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java index 1641cbf4e8..66c5e19633 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java @@ -1,12 +1,7 @@ package org.apache.qpid.framing; -import org.apache.mina.common.ByteBuffer; - -import org.apache.log4j.Logger; - public interface CommonContentHeaderProperties extends ContentHeaderProperties { - AMQShortString getContentType(); void setContentType(AMQShortString contentType); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java index 5636229d53..c42995d148 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentBodyFactory.java @@ -7,9 +7,9 @@ * 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 @@ -20,12 +20,14 @@ */ package org.apache.qpid.framing; -import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class ContentBodyFactory implements BodyFactory { - private static final Logger _log = Logger.getLogger(AMQMethodBodyFactory.class); + private static final Logger _log = LoggerFactory.getLogger(AMQMethodBodyFactory.class); private static final ContentBodyFactory _instance = new ContentBodyFactory(); @@ -44,4 +46,3 @@ public class ContentBodyFactory implements BodyFactory return new ContentBody(in, bodySize); } } - diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java index 818fc9cf0c..8d5e2f9fb4 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/ContentHeaderBodyFactory.java @@ -7,9 +7,9 @@ * 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 @@ -20,12 +20,14 @@ */ package org.apache.qpid.framing; -import org.apache.log4j.Logger; import org.apache.mina.common.ByteBuffer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class ContentHeaderBodyFactory implements BodyFactory { - private static final Logger _log = Logger.getLogger(AMQMethodBodyFactory.class); + private static final Logger _log = LoggerFactory.getLogger(AMQMethodBodyFactory.class); private static final ContentHeaderBodyFactory _instance = new ContentHeaderBodyFactory(); @@ -43,8 +45,6 @@ public class ContentHeaderBodyFactory implements BodyFactory { // all content headers are the same - it is only the properties that differ. // the content header body further delegates construction of properties - return new ContentHeaderBody(in,bodySize); + return new ContentHeaderBody(in, bodySize); } - - } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java index 62fefdc2fc..ccba8bd41e 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java @@ -20,15 +20,16 @@ */ package org.apache.qpid.framing; -import java.nio.charset.Charset; +import org.apache.mina.common.ByteBuffer; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import org.apache.mina.common.ByteBuffer; +import java.nio.charset.Charset; public class EncodingUtils { - private static final Logger _logger = Logger.getLogger(EncodingUtils.class); + private static final Logger _logger = LoggerFactory.getLogger(EncodingUtils.class); private static final String STRING_ENCODING = "iso8859-15"; @@ -1024,6 +1025,4 @@ public class EncodingUtils return l; } - - } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java index 631a3ae149..2fe96b722b 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java @@ -20,6 +20,14 @@ */ package org.apache.qpid.framing; +import org.apache.mina.common.ByteBuffer; + +import org.apache.qpid.AMQPInvalidClassException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.math.BigDecimal; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; @@ -27,16 +35,13 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; -import java.math.BigDecimal; -import org.apache.log4j.Logger; -import org.apache.mina.common.ByteBuffer; -import org.apache.qpid.AMQPInvalidClassException; - -//extends FieldTable +// extends FieldTable public class FieldTable { - private static final Logger _logger = Logger.getLogger(FieldTable.class); + private static final Logger _logger = LoggerFactory.getLogger(FieldTable.class); + private static final String STRICT_AMQP = "STRICT_AMQP"; + private final boolean _strictAMQP = Boolean.valueOf(System.getProperty(STRICT_AMQP, "false")); private ByteBuffer _encodedForm; private LinkedHashMap _properties; @@ -47,9 +52,9 @@ public class FieldTable public FieldTable() { super(); -// _encodedForm = ByteBuffer.allocate(INITIAL_ENCODED_FORM_SIZE); -// _encodedForm.setAutoExpand(true); -// _encodedForm.limit(0); + // _encodedForm = ByteBuffer.allocate(INITIAL_ENCODED_FORM_SIZE); + // _encodedForm.setAutoExpand(true); + // _encodedForm.limit(0); } /** @@ -69,7 +74,6 @@ public class FieldTable buffer.skip((int) length); } - private AMQTypedValue getProperty(AMQShortString string) { checkPropertyName(string); @@ -112,7 +116,6 @@ public class FieldTable } } - private AMQTypedValue setProperty(AMQShortString key, AMQTypedValue val) { checkPropertyName(key); @@ -126,7 +129,7 @@ public class FieldTable return removeKey(key); } } - else if (_encodedForm != null && val != null) + else if ((_encodedForm != null) && (val != null)) { EncodingUtils.writeShortStringBytes(_encodedForm, key); val.writeToBuffer(_encodedForm); @@ -137,7 +140,6 @@ public class FieldTable return null; } - AMQTypedValue oldVal = _properties.put(key, val); if (oldVal != null) { @@ -147,6 +149,7 @@ public class FieldTable { _encodedSize += EncodingUtils.encodedShortStringLength(key) + 1; } + _encodedSize += val.getEncodingSize(); return oldVal; @@ -158,7 +161,7 @@ public class FieldTable { if (_properties == null) { - if (_encodedForm == null || _encodedSize == 0) + if ((_encodedForm == null) || (_encodedSize == 0)) { _properties = new LinkedHashMap(); } @@ -171,7 +174,6 @@ public class FieldTable } } - public Boolean getBoolean(String string) { return getBoolean(new AMQShortString(string)); @@ -180,7 +182,7 @@ public class FieldTable public Boolean getBoolean(AMQShortString string) { AMQTypedValue value = getProperty(string); - if (value != null && (value.getType() == AMQType.BOOLEAN)) + if ((value != null) && (value.getType() == AMQType.BOOLEAN)) { return (Boolean) value.getValue(); } @@ -190,7 +192,6 @@ public class FieldTable } } - public Byte getByte(String string) { return getByte(new AMQShortString(string)); @@ -199,7 +200,7 @@ public class FieldTable public Byte getByte(AMQShortString string) { AMQTypedValue value = getProperty(string); - if (value != null && (value.getType() == AMQType.BYTE)) + if ((value != null) && (value.getType() == AMQType.BYTE)) { return (Byte) value.getValue(); } @@ -217,7 +218,7 @@ public class FieldTable public Short getShort(AMQShortString string) { AMQTypedValue value = getProperty(string); - if (value != null && (value.getType() == AMQType.SHORT)) + if ((value != null) && (value.getType() == AMQType.SHORT)) { return (Short) value.getValue(); } @@ -235,7 +236,7 @@ public class FieldTable public Integer getInteger(AMQShortString string) { AMQTypedValue value = getProperty(string); - if (value != null && (value.getType() == AMQType.INT)) + if ((value != null) && (value.getType() == AMQType.INT)) { return (Integer) value.getValue(); } @@ -253,7 +254,7 @@ public class FieldTable public Long getLong(AMQShortString string) { AMQTypedValue value = getProperty(string); - if (value != null && (value.getType() == AMQType.LONG)) + if ((value != null) && (value.getType() == AMQType.LONG)) { return (Long) value.getValue(); } @@ -271,7 +272,7 @@ public class FieldTable public Float getFloat(AMQShortString string) { AMQTypedValue value = getProperty(string); - if (value != null && (value.getType() == AMQType.FLOAT)) + if ((value != null) && (value.getType() == AMQType.FLOAT)) { return (Float) value.getValue(); } @@ -289,7 +290,7 @@ public class FieldTable public Double getDouble(AMQShortString string) { AMQTypedValue value = getProperty(string); - if (value != null && (value.getType() == AMQType.DOUBLE)) + if ((value != null) && (value.getType() == AMQType.DOUBLE)) { return (Double) value.getValue(); } @@ -307,12 +308,10 @@ public class FieldTable public String getString(AMQShortString string) { AMQTypedValue value = getProperty(string); - if ((value != null) && ((value.getType() == AMQType.WIDE_STRING) || - (value.getType() == AMQType.ASCII_STRING))) + if ((value != null) && ((value.getType() == AMQType.WIDE_STRING) || (value.getType() == AMQType.ASCII_STRING))) { return (String) value.getValue(); } - else if ((value != null) && (value.getValue() != null) && !(value.getValue() instanceof byte[])) { return String.valueOf(value.getValue()); @@ -332,7 +331,7 @@ public class FieldTable public Character getCharacter(AMQShortString string) { AMQTypedValue value = getProperty(string); - if (value != null && (value.getType() == AMQType.ASCII_CHARACTER)) + if ((value != null) && (value.getType() == AMQType.ASCII_CHARACTER)) { return (Character) value.getValue(); } @@ -350,7 +349,7 @@ public class FieldTable public byte[] getBytes(AMQShortString string) { AMQTypedValue value = getProperty(string); - if (value != null && (value.getType() == AMQType.BINARY)) + if ((value != null) && (value.getType() == AMQType.BINARY)) { return (byte[]) value.getValue(); } @@ -382,7 +381,7 @@ public class FieldTable public Long getTimestamp(AMQShortString name) { AMQTypedValue value = getProperty(name); - if ((value != null) && ((value.getType() == AMQType.TIMESTAMP))) + if ((value != null) && (value.getType() == AMQType.TIMESTAMP)) { return (Long) value.getValue(); } @@ -395,7 +394,7 @@ public class FieldTable public BigDecimal getDecimal(AMQShortString propertyName) { AMQTypedValue value = getProperty(propertyName); - if ((value != null) && ((value.getType() == AMQType.DECIMAL))) + if ((value != null) && (value.getType() == AMQType.DECIMAL)) { return (BigDecimal) value.getValue(); } @@ -405,76 +404,73 @@ public class FieldTable } } - // ************ Setters - public Object setBoolean(String string, boolean b) + public Object setBoolean(String string, Boolean b) { return setBoolean(new AMQShortString(string), b); } - public Object setBoolean(AMQShortString string, boolean b) + public Object setBoolean(AMQShortString string, Boolean b) { return setProperty(string, AMQType.BOOLEAN.asTypedValue(b)); } - public Object setByte(String string, byte b) + public Object setByte(String string, Byte b) { return setByte(new AMQShortString(string), b); } - public Object setByte(AMQShortString string, byte b) + public Object setByte(AMQShortString string, Byte b) { return setProperty(string, AMQType.BYTE.asTypedValue(b)); } - public Object setShort(String string, short i) + public Object setShort(String string, Short i) { return setShort(new AMQShortString(string), i); } - public Object setShort(AMQShortString string, short i) + public Object setShort(AMQShortString string, Short i) { return setProperty(string, AMQType.SHORT.asTypedValue(i)); } - - public Object setInteger(String string, int i) + public Object setInteger(String string, Integer i) { return setInteger(new AMQShortString(string), i); } - public Object setInteger(AMQShortString string, int i) + public Object setInteger(AMQShortString string, Integer i) { return setProperty(string, AMQType.INT.asTypedValue(i)); } - - public Object setLong(String string, long l) + public Object setLong(String string, Long l) { return setLong(new AMQShortString(string), l); } - public Object setLong(AMQShortString string, long l) + public Object setLong(AMQShortString string, Long l) { return setProperty(string, AMQType.LONG.asTypedValue(l)); } - public Object setFloat(String string, float f) + public Object setFloat(String string, Float f) { return setFloat(new AMQShortString(string), f); } - public Object setFloat(AMQShortString string, float v) + public Object setFloat(AMQShortString string, Float v) { return setProperty(string, AMQType.FLOAT.asTypedValue(v)); } - public Object setDouble(String string, double d) + public Object setDouble(String string, Double d) { return setDouble(new AMQShortString(string), d); } - public Object setDouble(AMQShortString string, double v) + public Object setDouble(AMQShortString string, Double v) { return setProperty(string, AMQType.DOUBLE.asTypedValue(v)); } @@ -537,6 +533,7 @@ public class FieldTable { byte[] newBytes = new byte[length]; System.arraycopy(bytes, start, newBytes, 0, length); + return setBytes(string, bytes); } @@ -560,7 +557,7 @@ public class FieldTable if (decimal.scale() > Byte.MAX_VALUE) { throw new UnsupportedOperationException("AMQP doesnot support decimal scales larger than " + Byte.MAX_VALUE); - } + } return setProperty(string, AMQType.DECIMAL.asTypedValue(decimal)); } @@ -619,6 +616,7 @@ public class FieldTable public boolean isNullStringValue(String name) { AMQTypedValue value = getProperty(new AMQShortString(name)); + return (value != null) && (value.getType() == AMQType.VOID); } @@ -643,6 +641,7 @@ public class FieldTable { checkPropertyName(propertyName); initMapIfNecessary(); + return _properties.containsKey(propertyName); } @@ -654,6 +653,7 @@ public class FieldTable public String toString() { initMapIfNecessary(); + return _properties.toString(); } @@ -668,20 +668,23 @@ public class FieldTable throw new IllegalArgumentException("Property name must not be the empty string"); } - checkIdentiferFormat(propertyName); + if (_strictAMQP) + { + checkIdentiferFormat(propertyName); + } } protected static void checkIdentiferFormat(AMQShortString propertyName) { -// AMQP Spec: 4.2.5.5 Field Tables -// Guidelines for implementers: -// * Field names MUST start with a letter, '$' or '#' and may continue with -// letters, '$' or '#', digits, or underlines, to a maximum length of 128 -// characters. -// * The server SHOULD validate field names and upon receiving an invalid -// field name, it SHOULD signal a connection exception with reply code -// 503 (syntax error). Conformance test: amq_wlp_table_01. -// * A peer MUST handle duplicate fields by using only the first instance. + // AMQP Spec: 4.2.5.5 Field Tables + // Guidelines for implementers: + // * Field names MUST start with a letter, '$' or '#' and may continue with + // letters, '$' or '#', digits, or underlines, to a maximum length of 128 + // characters. + // * The server SHOULD validate field names and upon receiving an invalid + // field name, it SHOULD signal a connection exception with reply code + // 503 (syntax error). Conformance test: amq_wlp_table_01. + // * A peer MUST handle duplicate fields by using only the first instance. // AMQP length limit if (propertyName.length() > 128) @@ -690,12 +693,11 @@ public class FieldTable } // AMQ start character - if (!(Character.isLetter(propertyName.charAt(0)) - || propertyName.charAt(0) == '$' - || propertyName.charAt(0) == '#' - || propertyName.charAt(0) == '_')) // Not official AMQP added for JMS. + if (!(Character.isLetter(propertyName.charAt(0)) || (propertyName.charAt(0) == '$') + || (propertyName.charAt(0) == '#') || (propertyName.charAt(0) == '_'))) // Not official AMQP added for JMS. { - throw new IllegalArgumentException("Identifier '" + propertyName + "' does not start with a valid AMQP start character"); + throw new IllegalArgumentException("Identifier '" + propertyName + + "' does not start with a valid AMQP start character"); } } @@ -708,7 +710,7 @@ public class FieldTable if (trace) { _logger.trace("FieldTable::writeToBuffer: Writing encoded length of " + getEncodedSize() + "..."); - _logger.trace(_properties); + _logger.trace(_properties.toString()); } EncodingUtils.writeUnsignedInteger(buffer, getEncodedSize()); @@ -727,6 +729,7 @@ public class FieldTable buffer.flip(); buffer.get(result); buffer.release(); + return result; } @@ -749,6 +752,7 @@ public class FieldTable } } + _encodedSize = encodedSize; } @@ -760,7 +764,6 @@ public class FieldTable recalculateEncodedSize(); } - public static interface FieldTableElementProcessor { public boolean processElement(String propertyName, AMQTypedValue value); @@ -782,15 +785,15 @@ public class FieldTable } } } - return processor.getResult(); + return processor.getResult(); } - public int size() { initMapIfNecessary(); + return _properties.size(); } @@ -803,6 +806,7 @@ public class FieldTable public boolean containsKey(AMQShortString key) { initMapIfNecessary(); + return _properties.containsKey(key); } @@ -819,23 +823,21 @@ public class FieldTable { keys.add(key.toString()); } + return keys; } - public Object get(AMQShortString key) { return getObject(key); } - public Object put(AMQShortString key, Object value) { return setObject(key, value); } - public Object remove(String key) { @@ -846,10 +848,10 @@ public class FieldTable public Object remove(AMQShortString key) { AMQTypedValue val = removeKey(key); - return val == null ? null : val.getValue(); - } + return (val == null) ? null : val.getValue(); + } public AMQTypedValue removeKey(AMQShortString key) { @@ -865,12 +867,12 @@ public class FieldTable _encodedSize -= EncodingUtils.encodedShortStringLength(key); _encodedSize--; _encodedSize -= value.getEncodingSize(); + return value; } } - public void clear() { initMapIfNecessary(); @@ -882,6 +884,7 @@ public class FieldTable public Set keySet() { initMapIfNecessary(); + return _properties.keySet(); } @@ -895,17 +898,17 @@ public class FieldTable { _encodedForm.flip(); } -// _encodedForm.limit((int)getEncodedSize()); + // _encodedForm.limit((int)getEncodedSize()); + buffer.put(_encodedForm); } else if (_properties != null) { final Iterator> it = _properties.entrySet().iterator(); - //If there are values then write out the encoded Size... could check _encodedSize != 0 + // If there are values then write out the encoded Size... could check _encodedSize != 0 // write out the total length, which we have kept up to date as data is added - while (it.hasNext()) { final Map.Entry me = it.next(); @@ -913,14 +916,12 @@ public class FieldTable { if (_logger.isTraceEnabled()) { - _logger.trace("Writing Property:" + me.getKey() + - " Type:" + me.getValue().getType() + - " Value:" + me.getValue().getValue()); - _logger.trace("Buffer Position:" + buffer.position() + - " Remaining:" + buffer.remaining()); + _logger.trace("Writing Property:" + me.getKey() + " Type:" + me.getValue().getType() + " Value:" + + me.getValue().getValue()); + _logger.trace("Buffer Position:" + buffer.position() + " Remaining:" + buffer.remaining()); } - //Write the actual parameter name + // Write the actual parameter name EncodingUtils.writeShortStringBytes(buffer, me.getKey()); me.getValue().writeToBuffer(buffer); } @@ -929,19 +930,17 @@ public class FieldTable if (_logger.isTraceEnabled()) { _logger.trace("Exception thrown:" + e); - _logger.trace("Writing Property:" + me.getKey() + - " Type:" + me.getValue().getType() + - " Value:" + me.getValue().getValue()); - _logger.trace("Buffer Position:" + buffer.position() + - " Remaining:" + buffer.remaining()); + _logger.trace("Writing Property:" + me.getKey() + " Type:" + me.getValue().getType() + " Value:" + + me.getValue().getValue()); + _logger.trace("Buffer Position:" + buffer.position() + " Remaining:" + buffer.remaining()); } + throw new RuntimeException(e); } } } } - private void setFromBuffer(ByteBuffer buffer, long length) throws AMQFrameDecodingException { @@ -961,17 +960,17 @@ public class FieldTable if (trace) { - _logger.trace("FieldTable::PropFieldTable(buffer," + length + "): Read type '" + value.getType() + "', key '" + key + "', value '" + value.getValue() + "'"); + _logger.trace("FieldTable::PropFieldTable(buffer," + length + "): Read type '" + value.getType() + + "', key '" + key + "', value '" + value.getValue() + "'"); } - _properties.put(key, value); - } while (buffer.remaining() > expectedRemaining); } + _encodedSize = length; if (trace) @@ -983,20 +982,22 @@ public class FieldTable public int hashCode() { initMapIfNecessary(); + return _properties.hashCode(); } - public boolean equals(Object o) { if (o == this) { return true; } + if (o == null) { return false; } + if (!(o instanceof FieldTable)) { return false; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java index 916b476185..6006e9793c 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java @@ -20,15 +20,16 @@ */ package org.apache.qpid.framing; -import org.apache.log4j.Logger; - import org.apache.mina.common.ByteBuffer; import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class VersionSpecificRegistry { - private static final Logger _log = Logger.getLogger(VersionSpecificRegistry.class); + private static final Logger _log = LoggerFactory.getLogger(VersionSpecificRegistry.class); private final byte _protocolMajorVersion; private final byte _protocolMinorVersion; @@ -152,16 +153,17 @@ public class VersionSpecificRegistry } catch (NullPointerException e) { - throw new AMQFrameDecodingException(null, "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion - + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + " method " + methodID + ".", e); + throw new AMQFrameDecodingException(null, "Class " + classID + " unknown in AMQP version " + + _protocolMajorVersion + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + + " method " + methodID + ".", e); } catch (IndexOutOfBoundsException e) { if (classID >= _registry.length) { - throw new AMQFrameDecodingException(null, "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion - + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + " method " + methodID - + ".", e); + throw new AMQFrameDecodingException(null, "Class " + classID + " unknown in AMQP version " + + _protocolMajorVersion + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + + " method " + methodID + ".", e); } else @@ -175,8 +177,9 @@ public class VersionSpecificRegistry if (bodyFactory == null) { - throw new AMQFrameDecodingException(null, "Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion - + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + " method " + methodID + ".", null); + throw new AMQFrameDecodingException(null, "Method " + methodID + " unknown in AMQP version " + + _protocolMajorVersion + "-" + _protocolMinorVersion + " (while trying to decode class " + classID + + " method " + methodID + ".", null); } return bodyFactory.newInstance(_protocolMajorVersion, _protocolMinorVersion, classID, methodID, in, size); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java index 7f6b1d40ac..d0dfb1adcf 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java @@ -22,12 +22,15 @@ package org.apache.qpid.pool; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import org.apache.log4j.Logger; import org.apache.mina.common.IdleStatus; import org.apache.mina.common.IoFilterAdapter; import org.apache.mina.common.IoSession; import org.apache.qpid.pool.Event.CloseEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + /** * PoolingFilter, is a no-op pass through filter that hands all events down the Mina filter chain by default. As it * adds no behaviour by default to the filter chain, it is abstract. @@ -78,7 +81,7 @@ import org.apache.qpid.pool.Event.CloseEvent; public abstract class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionHandler { /** Used for debugging purposes. */ - private static final Logger _logger = Logger.getLogger(PoolingFilter.class); + private static final Logger _logger = LoggerFactory.getLogger(PoolingFilter.class); /** Holds a mapping from Mina sessions to batched jobs for execution. */ private final ConcurrentMap _jobs = new ConcurrentHashMap(); @@ -135,7 +138,7 @@ public abstract class PoolingFilter extends IoFilterAdapter implements Job.JobCo */ public void init() { - _logger.info("Init called on PoolingFilter " + toString()); + _logger.debug("Init called on PoolingFilter " + toString()); // Called when the filter is initialised in the chain. If the reference count is // zero this acquire will initialise the pool. @@ -147,7 +150,7 @@ public abstract class PoolingFilter extends IoFilterAdapter implements Job.JobCo */ public void destroy() { - _logger.info("Destroy called on PoolingFilter " + toString()); + _logger.debug("Destroy called on PoolingFilter " + toString()); // When the reference count gets to zero we release the executor service. _poolReference.releaseExecutorService(); diff --git a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java index 808272e9ec..2fbeeda1d4 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/protocol/AMQMethodListener.java @@ -28,7 +28,7 @@ import org.apache.qpid.framing.AMQMethodBody; * *

        An event listener may be associated with a particular context, usually an AMQP channel, and in addition to * receiving method events will be notified of errors on that context. This enables listeners to perform any clean - * up that they need to do before the context is closed. + * up that they need to do before the context is closed or retried. * *

        *
        CRC Card
        Responsibilities @@ -64,8 +64,6 @@ public interface AMQMethodListener * any necessary clean-up for the context. * * @param e The underlying exception that is the source of the error. - * - * @todo Consider narrowing the exception, or wrapping it. */ void error(Exception e); } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java b/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java index 353c0d39c2..1774fa1194 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java @@ -20,18 +20,19 @@ */ package org.apache.qpid.url; +import org.apache.qpid.exchange.ExchangeDefaults; +import org.apache.qpid.framing.AMQShortString; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; -import org.apache.log4j.Logger; - -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; - public class AMQBindingURL implements BindingURL { - private static final Logger _logger = Logger.getLogger(AMQBindingURL.class); + private static final Logger _logger = LoggerFactory.getLogger(AMQBindingURL.class); String _url; AMQShortString _exchangeClass; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java b/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java index 4636f44795..461cf9591d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java @@ -14,22 +14,23 @@ * "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. + * under the License. + * * - * */ package org.apache.qpid.util; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Queue; import java.util.Collection; import java.util.Iterator; +import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQueueAtomicSize implements MessageQueue { - private static final Logger _logger = Logger.getLogger(ConcurrentLinkedMessageQueueAtomicSize.class); + private static final Logger _logger = LoggerFactory.getLogger(ConcurrentLinkedMessageQueueAtomicSize.class); protected Queue _messageHead = new ConcurrentLinkedQueueAtomicSize(); @@ -62,7 +63,6 @@ public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQ _logger.debug("Providing item(" + e + ")from message head"); } - if (e != null) { _messageHeadSize.decrementAndGet(); @@ -85,6 +85,7 @@ public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQ if (_messageHead.remove(o)) { _messageHeadSize.decrementAndGet(); + return true; } @@ -101,26 +102,25 @@ public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQ } else { - //fixme this is super.removeAll but iterator here doesn't work + // fixme this is super.removeAll but iterator here doesn't work // we need to be able to correctly decrement _messageHeadSize -// boolean modified = false; -// Iterator e = iterator(); -// while (e.hasNext()) -// { -// if (c.contains(e.next())) -// { -// e.remove(); -// modified = true; -// _size.decrementAndGet(); -// } -// } -// return modified; + // boolean modified = false; + // Iterator e = iterator(); + // while (e.hasNext()) + // { + // if (c.contains(e.next())) + // { + // e.remove(); + // modified = true; + // _size.decrementAndGet(); + // } + // } + // return modified; throw new RuntimeException("Not implemented"); } } - @Override public boolean isEmpty() { @@ -173,6 +173,7 @@ public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQ { _logger.debug("Peeking item (" + o + ") from message head"); } + return o; } @@ -182,36 +183,40 @@ public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQ public Iterator iterator() { final Iterator mainMessageIterator = super.iterator(); + return new Iterator() - { - final Iterator _headIterator = _messageHead.iterator(); - final Iterator _mainIterator = mainMessageIterator; + { + final Iterator _headIterator = _messageHead.iterator(); + final Iterator _mainIterator = mainMessageIterator; - Iterator last; + Iterator last; - public boolean hasNext() - { - return _headIterator.hasNext() || _mainIterator.hasNext(); - } + public boolean hasNext() + { + return _headIterator.hasNext() || _mainIterator.hasNext(); + } - public E next() - { - if (_headIterator.hasNext()) + public E next() { - last = _headIterator; - return _headIterator.next(); + if (_headIterator.hasNext()) + { + last = _headIterator; + + return _headIterator.next(); + } + else + { + last = _mainIterator; + + return _mainIterator.next(); + } } - else + + public void remove() { - last = _mainIterator; - return _mainIterator.next(); + last.remove(); } - } - public void remove() - { - last.remove(); - } - }; + }; } @Override @@ -232,11 +237,14 @@ public class ConcurrentLinkedMessageQueueAtomicSize extends ConcurrentLinkedQ { _logger.debug("Adding item(" + o + ") to head of queue"); } + if (_messageHead.offer(o)) { _messageHeadSize.incrementAndGet(); + return true; } + return false; } -} \ No newline at end of file +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java index 3c8d3f916b..3b8ebc1666 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/FileUtils.java @@ -22,8 +22,6 @@ package org.apache.qpid.util; import java.io.*; -import org.apache.log4j.Logger; - /** * FileUtils provides some simple helper methods for working with files. It follows the convention of wrapping all * checked exceptions as runtimes, so code using these methods is free of try-catch blocks but does not expect to diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java index faeb9d7167..10f6a27293 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java @@ -26,6 +26,8 @@ package org.apache.qpid.util; *

        *
        CRC Card
        Responsibilities Collaborations *
        + * + * @todo Drop this. There are already array pretty printing methods it java.utils.Arrays. */ public class PrettyPrintingUtils { diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/PropertiesUtils.java b/qpid/java/common/src/main/java/org/apache/qpid/util/PropertiesUtils.java index aa21841256..63cf6f252b 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/PropertiesUtils.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/PropertiesUtils.java @@ -20,6 +20,9 @@ */ package org.apache.qpid.util; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -28,8 +31,6 @@ import java.net.URL; import java.util.Iterator; import java.util.Properties; -import org.apache.log4j.Logger; - /** * PropertiesHelper defines some static methods which are useful when working with properties * files. @@ -46,7 +47,7 @@ import org.apache.log4j.Logger; public class PropertiesUtils { /** Used for logging. */ - private static final Logger log = Logger.getLogger(PropertiesUtils.class); + private static final Logger log = LoggerFactory.getLogger(PropertiesUtils.class); /** * Get properties from an input stream. diff --git a/qpid/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java b/qpid/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java index 6160dc1843..e63b0df770 100644 --- a/qpid/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java +++ b/qpid/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java @@ -14,27 +14,25 @@ * "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. + * under the License. + * * - * */ package org.apache.qpid.framing; import junit.framework.Assert; import junit.framework.TestCase; -import java.util.Enumeration; -import java.util.Iterator; - import org.apache.mina.common.ByteBuffer; -import org.apache.log4j.Logger; + import org.apache.qpid.AMQPInvalidClassException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class PropertyFieldTableTest extends TestCase { - - private static final Logger _logger = Logger.getLogger(PropertyFieldTableTest.class); - + private static final Logger _logger = LoggerFactory.getLogger(PropertyFieldTableTest.class); /** * Test that setting a similar named value replaces any previous value set on that name @@ -42,9 +40,9 @@ public class PropertyFieldTableTest extends TestCase public void testReplacement() { FieldTable table1 = new FieldTable(); - //Set a boolean value + // Set a boolean value table1.setBoolean("value", true); - //Check length of table is correct ( + + ) + // Check length of table is correct ( + + ) int size = EncodingUtils.encodedShortStringLength("value") + 1 + EncodingUtils.encodedBooleanLength(); Assert.assertEquals(size, table1.getEncodedSize()); @@ -55,13 +53,12 @@ public class PropertyFieldTableTest extends TestCase size = EncodingUtils.encodedShortStringLength("value") + 1 + EncodingUtils.encodedIntegerLength(); Assert.assertEquals(size, table1.getEncodedSize()); - //Check boolean value is null + // Check boolean value is null Assert.assertEquals(null, table1.getBoolean("value")); // ... and integer value is good Assert.assertEquals((Integer) Integer.MAX_VALUE, table1.getInteger("value")); } - /** * Set a boolean and check that we can only get it back as a boolean and a string * Check that attempting to lookup a non existent value returns null @@ -72,10 +69,10 @@ public class PropertyFieldTableTest extends TestCase table1.setBoolean("value", true); Assert.assertTrue(table1.propertyExists("value")); - //Test Getting right value back + // Test Getting right value back Assert.assertEquals((Boolean) true, table1.getBoolean("value")); - //Check we don't get anything back for other gets + // Check we don't get anything back for other gets Assert.assertEquals(null, table1.getByte("value")); Assert.assertEquals(null, table1.getByte("value")); Assert.assertEquals(null, table1.getShort("value")); @@ -86,7 +83,7 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals(null, table1.getLong("value")); Assert.assertEquals(null, table1.getBytes("value")); - //except value as a string + // except value as a string Assert.assertEquals("true", table1.getString("value")); table1.remove("value"); @@ -94,7 +91,7 @@ public class PropertyFieldTableTest extends TestCase // Table should now have zero length for encoding checkEmpty(table1); - //Looking up an invalid value returns null + // Looking up an invalid value returns null Assert.assertEquals(null, table1.getBoolean("Rubbish")); } @@ -108,8 +105,8 @@ public class PropertyFieldTableTest extends TestCase table1.setByte("value", Byte.MAX_VALUE); Assert.assertTrue(table1.propertyExists("value")); - //Tets lookups we shouldn't get anything back for other gets - //we should get right value back for this type .... + // Tets lookups we shouldn't get anything back for other gets + // we should get right value back for this type .... Assert.assertEquals(null, table1.getBoolean("value")); Assert.assertEquals(Byte.MAX_VALUE, (byte) table1.getByte("value")); Assert.assertEquals(null, table1.getShort("value")); @@ -120,14 +117,14 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals(null, table1.getLong("value")); Assert.assertEquals(null, table1.getBytes("value")); - //... and a the string value of it. + // ... and a the string value of it. Assert.assertEquals("" + Byte.MAX_VALUE, table1.getString("value")); table1.remove("value"); // Table should now have zero length for encoding checkEmpty(table1); - //Looking up an invalid value returns null + // Looking up an invalid value returns null Assert.assertEquals(null, table1.getByte("Rubbish")); } @@ -141,8 +138,8 @@ public class PropertyFieldTableTest extends TestCase table1.setShort("value", Short.MAX_VALUE); Assert.assertTrue(table1.propertyExists("value")); - //Tets lookups we shouldn't get anything back for other gets - //we should get right value back for this type .... + // Tets lookups we shouldn't get anything back for other gets + // we should get right value back for this type .... Assert.assertEquals(null, table1.getBoolean("value")); Assert.assertEquals(null, table1.getByte("value")); Assert.assertEquals(Short.MAX_VALUE, (short) table1.getShort("value")); @@ -153,18 +150,17 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals(null, table1.getLong("value")); Assert.assertEquals(null, table1.getBytes("value")); - //... and a the string value of it. + // ... and a the string value of it. Assert.assertEquals("" + Short.MAX_VALUE, table1.getString("value")); table1.remove("value"); // Table should now have zero length for encoding checkEmpty(table1); - //Looking up an invalid value returns null + // Looking up an invalid value returns null Assert.assertEquals(null, table1.getShort("Rubbish")); } - /** * Set a char and check that we can only get it back as a char * Check that attempting to lookup a non existent value returns null @@ -175,8 +171,8 @@ public class PropertyFieldTableTest extends TestCase table1.setChar("value", 'c'); Assert.assertTrue(table1.propertyExists("value")); - //Tets lookups we shouldn't get anything back for other gets - //we should get right value back for this type .... + // Tets lookups we shouldn't get anything back for other gets + // we should get right value back for this type .... Assert.assertEquals(null, table1.getBoolean("value")); Assert.assertEquals(null, table1.getByte("value")); Assert.assertEquals(null, table1.getShort("value")); @@ -187,7 +183,7 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals(null, table1.getLong("value")); Assert.assertEquals(null, table1.getBytes("value")); - //... and a the string value of it. + // ... and a the string value of it. Assert.assertEquals("c", table1.getString("value")); table1.remove("value"); @@ -195,11 +191,10 @@ public class PropertyFieldTableTest extends TestCase // Table should now have zero length for encoding checkEmpty(table1); - //Looking up an invalid value returns null + // Looking up an invalid value returns null Assert.assertEquals(null, table1.getCharacter("Rubbish")); } - /** * Set a double and check that we can only get it back as a double * Check that attempting to lookup a non existent value returns null @@ -210,8 +205,8 @@ public class PropertyFieldTableTest extends TestCase table1.setDouble("value", Double.MAX_VALUE); Assert.assertTrue(table1.propertyExists("value")); - //Tets lookups we shouldn't get anything back for other gets - //we should get right value back for this type .... + // Tets lookups we shouldn't get anything back for other gets + // we should get right value back for this type .... Assert.assertEquals(null, table1.getBoolean("value")); Assert.assertEquals(null, table1.getByte("value")); Assert.assertEquals(null, table1.getShort("value")); @@ -222,20 +217,19 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals(null, table1.getLong("value")); Assert.assertEquals(null, table1.getBytes("value")); - //... and a the string value of it. + // ... and a the string value of it. Assert.assertEquals("" + Double.MAX_VALUE, table1.getString("value")); table1.remove("value"); - //but after a removeKey it doesn't + // but after a removeKey it doesn't Assert.assertFalse(table1.containsKey("value")); // Table should now have zero length for encoding checkEmpty(table1); - //Looking up an invalid value returns null + // Looking up an invalid value returns null Assert.assertEquals(null, table1.getDouble("Rubbish")); } - /** * Set a float and check that we can only get it back as a float * Check that attempting to lookup a non existent value returns null @@ -246,8 +240,8 @@ public class PropertyFieldTableTest extends TestCase table1.setFloat("value", Float.MAX_VALUE); Assert.assertTrue(table1.propertyExists("value")); - //Tets lookups we shouldn't get anything back for other gets - //we should get right value back for this type .... + // Tets lookups we shouldn't get anything back for other gets + // we should get right value back for this type .... Assert.assertEquals(null, table1.getBoolean("value")); Assert.assertEquals(null, table1.getByte("value")); Assert.assertEquals(null, table1.getShort("value")); @@ -258,22 +252,20 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals(null, table1.getLong("value")); Assert.assertEquals(null, table1.getBytes("value")); - //... and a the string value of it. + // ... and a the string value of it. Assert.assertEquals("" + Float.MAX_VALUE, table1.getString("value")); - table1.remove("value"); - //but after a removeKey it doesn't + // but after a removeKey it doesn't Assert.assertFalse(table1.containsKey("value")); // Table should now have zero length for encoding checkEmpty(table1); - //Looking up an invalid value returns null + // Looking up an invalid value returns null Assert.assertEquals(null, table1.getFloat("Rubbish")); } - /** * Set an int and check that we can only get it back as an int * Check that attempting to lookup a non existent value returns null @@ -284,8 +276,8 @@ public class PropertyFieldTableTest extends TestCase table1.setInteger("value", Integer.MAX_VALUE); Assert.assertTrue(table1.propertyExists("value")); - //Tets lookups we shouldn't get anything back for other gets - //we should get right value back for this type .... + // Tets lookups we shouldn't get anything back for other gets + // we should get right value back for this type .... Assert.assertEquals(null, table1.getBoolean("value")); Assert.assertEquals(null, table1.getByte("value")); Assert.assertEquals(null, table1.getShort("value")); @@ -296,22 +288,20 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals(null, table1.getLong("value")); Assert.assertEquals(null, table1.getBytes("value")); - //... and a the string value of it. + // ... and a the string value of it. Assert.assertEquals("" + Integer.MAX_VALUE, table1.getString("value")); - table1.remove("value"); - //but after a removeKey it doesn't + // but after a removeKey it doesn't Assert.assertFalse(table1.containsKey("value")); // Table should now have zero length for encoding checkEmpty(table1); - //Looking up an invalid value returns null + // Looking up an invalid value returns null Assert.assertEquals(null, table1.getInteger("Rubbish")); } - /** * Set a long and check that we can only get it back as a long * Check that attempting to lookup a non existent value returns null @@ -322,8 +312,8 @@ public class PropertyFieldTableTest extends TestCase table1.setLong("value", Long.MAX_VALUE); Assert.assertTrue(table1.propertyExists("value")); - //Tets lookups we shouldn't get anything back for other gets - //we should get right value back for this type .... + // Tets lookups we shouldn't get anything back for other gets + // we should get right value back for this type .... Assert.assertEquals(null, table1.getBoolean("value")); Assert.assertEquals(null, table1.getByte("value")); Assert.assertEquals(null, table1.getShort("value")); @@ -334,36 +324,34 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals(Long.MAX_VALUE, (long) table1.getLong("value")); Assert.assertEquals(null, table1.getBytes("value")); - //... and a the string value of it. + // ... and a the string value of it. Assert.assertEquals("" + Long.MAX_VALUE, table1.getString("value")); - table1.remove("value"); - //but after a removeKey it doesn't + // but after a removeKey it doesn't Assert.assertFalse(table1.containsKey("value")); // Table should now have zero length for encoding checkEmpty(table1); - //Looking up an invalid value returns null + // Looking up an invalid value returns null Assert.assertEquals(null, table1.getLong("Rubbish")); } - /** * Set a double and check that we can only get it back as a double * Check that attempting to lookup a non existent value returns null */ public void testBytes() { - byte[] bytes = {99, 98, 97, 96, 95}; + byte[] bytes = { 99, 98, 97, 96, 95 }; FieldTable table1 = new FieldTable(); table1.setBytes("value", bytes); Assert.assertTrue(table1.propertyExists("value")); - //Tets lookups we shouldn't get anything back for other gets - //we should get right value back for this type .... + // Tets lookups we shouldn't get anything back for other gets + // we should get right value back for this type .... Assert.assertEquals(null, table1.getBoolean("value")); Assert.assertEquals(null, table1.getByte("value")); Assert.assertEquals(null, table1.getShort("value")); @@ -374,17 +362,17 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals(null, table1.getLong("value")); assertBytesEqual(bytes, table1.getBytes("value")); - //... and a the string value of it is null + // ... and a the string value of it is null Assert.assertEquals(null, table1.getString("value")); table1.remove("value"); - //but after a removeKey it doesn't + // but after a removeKey it doesn't Assert.assertFalse(table1.containsKey("value")); // Table should now have zero length for encoding checkEmpty(table1); - //Looking up an invalid value returns null + // Looking up an invalid value returns null Assert.assertEquals(null, table1.getBytes("Rubbish")); } @@ -405,7 +393,6 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals(0, table.keySet().size()); } - /** * Set a String and check that we can only get it back as a String * Check that attempting to lookup a non existent value returns null @@ -416,8 +403,8 @@ public class PropertyFieldTableTest extends TestCase table1.setString("value", "Hello"); Assert.assertTrue(table1.propertyExists("value")); - //Tets lookups we shouldn't get anything back for other gets - //we should get right value back for this type .... + // Tets lookups we shouldn't get anything back for other gets + // we should get right value back for this type .... Assert.assertEquals(null, table1.getBoolean("value")); Assert.assertEquals(null, table1.getByte("value")); Assert.assertEquals(null, table1.getShort("value")); @@ -429,40 +416,35 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals(null, table1.getBytes("value")); Assert.assertEquals("Hello", table1.getString("value")); - //Try setting a null value and read it back + // Try setting a null value and read it back table1.setString("value", null); Assert.assertEquals(null, table1.getString("value")); - //but still contains the value + // but still contains the value Assert.assertTrue(table1.containsKey("value")); table1.remove("value"); - //but after a removeKey it doesn't + // but after a removeKey it doesn't Assert.assertFalse(table1.containsKey("value")); checkEmpty(table1); - //Looking up an invalid value returns null + // Looking up an invalid value returns null Assert.assertEquals(null, table1.getString("Rubbish")); - //Additional Test that haven't been covered for string + // Additional Test that haven't been covered for string table1.setObject("value", "Hello"); - //Check that it was set correctly + // Check that it was set correctly Assert.assertEquals("Hello", table1.getString("value")); } - - - - - public void testValues() { FieldTable table = new FieldTable(); table.setBoolean("bool", true); table.setByte("byte", Byte.MAX_VALUE); - byte[] bytes = {99, 98, 97, 96, 95}; + byte[] bytes = { 99, 98, 97, 96, 95 }; table.setBytes("bytes", bytes); table.setChar("char", 'c'); table.setDouble("double", Double.MAX_VALUE); @@ -484,7 +466,6 @@ public class PropertyFieldTableTest extends TestCase table.setObject("object-short", Short.MAX_VALUE); table.setObject("object-string", "Hello"); - Assert.assertEquals((Boolean) true, table.getBoolean("bool")); Assert.assertEquals((Byte) Byte.MAX_VALUE, table.getByte("byte")); assertBytesEqual(bytes, table.getBytes("bytes")); @@ -509,10 +490,9 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals("Hello", table.getObject("object-string")); } - public void testwriteBuffer() { - byte[] bytes = {99, 98, 97, 96, 95}; + byte[] bytes = { 99, 98, 97, 96, 95 }; FieldTable table = new FieldTable(); table.setBoolean("bool", true); @@ -569,13 +549,11 @@ public class PropertyFieldTableTest extends TestCase size += 1 + EncodingUtils.encodedShortStringLength("boolean") + EncodingUtils.encodedBooleanLength(); Assert.assertEquals(size, result.getEncodedSize()); - result.setByte("byte", (byte) Byte.MAX_VALUE); size += 1 + EncodingUtils.encodedShortStringLength("byte") + EncodingUtils.encodedByteLength(); Assert.assertEquals(size, result.getEncodedSize()); - - byte[] _bytes = {99, 98, 97, 96, 95}; + byte[] _bytes = { 99, 98, 97, 96, 95 }; result.setBytes("bytes", _bytes); size += 1 + EncodingUtils.encodedShortStringLength("bytes") + 4 + _bytes.length; @@ -597,7 +575,6 @@ public class PropertyFieldTableTest extends TestCase size += 1 + EncodingUtils.encodedShortStringLength("int") + EncodingUtils.encodedIntegerLength(); Assert.assertEquals(size, result.getEncodedSize()); - result.setLong("long", (long) Long.MAX_VALUE); size += 1 + EncodingUtils.encodedShortStringLength("long") + EncodingUtils.encodedLongLength(); Assert.assertEquals(size, result.getEncodedSize()); @@ -610,7 +587,6 @@ public class PropertyFieldTableTest extends TestCase size += 1 + EncodingUtils.encodedShortStringLength("result") + EncodingUtils.encodedLongStringLength("Hello"); Assert.assertEquals(size, result.getEncodedSize()); - result.setObject("object-bool", true); size += 1 + EncodingUtils.encodedShortStringLength("object-bool") + EncodingUtils.encodedBooleanLength(); Assert.assertEquals(size, result.getEncodedSize()); @@ -639,7 +615,6 @@ public class PropertyFieldTableTest extends TestCase size += 1 + EncodingUtils.encodedShortStringLength("object-int") + EncodingUtils.encodedIntegerLength(); Assert.assertEquals(size, result.getEncodedSize()); - result.setObject("object-long", Long.MAX_VALUE); size += 1 + EncodingUtils.encodedShortStringLength("object-long") + EncodingUtils.encodedLongLength(); Assert.assertEquals(size, result.getEncodedSize()); @@ -650,63 +625,62 @@ public class PropertyFieldTableTest extends TestCase } -// public void testEncodingSize1() -// { -// PropertyFieldTable table = new PropertyFieldTable(); -// int length = 0; -// result.put("one", 1L); -// length = EncodingUtils.encodedShortStringLength("one"); -// length += 1 + EncodingUtils.encodedLongLength(); -// assertEquals(length, result.getEncodedSize()); -// -// result.put("two", 2L); -// length += EncodingUtils.encodedShortStringLength("two"); -// length += 1 + EncodingUtils.encodedLongLength(); -// assertEquals(length, result.getEncodedSize()); -// -// result.put("three", 3L); -// length += EncodingUtils.encodedShortStringLength("three"); -// length += 1 + EncodingUtils.encodedLongLength(); -// assertEquals(length, result.getEncodedSize()); -// -// result.put("four", 4L); -// length += EncodingUtils.encodedShortStringLength("four"); -// length += 1 + EncodingUtils.encodedLongLength(); -// assertEquals(length, result.getEncodedSize()); -// -// result.put("five", 5L); -// length += EncodingUtils.encodedShortStringLength("five"); -// length += 1 + EncodingUtils.encodedLongLength(); -// assertEquals(length, result.getEncodedSize()); -// -// //fixme should perhaps be expanded to incorporate all types. -// -// final ByteBuffer buffer = ByteBuffer.allocate((int) result.getEncodedSize()); // FIXME XXX: Is cast a problem? -// -// result.writeToBuffer(buffer); -// -// buffer.flip(); -// -// long length = buffer.getUnsignedInt(); -// -// try -// { -// PropertyFieldTable table2 = new PropertyFieldTable(buffer, length); -// -// Assert.assertEquals((Long) 1L, table2.getLong("one")); -// Assert.assertEquals((Long) 2L, table2.getLong("two")); -// Assert.assertEquals((Long) 3L, table2.getLong("three")); -// Assert.assertEquals((Long) 4L, table2.getLong("four")); -// Assert.assertEquals((Long) 5L, table2.getLong("five")); -// } -// catch (AMQFrameDecodingException e) -// { -// e.printStackTrace(); -// fail("PFT should be instantiated from bytes." + e.getCause()); -// } -// -// } - + // public void testEncodingSize1() + // { + // PropertyFieldTable table = new PropertyFieldTable(); + // int length = 0; + // result.put("one", 1L); + // length = EncodingUtils.encodedShortStringLength("one"); + // length += 1 + EncodingUtils.encodedLongLength(); + // assertEquals(length, result.getEncodedSize()); + // + // result.put("two", 2L); + // length += EncodingUtils.encodedShortStringLength("two"); + // length += 1 + EncodingUtils.encodedLongLength(); + // assertEquals(length, result.getEncodedSize()); + // + // result.put("three", 3L); + // length += EncodingUtils.encodedShortStringLength("three"); + // length += 1 + EncodingUtils.encodedLongLength(); + // assertEquals(length, result.getEncodedSize()); + // + // result.put("four", 4L); + // length += EncodingUtils.encodedShortStringLength("four"); + // length += 1 + EncodingUtils.encodedLongLength(); + // assertEquals(length, result.getEncodedSize()); + // + // result.put("five", 5L); + // length += EncodingUtils.encodedShortStringLength("five"); + // length += 1 + EncodingUtils.encodedLongLength(); + // assertEquals(length, result.getEncodedSize()); + // + // //fixme should perhaps be expanded to incorporate all types. + // + // final ByteBuffer buffer = ByteBuffer.allocate((int) result.getEncodedSize()); // FIXME XXX: Is cast a problem? + // + // result.writeToBuffer(buffer); + // + // buffer.flip(); + // + // long length = buffer.getUnsignedInt(); + // + // try + // { + // PropertyFieldTable table2 = new PropertyFieldTable(buffer, length); + // + // Assert.assertEquals((Long) 1L, table2.getLong("one")); + // Assert.assertEquals((Long) 2L, table2.getLong("two")); + // Assert.assertEquals((Long) 3L, table2.getLong("three")); + // Assert.assertEquals((Long) 4L, table2.getLong("four")); + // Assert.assertEquals((Long) 5L, table2.getLong("five")); + // } + // catch (AMQFrameDecodingException e) + // { + // e.printStackTrace(); + // fail("PFT should be instantiated from bytes." + e.getCause()); + // } + // + // } /** * Additional test for setObject @@ -715,7 +689,7 @@ public class PropertyFieldTableTest extends TestCase { FieldTable table = new FieldTable(); - //Try setting a non primative object + // Try setting a non primative object try { @@ -724,7 +698,7 @@ public class PropertyFieldTableTest extends TestCase } catch (AMQPInvalidClassException iae) { - //normal path + // normal path } // so length should be zero Assert.assertEquals(0, table.getEncodedSize()); @@ -739,18 +713,17 @@ public class PropertyFieldTableTest extends TestCase try { - table.setObject((String)null, "String"); + table.setObject((String) null, "String"); fail("Null property name is not allowed"); } catch (IllegalArgumentException iae) { - //normal path + // normal path } // so length should be zero Assert.assertEquals(0, table.getEncodedSize()); } - /** * Additional test checkPropertyName doesn't accept an empty String */ @@ -765,18 +738,19 @@ public class PropertyFieldTableTest extends TestCase } catch (IllegalArgumentException iae) { - //normal path + // normal path } // so length should be zero Assert.assertEquals(0, table.getEncodedSize()); } - /** * Additional test checkPropertyName doesn't accept an empty String */ public void testCheckPropertyNamehasMaxLength() { + String oldVal = System.getProperty("STRICT_AMQP"); + System.setProperty("STRICT_AMQP", "true"); FieldTable table = new FieldTable(); StringBuffer longPropertyName = new StringBuffer(129); @@ -793,21 +767,30 @@ public class PropertyFieldTableTest extends TestCase } catch (IllegalArgumentException iae) { - //normal path + // normal path } // so length should be zero Assert.assertEquals(0, table.getEncodedSize()); + if (oldVal != null) + { + System.setProperty("STRICT_AMQP", oldVal); + } + else + { + System.clearProperty("STRICT_AMQP"); + } } - /** * Additional test checkPropertyName starts with a letter */ public void testCheckPropertyNameStartCharacterIsLetter() { + String oldVal = System.getProperty("STRICT_AMQP"); + System.setProperty("STRICT_AMQP", "true"); FieldTable table = new FieldTable(); - //Try a name that starts with a number + // Try a name that starts with a number try { table.setObject("1", "String"); @@ -815,21 +798,30 @@ public class PropertyFieldTableTest extends TestCase } catch (IllegalArgumentException iae) { - //normal path + // normal path } // so length should be zero Assert.assertEquals(0, table.getEncodedSize()); + if (oldVal != null) + { + System.setProperty("STRICT_AMQP", oldVal); + } + else + { + System.clearProperty("STRICT_AMQP"); + } } - /** * Additional test checkPropertyName starts with a hash or a dollar */ public void testCheckPropertyNameStartCharacterIsHashorDollar() { + String oldVal = System.getProperty("STRICT_AMQP"); + System.setProperty("STRICT_AMQP", "true"); FieldTable table = new FieldTable(); - //Try a name that starts with a number + // Try a name that starts with a number try { table.setObject("#", "String"); @@ -839,8 +831,16 @@ public class PropertyFieldTableTest extends TestCase { fail("property name are allowed to start with # and $s"); } - } + if (oldVal != null) + { + System.setProperty("STRICT_AMQP", oldVal); + } + else + { + System.clearProperty("STRICT_AMQP"); + } + } /** * Additional test to test the contents of the table @@ -853,7 +853,7 @@ public class PropertyFieldTableTest extends TestCase Assert.assertEquals("String", table.getString("StringProperty")); - //Test Clear + // Test Clear table.clear(); @@ -872,18 +872,12 @@ public class PropertyFieldTableTest extends TestCase table.setObject("n2", "2"); table.setObject("n3", "3"); - Assert.assertEquals("1", table.getObject("n1")); Assert.assertEquals("2", table.getObject("n2")); Assert.assertEquals("3", table.getObject("n3")); - - - } - - private void assertBytesEqual(byte[] expected, byte[] actual) { Assert.assertEquals(expected.length, actual.length); diff --git a/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java b/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java index c480ce3944..815b61d293 100644 --- a/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java +++ b/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java @@ -1,10 +1,11 @@ package org.apache.qpid.util; -import java.util.Properties; - import junit.framework.*; -import org.apache.log4j.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Properties; /** * Unit tests the {@link CommandLineParser} class. @@ -37,7 +38,7 @@ import org.apache.log4j.*; */ public class CommandLineParserTest extends TestCase { - private static final Logger log = Logger.getLogger(CommandLineParserTest.class); + private static final Logger log = LoggerFactory.getLogger(CommandLineParserTest.class); public CommandLineParserTest(String name) { @@ -58,11 +59,6 @@ public class CommandLineParserTest extends TestCase return suite; } - public void setUp() - { - NDC.push(getName()); - } - /** Check that get errors returns an empty string on no errors. */ public void testGetErrorsReturnsEmptyStringOnNoErrors() throws Exception { @@ -534,9 +530,4 @@ public class CommandLineParserTest extends TestCase assertTrue("IllegalArgumentException not thrown for an unknown option when errors on unknowns mode is on.", testPassed); } - - protected void tearDown() throws Exception - { - NDC.pop(); - } } -- cgit v1.2.1 From 3769af8867386add4cbfa191ec45f786e4f84e69 Mon Sep 17 00:00:00 2001 From: Martin Ritchie Date: Fri, 15 Jun 2007 16:37:08 +0000 Subject: Merged revisions 547178 via svnmerge from https://svn.apache.org/repos/asf/incubator/qpid/branches/M2 ........ r547178 | gsim | 2007-06-14 09:51:39 +0100 (Thu, 14 Jun 2007) | 3 lines Converted templates to generate classes using slf4j rather than log4j inline with changes applied in rev 546190. ........ git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@547731 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java index 08b5745b19..5bd7b9aea0 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java @@ -1,11 +1,13 @@ package org.apache.qpid.util.concurrent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; -import org.apache.log4j.Logger; /** * Synchronous/Asynchronous puts. Asynchronous is easiest, just wait till can write to queue and deposit data. @@ -41,7 +43,8 @@ import org.apache.log4j.Logger; public abstract class BatchSynchQueueBase extends AbstractQueue implements BatchSynchQueue { /** Used for logging. */ - private static final Logger log = Logger.getLogger(BatchSynchQueueBase.class); + private static final Logger log = LoggerFactory.getLogger(BatchSynchQueueBase.class); + /** Holds a reference to the queue implementation that holds the buffer. */ Queue> buffer; -- cgit v1.2.1 From 8c8ee073330c02ba451a7a1a57e7da7110e4d8c0 Mon Sep 17 00:00:00 2001 From: Martin Ritchie Date: Mon, 18 Jun 2007 16:29:49 +0000 Subject: Merged revisions 539476-539480,539482-539483,539485-539500,539502-539593,539595-539782,539784-539787,539789-540106,540108-540168,540170-540510,540512-541246,541248-541919,541921-542483,542485-542788,542790-543495,543497-544108,544110-544421,544423-544507,544509-546095,546097-546189,546191-546440,546442-546457,546459-547177,547179-547626,547628-548381 via svnmerge from https://svn.apache.org/repos/asf/incubator/qpid/branches/M2 ........ r539476 | ritchiem | 2007-05-18 15:12:28 +0100 (Fri, 18 May 2007) | 1 line QPID-401 Update to pom to correctly set the broker.dir ........ r544866 | rupertlssmith | 2007-06-06 16:25:02 +0100 (Wed, 06 Jun 2007) | 1 line Updated examples to build source jar. Also put the java14 retrotranslated module back in now that the strange repeating build problem is solved. ........ r545146 | ritchiem | 2007-06-07 12:30:01 +0100 (Thu, 07 Jun 2007) | 1 line POM update renumbering tests now we have trimmed down the tests being run. ........ r548276 | ritchiem | 2007-06-18 10:59:32 +0100 (Mon, 18 Jun 2007) | 1 line Various License header updates. ........ r548279 | ritchiem | 2007-06-18 11:17:20 +0100 (Mon, 18 Jun 2007) | 1 line Various License header updates. ........ r548302 | ritchiem | 2007-06-18 11:49:50 +0100 (Mon, 18 Jun 2007) | 2 lines Various License header updates. Update to PrincipalDatabase's to ensure they work correctly with # comments. ........ r548308 | ritchiem | 2007-06-18 11:58:38 +0100 (Mon, 18 Jun 2007) | 1 line Various License header updates, missed this file. Though the first update of it via the JMX console will remove the license. ........ r548312 | rupertlssmith | 2007-06-18 12:03:09 +0100 (Mon, 18 Jun 2007) | 1 line Added SLF4J to Log4J binding. ........ r548315 | ritchiem | 2007-06-18 12:07:45 +0100 (Mon, 18 Jun 2007) | 1 line Old lib dir from M1 ........ r548317 | ritchiem | 2007-06-18 12:13:57 +0100 (Mon, 18 Jun 2007) | 1 line Old lib dirs from M1 ........ r548319 | ritchiem | 2007-06-18 12:16:25 +0100 (Mon, 18 Jun 2007) | 1 line Mistakenly checked in Intelij file ........ r548381 | ritchiem | 2007-06-18 16:37:41 +0100 (Mon, 18 Jun 2007) | 1 line QPID-525 Memory leak in DestWildExchange. Used routing key in remove rather than empty queue ........ git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@548400 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/qpid/AMQConnectionFailureException.java | 21 +++++++++++++++++++++ .../org/apache/qpid/AMQUnknownExchangeType.java | 21 +++++++++++++++++++++ .../qpid/framing/AMQMethodBodyInstanceFactory.java | 21 +++++++++++++++++++++ .../org/apache/qpid/framing/AMQShortString.java | 21 +++++++++++++++++++++ .../java/org/apache/qpid/framing/AMQTypedValue.java | 21 +++++++++++++++++++++ .../qpid/framing/CommonContentHeaderProperties.java | 21 +++++++++++++++++++++ .../java/org/apache/qpid/framing/FieldTable.java | 1 + .../apache/qpid/framing/MethodConverter_8_0.java | 21 +++++++++++++++++++++ .../qpid/framing/SmallCompositeAMQDataBlock.java | 21 +++++++++++++++++++++ .../abstraction/AbstractMethodConverter.java | 21 +++++++++++++++++++++ .../org/apache/qpid/util/CommandLineParserTest.java | 21 +++++++++++++++++++++ 11 files changed, 211 insertions(+) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java index c043a00836..b60f130652 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java @@ -1,3 +1,24 @@ +/* + * + * 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; /** diff --git a/qpid/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java b/qpid/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java index f483b9947b..b31765ce66 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java @@ -1,3 +1,24 @@ +/* + * + * 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; /** diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java index cfbc9d1828..359efe7eb7 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java @@ -1,3 +1,24 @@ +/* + * + * 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.framing; import org.apache.mina.common.ByteBuffer; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java index ee7abd55c0..05e9473463 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java @@ -1,3 +1,24 @@ +/* + * + * 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.framing; import org.apache.mina.common.ByteBuffer; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java index e7175e7973..7193580884 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java @@ -1,3 +1,24 @@ +/* + * + * 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.framing; import org.apache.mina.common.ByteBuffer; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java index 66c5e19633..6a608a8bff 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/CommonContentHeaderProperties.java @@ -1,3 +1,24 @@ +/* + * + * 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.framing; public interface CommonContentHeaderProperties extends ContentHeaderProperties diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java index 2fe96b722b..3438770450 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java @@ -18,6 +18,7 @@ * under the License. * */ + package org.apache.qpid.framing; import org.apache.mina.common.ByteBuffer; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/MethodConverter_8_0.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/MethodConverter_8_0.java index dd93cc97fa..9a113f452b 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/MethodConverter_8_0.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/MethodConverter_8_0.java @@ -1,3 +1,24 @@ +/* + * + * 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.framing; import org.apache.qpid.framing.abstraction.ProtocolVersionMethodConverter; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java index 174cb142e0..26c048e34a 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java @@ -1,3 +1,24 @@ +/* + * + * 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.framing; import org.apache.mina.common.ByteBuffer; diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/AbstractMethodConverter.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/AbstractMethodConverter.java index 5490d482a1..1c335f3036 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/AbstractMethodConverter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/AbstractMethodConverter.java @@ -1,3 +1,24 @@ +/* + * + * 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.framing.abstraction; public abstract class AbstractMethodConverter implements ProtocolVersionMethodConverter diff --git a/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java b/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java index 815b61d293..66fb3252df 100644 --- a/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java +++ b/qpid/java/common/src/test/java/org/apache/qpid/util/CommandLineParserTest.java @@ -1,3 +1,24 @@ +/* + * + * 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.util; import junit.framework.*; -- cgit v1.2.1 From 7e4c859715e60572f391c781944c901ce45db42c Mon Sep 17 00:00:00 2001 From: Martin Ritchie Date: Tue, 19 Jun 2007 14:53:29 +0000 Subject: Fixed outstanding merge issues and updates to trunk code that were required for sl4j. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@548753 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java index 5bd7b9aea0..47eff4be19 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java @@ -1,13 +1,13 @@ package org.apache.qpid.util.concurrent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Synchronous/Asynchronous puts. Asynchronous is easiest, just wait till can write to queue and deposit data. @@ -44,7 +44,6 @@ public abstract class BatchSynchQueueBase extends AbstractQueue implements { /** Used for logging. */ private static final Logger log = LoggerFactory.getLogger(BatchSynchQueueBase.class); - /** Holds a reference to the queue implementation that holds the buffer. */ Queue> buffer; -- cgit v1.2.1 From 74bf9662eb1c0f54ef20eda618e8e7f72f2fdfad Mon Sep 17 00:00:00 2001 From: Arnaud Simon Date: Mon, 23 Jul 2007 12:32:08 +0000 Subject: First version of the Java Qpid API. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@558701 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/nclient/FieldTable.java | 28 +++ .../qpid/nclient/exception/QpidException.java | 48 ++++ .../apache/qpid/nclient/qpidapi/Connection.java | 81 +++++++ .../qpid/nclient/qpidapi/CreateReceiverOption.java | 16 ++ .../nclient/qpidapi/DeclareExchangeOption.java | 17 ++ .../qpid/nclient/qpidapi/DeleteExchangeOption.java | 12 + .../qpid/nclient/qpidapi/DeleteQueueOption.java | 13 ++ .../apache/qpid/nclient/qpidapi/DtxSession.java | 43 ++++ .../org/apache/qpid/nclient/qpidapi/Message.java | 126 +++++++++++ .../qpid/nclient/qpidapi/MessageListener.java | 36 +++ .../qpid/nclient/qpidapi/MessageReceiver.java | 95 ++++++++ .../apache/qpid/nclient/qpidapi/MessageSender.java | 44 ++++ .../org/apache/qpid/nclient/qpidapi/Resource.java | 54 +++++ .../org/apache/qpid/nclient/qpidapi/Session.java | 247 +++++++++++++++++++++ .../qpid/nclient/qpidapi/declareQueueOption.java | 17 ++ 15 files changed, 877 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/FieldTable.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/exception/QpidException.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Connection.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/CreateReceiverOption.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeclareExchangeOption.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteExchangeOption.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteQueueOption.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DtxSession.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Message.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageListener.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageReceiver.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageSender.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Resource.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Session.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/declareQueueOption.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/FieldTable.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/FieldTable.java new file mode 100644 index 0000000000..d79794e98d --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/FieldTable.java @@ -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. + */ +package org.apache.qpid.nclient; + +/** + * Created by Arnaud Simon + * Date: 23-Jul-2007 + * Time: 09:47:32 + */ +public interface FieldTable +{ +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/exception/QpidException.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/exception/QpidException.java new file mode 100644 index 0000000000..cacac98cc0 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/exception/QpidException.java @@ -0,0 +1,48 @@ +/* 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.nclient.exception; + +/** + * Created by Arnaud Simon + * Date: 20-Jul-2007 + * Time: 10:56:55 + */ +public class QpidException extends Exception +{ + /** + * This exception error code. + *

        This error code is used for internationalisation purpose. + *

        This error code is set from the AMQP ones. + * So we may want to use the AMQP error code directly. + */ + String _errorCode; + + /** + * Constructor for a Qpid Exception. + *

        This is the only provided constructor and the parameters have to be set to null when + * they are unknown. + * @param message A description of the reason of this exception . + * @param errorCode A string specifyin the error code of this exception. + * @param cause The linked Execption. + */ + public QpidException(String message, String errorCode, Throwable cause) + { + super(message, cause); + _errorCode = errorCode; + } +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Connection.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Connection.java new file mode 100644 index 0000000000..fd59b95c0f --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Connection.java @@ -0,0 +1,81 @@ +/* + * 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.nclient.qpidapi; + +import org.apache.qpid.nclient.exception.QpidException; + +import java.net.URL; + +/** + * This represents a physical connection to a broker. + *

        + * Created by Arnaud Simon + * Date: 20-Jul-2007 + * Time: 09:34:15 + */ +public interface Connection +{ + /** + * Establish the connection with the broker identified by the provided URL. + * + * @param url The URL of the broker. + * @throws QpidException If the communication layer fails to connect with the broker. + */ + public void connect(URL url) + throws + QpidException; + + /** + * Close this connection. + * + * @throws QpidException if the communication layer fails to close the connection. + */ + public void close() + throws + QpidException; + + + /** + * Create a session for this connection. + *

        The retuned session is suspended + * (i.e. this session is not attached with an underlying channel) + * + * @param expiryInSeconds Expiry time expressed in seconds, if the value is <= 0 then the session does not expire. + * @return A Newly created (suspended) session. + * @throws QpidException If the connection fails to create a session due to some internal error. + */ + public Session createSession(int expiryInSeconds) + throws + QpidException; + + /** + * Create a DtxSession for this connection. + *

        A Dtx Session must be used when resources have to be manipulated as + * part of a global transaction. + *

        The retuned DtxSession is suspended + * (i.e. this session is not attached with an underlying channel) + * + * @param expiryInSeconds Expiry time expressed in seconds, if the value is <= 0 then the session does not expire. + * @return A Newly created (suspended) DtxSession. + * @throws QpidException If the connection fails to create a DtxSession due to some internal error. + */ + public DtxSession createDTXSession(int expiryInSeconds) + throws + QpidException; +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/CreateReceiverOption.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/CreateReceiverOption.java new file mode 100644 index 0000000000..4d8315c33b --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/CreateReceiverOption.java @@ -0,0 +1,16 @@ +package org.apache.qpid.nclient.qpidapi; + +/** + * Enumeration of the options available when creating a receiver + * + * Created by Arnaud Simon + * Date: 20-Jul-2007 + * Time: 09:43:31 + */ +public enum CreateReceiverOption +{ + NO_LOCAL, + EXCLUSIVE, + NO_ACQUIRE, + CONFIRME; +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeclareExchangeOption.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeclareExchangeOption.java new file mode 100644 index 0000000000..8674792252 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeclareExchangeOption.java @@ -0,0 +1,17 @@ +package org.apache.qpid.nclient.qpidapi; + +/** + * Enumeration of the options available when declaring an exchange + * + * Created by Arnaud Simon + * Date: 20-Jul-2007 + * Time: 09:44:52 + */ +public enum DeclareExchangeOption +{ + AUTO_DELETE, + DURABLE, + INTERNAL, + NOWAIT, + PASSIVE; +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteExchangeOption.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteExchangeOption.java new file mode 100644 index 0000000000..188d665c8c --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteExchangeOption.java @@ -0,0 +1,12 @@ +package org.apache.qpid.nclient.qpidapi; + +/** + * Created by Arnaud Simon + * Date: 23-Jul-2007 + * Time: 12:55:55 + */ +public enum DeleteExchangeOption +{ + IF_UNUSED, + NOWAIT; +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteQueueOption.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteQueueOption.java new file mode 100644 index 0000000000..0062218a70 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteQueueOption.java @@ -0,0 +1,13 @@ +package org.apache.qpid.nclient.qpidapi; + +/** + * Created by Arnaud Simon + * Date: 23-Jul-2007 + * Time: 12:44:43 + */ +public enum DeleteQueueOption +{ + IF_EMPTY, + IF_UNUSED, + NO_WAIT; +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DtxSession.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DtxSession.java new file mode 100644 index 0000000000..c361fdcf82 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DtxSession.java @@ -0,0 +1,43 @@ +/* + * 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.nclient.qpidapi; + +import org.apache.qpid.nclient.exception.QpidException; + +/** + * This session’s resources are control under the scope of a distributed transaction. + * + * Created by Arnaud Simon + * Date: 20-Jul-2007 + * Time: 09:39:11 + */ +public interface DtxSession extends Session +{ + + /** + * Get the XA resource associated with this session. + * + * @return this session XA resource. + * @throws QpidException If the session fails to retrieve its associated XA resource + * due to some error. + */ + public javax.transaction.xa.XAResource getDTXResource() + throws + QpidException; +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Message.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Message.java new file mode 100644 index 0000000000..6974d0cae2 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Message.java @@ -0,0 +1,126 @@ +/* + * 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.nclient.qpidapi; + + +import org.apache.qpid.nclient.FieldTable; +import org.apache.qpid.nclient.exception.QpidException; + +import java.nio.ByteBuffer; + +/** + * A message is sent and received by resources. It is composed of a set of header and a payload. + *

        + * Created by Arnaud Simon + * Date: 20-Jul-2007 + * Time: 09:40:49 + */ +public interface Message +{ + /** + * Get this message auto-allocated messageID. + * + * @return This message ID. + */ + public long getMessageID(); + + /** + * Set this message headers + *

        Previous headers are reset. + * + * @param headers The message headers as a field table. + * @see FieldTable + */ + public void setHeaders(FieldTable headers); + + /** + * Access to this message headers. + * + * @return This message headers as a field table. + */ + public FieldTable getHeaders(); + + /** + * Set this message payload. + * + * @param buffer This message payload. + */ + public void setBody(ByteBuffer buffer); + + /** + * Access this message body. + * + * @return The payload of this message. + */ + public ByteBuffer getBody(); + + /** + * Acknowledge the receipt of this message. + *

        The message must have been previously acquired either by receiving it in + * pre-acquire mode or by explicitly acquiring it. + * + * @throws QpidException If the acknowledgement of the message fails due to some error. + * @throws IllegalStateException If this messages is not acquired. + */ + public void acknowledge() + throws + QpidException, + IllegalStateException; + + /** + * Acknowledge the receipt of an acquired messages which IDs are within + * the interval [this.messageID, message.messageID] + * + * @param message The last message to be acknowledged. + * @throws QpidException If the acknowledgement of this set of messages fails due to some error. + * @throws IllegalStateException If some messages are not acquired. + */ + public void acknowledge(Message message) + throws + QpidException, + IllegalStateException; + + /** + * Reject a previously acquired message. + *

        A rejected message will not be delivered to any receiver + * and may be either discarded or moved to the broker dead letter queue. + * + * @throws QpidException If this message cannot be rejected dus to some error + * @throws IllegalStateException If this message is not acquired. + */ + public void reject() + throws + QpidException, + IllegalStateException; + + /** + * Try to acquire this message hence releasing it form the queue. This means that once acknowledged, + * this message will not be delivered to any other receiver. + *

        As this message may have been consumed by another receiver, message acquisition can fail. + * The outcome of the acquisition is returned as a Boolean. + * + * @return True if the message is successfully acquired, False otherwise. + * @throws QpidException If this message cannot be acquired dus to some error + * @throws IllegalStateException If this message has already been acquired. + */ + public boolean acquire() + throws + QpidException, + IllegalStateException; +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageListener.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageListener.java new file mode 100644 index 0000000000..d607d0a3c2 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageListener.java @@ -0,0 +1,36 @@ +/* + * 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.nclient.qpidapi; + +/** + * MessageListeners are used to asynchronously receive messages. + * + * Created by Arnaud Simon + * Date: 2o-Jul-2007 + * Time: 09:42:52 + */ +public interface MessageListener +{ + /** + * Deliver a message to the listener. + * + * @param message The message delivered to the listner. + */ + public void onMessage(Message message); +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageReceiver.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageReceiver.java new file mode 100644 index 0000000000..6592857b2e --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageReceiver.java @@ -0,0 +1,95 @@ +/* + * 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.nclient.qpidapi; + +import org.apache.qpid.nclient.exception.QpidException; + +import java.util.Set; + +/** + * Used to receive messages from a queue + * + *

        + * Created by Arnaud Simon + * Date: 20-Jul-2007 + * Time: 09:42:37 + */ +public interface MessageReceiver extends Resource +{ + /** + * Get this receiver options. + * + * @return This receiver set of options. + */ + public Set getOptions(); + + /** + * Receive a message form this receiver queue. + *

        If the timeout is less or equal than 0 then this operation is blocking. + * Otherwise it blocks until a message arrives, the timeout expires, or this receiver is closed. + *

        To receive messages, a receiver must be started. + * + * @param timeout The timeout value (in milliseconds). + * @return A message or null if timeout expires or this receiver is concurrently closed. + * @throws QpidException If this receiver fails to receive a message due to some error. + * @throws IllegalStateException If this receiver is closed, not started or a MessageListener is set. + */ + public Message receive(long timeout) + throws + QpidException, + IllegalStateException; + + /** + * Stop the delivery of messages to this receiver. + * + * @throws QpidException If this receiver fails to be stopped due to some error. + * @throws IllegalStateException If this receiver is closed or already stopped. + */ + public void stop() + throws + QpidException, + IllegalStateException; + + /** + * Start the delivery of messages to this receiver. + * + * @throws QpidException If this receiver fails to be started due to some error. + * @throws IllegalStateException If this receiver is closed or already started. + */ + public void start() + throws + QpidException, + IllegalStateException; + + /** + * Set the receiver’s MessageListener. + * Setting the message listener to null is the equivalent of un-setting the message + * listener for this receiver. + *

        Once a message listener is set, a receiver cannot receive messages through its + * receive method. + * + * @param listener The message listner. + * @throws QpidException If this receiver fails to set the message listner due to some error. + * @throws IllegalStateException If this receiver is closed. + */ + public void setAsynchronous(MessageListener listener) + throws + QpidException, + IllegalStateException; +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageSender.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageSender.java new file mode 100644 index 0000000000..cbe1443798 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageSender.java @@ -0,0 +1,44 @@ +/* + * 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.nclient.qpidapi; + +import org.apache.qpid.nclient.exception.QpidException; + +/** + * A sender is used to send message to its queue. + * + * Created by Arnaud Simon + * Date: 22-Jul-2007 + * Time: 09:41:58 + */ +public interface MessageSender extends Resource +{ + + /** + * Sends a message to this sender queue. + * + * @param message The message to be sent + * @param inline //TODO + * @throws QpidException If the sender fails to send the message due to some error. + * @throws IllegalStateException If this sender was closed or its session suspended. + */ + public void send(Message message, boolean inline) throws + QpidException, + IllegalStateException; +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Resource.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Resource.java new file mode 100644 index 0000000000..29965e0045 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Resource.java @@ -0,0 +1,54 @@ +/* + * 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.nclient.qpidapi; + +import org.apache.qpid.nclient.exception.QpidException; + +/** + * A Resource is associated with a session and can be independently closed. + * + * Created by Arnaud Simon + * Date: 21-Jul-2007 + * Time: 09:41:30 + */ +public interface Resource +{ + + /** + * Close this resource. + * + * @throws QpidException If the session fails to close this resource due to some error + */ + public void close() throws + QpidException; + + /** + * Get this resource session. + * + * @return This resource's session. + */ + public Session getSession(); + + /** + * Get the queue name to which this resource is tied. + * + * @return The queue name of this resource. + */ + public String getQueueNAme(); +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Session.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Session.java new file mode 100644 index 0000000000..24e47a7657 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Session.java @@ -0,0 +1,247 @@ +/* + * 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.nclient.qpidapi; + +import org.apache.qpid.nclient.exception.QpidException; + +/** + * A session is associated with a connection. + *

        When created a Session is not attached with an underlying channel. Unsuspended a Session is + * equivalent to attaching a communication channel that can be used to communicate with the broker. + *

        + * Created by Arnaud Simon + * Date: 20-Jul-2007 + * Time: 09:36:24 + */ +public interface Session +{ + /** + * Close this session and any associated resources. + * + * @throws QpidException If the communication layer fails to close this session or if an internal error happens + * when closing this session resources. . + */ + public void close() + throws + QpidException; + + /** + * Suspend this session resulting in interrupting the traffic with the broker. + * When a session is suspend any operation of this session and of the associated resources is unavailable. + * + * @throws QpidException If the communication layer fails to suspend this session + */ + public void suspend() + throws + QpidException; + + /** + * Unsuspended a Session is equivalent to attaching a communication channel that can be used to + * communicate with the broker. All the operations of this session and of the associated resources + * are made available. + * + * @throws QpidException If the communication layer fails to unsuspend this session + */ + public void unsuspend() + throws + QpidException; + + /** + * Create a message sender for sending messages to queue queueName. + * + * @param queueName The queue this sender is sending messages. + * @return A sender for queue queueName + * @throws QpidException If the session fails to create the sended due to some error + */ + public MessageSender createSender(String queueName) + throws + QpidException; + //Todo: Do we need to define more specific exception like queue name not valid? + + /** + * Create a message receiver for receiving messages from queue queueName. + *

        see available options: {@link CreateReceiverOption} + *

        When non of the options are set then the receiver is created with: + *

          + *
        • no_local = false + *
        • non exclusive + *
        • pre-acquire mode + *
        • no confirmation + *
        + * + * @param queueName The queue this receiver is receiving messages from. + * @param options Set of Options. + * @return A receiver for queue queueName. + * @throws QpidException If the session fails to create the receiver due to some error. + * @see CreateReceiverOption + */ + public MessageReceiver createReceiver(String queueName, CreateReceiverOption... options) + throws + QpidException; + //Todo: Do we need to define more specific exceptions like queue name not valid? + + /** + * Commit the receipt and the delivery of all messages exchanged by this session resources. + * + * @throws QpidException If the session fails to commit due to some error. + * @throws IllegalStateException If this session is not transacted. + */ + public void commit() + throws + QpidException, + IllegalStateException; + + /** + * Rollback the receipt and the delivery of all messages exchanged by this session resources. + * + * @throws QpidException If the session fails to rollback due to some error. + * @throws IllegalStateException If this session is not transacted. + */ + public void rollback() + throws + QpidException, + IllegalStateException; + + /** + * Set this session as transacted. + *

        This operation is irreversible. + * + * @throws QpidException If the session fail to be transacted due to some error. + * @throws IllegalStateException If this session is already transacted. + */ + public void setTransacted() + throws + QpidException, + IllegalStateException; + + /** + * Declare a queue of name queueName + *

        see available options: {@link declareQueueOption} + *

        When non of the options are set then the receiver is created with: + *

          + *
        • auto_delete = false + *
        • non-durable + *
        • non-exccusive + *
        • nowait = false + *
        • not passive + *
        + * + * @param queueName The name of the delcared queue. + * @param options Set of Options. + * @throws QpidException If the session fails to declare the queue due to some error. + * @see declareQueueOption + */ + public void declareQueue(String queueName, declareQueueOption... options) + throws + QpidException; + //Todo: Do we need to define more specific exceptions like queue name already exist? + + /** + * Bind a queue with an exchange. + * + * @param queueName The queue to be bound. + * @param exchangeName The exchange name. + * @param routingKey The routing key. + * @param nowait nowait + * @throws QpidException If the session fails to bind the queue due to some error. + */ + public void bindQueue(String queueName, String exchangeName, String routingKey, boolean nowait) + throws + QpidException; + //Todo: Do we need to define more specific exceptions like exchange does not exist? + + /** + * Unbind a queue from an exchange. + * + * @param queueName The queue to be unbound. + * @param exchangeName The exchange name. + * @param routingKey The routing key. + * @throws QpidException If the session fails to unbind the queue due to some error. + */ + public void unbindQueue(String queueName, String exchangeName, String routingKey) + throws + QpidException; + //Todo: Do we need to define more specific exceptions like exchange does not exist? + + /** + * Purge a queue. i.e. delete all enqueued messages + * TODO: Define the exact semantic i.e. are message sent to a dead letter queue? + * + * @param queueName The queue to be purged + * @param nowait nowait + * @throws QpidException If the session fails to purge the queue due to some error. + */ + public void purgeQueue(String queueName, boolean nowait) + throws + QpidException; + + /** + * Delet a queue. + *

        see available options: {@link DeleteQueueOption} + *

        When non of the options are set then The queue is immediately deleted even + * if it still contains messages or if ti is used by another resource. + * + * @param queueName The name of the queue to be deleted + * @param options Set of options + * @throws QpidException If the session fails to delete the queue due to some error. + * @see DeleteQueueOption + */ + public void deleteQueue(String queueName, DeleteQueueOption options) + throws + QpidException; + + /** + * Declare an exchange. + *

        see available options: {@link DeclareExchangeOption} + *

        When non of the options are set then the exchange is declared with: + *

          + *
        • auto_delete = false + *
        • non-durable + *
        • internal = false + *
        • nowait = false + *
        • not passive + *
        + * + * @param exchangeName The exchange name. + * @param exchangeClass The fully qualified name of the exchange class. + * @param options Set of options. + * @throws QpidException If the session fails to declare the exchange due to some error. + * @see DeclareExchangeOption + */ + public void declareExchange(String exchangeName, String exchangeClass, DeclareExchangeOption... options) + throws + QpidException; + //Todo: Do we need to define more specific exceptions like exchange already exist? + + /** + * Delete an exchange. + *

        see available options: {@link DeclareExchangeOption} + *

        When non of the options are set then the exchange + * Immediately deleted even if it is used by another resources. + * + * @param exchangeName The name of exchange to be deleted. + * @param options Set of options. + * @throws QpidException If the session fails to delete the exchange due to some error. + * @see DeleteExchangeOption + */ + public void deleteExchange(String exchangeName, DeleteExchangeOption... options) + throws + QpidException; + //Todo: Do we need to define more specific exceptions like exchange does not exist? +} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/declareQueueOption.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/declareQueueOption.java new file mode 100644 index 0000000000..5eb3b7927a --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/declareQueueOption.java @@ -0,0 +1,17 @@ +package org.apache.qpid.nclient.qpidapi; + +/** + * Enumeration of the options available when declaring a queue + * + * Created by Arnaud Simon + * Date: 23-Jul-2007 + * Time: 09:44:36 + */ +public enum declareQueueOption +{ + AUTO_DELETE, + DURABLE, + EXCLUSIVE, + NOWAIT, + PASSIVE; +} -- cgit v1.2.1 From be5ce35e4a9fb4a5a358522c23855da11116829c Mon Sep 17 00:00:00 2001 From: Arnaud Simon Date: Mon, 23 Jul 2007 13:40:31 +0000 Subject: Removed the inline option (this was a 0.9 parameter) git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@558724 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/nclient/qpidapi/MessageSender.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageSender.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageSender.java index cbe1443798..545c06e67e 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageSender.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageSender.java @@ -22,7 +22,7 @@ import org.apache.qpid.nclient.exception.QpidException; /** * A sender is used to send message to its queue. - * + *

        * Created by Arnaud Simon * Date: 22-Jul-2007 * Time: 09:41:58 @@ -34,11 +34,11 @@ public interface MessageSender extends Resource * Sends a message to this sender queue. * * @param message The message to be sent - * @param inline //TODO - * @throws QpidException If the sender fails to send the message due to some error. - * @throws IllegalStateException If this sender was closed or its session suspended. + * @throws QpidException If the sender fails to send the message due to some error. + * @throws IllegalStateException If this sender was closed or its session suspended. */ - public void send(Message message, boolean inline) throws - QpidException, - IllegalStateException; + public void send(Message message) + throws + QpidException, + IllegalStateException; } -- cgit v1.2.1 From bbca10722a085a990391d1f43ba439fa75f6ec04 Mon Sep 17 00:00:00 2001 From: Arnaud Simon Date: Mon, 23 Jul 2007 14:54:31 +0000 Subject: git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@558760 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpid/nclient/FieldTable.java | 28 --- .../qpid/nclient/exception/QpidException.java | 48 ---- .../apache/qpid/nclient/qpidapi/Connection.java | 81 ------- .../qpid/nclient/qpidapi/CreateReceiverOption.java | 16 -- .../nclient/qpidapi/DeclareExchangeOption.java | 17 -- .../qpid/nclient/qpidapi/DeleteExchangeOption.java | 12 - .../qpid/nclient/qpidapi/DeleteQueueOption.java | 13 -- .../apache/qpid/nclient/qpidapi/DtxSession.java | 43 ---- .../org/apache/qpid/nclient/qpidapi/Message.java | 126 ----------- .../qpid/nclient/qpidapi/MessageListener.java | 36 --- .../qpid/nclient/qpidapi/MessageReceiver.java | 95 -------- .../apache/qpid/nclient/qpidapi/MessageSender.java | 44 ---- .../org/apache/qpid/nclient/qpidapi/Resource.java | 54 ----- .../org/apache/qpid/nclient/qpidapi/Session.java | 247 --------------------- .../qpid/nclient/qpidapi/declareQueueOption.java | 17 -- 15 files changed, 877 deletions(-) delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/FieldTable.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/exception/QpidException.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Connection.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/CreateReceiverOption.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeclareExchangeOption.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteExchangeOption.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteQueueOption.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DtxSession.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Message.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageListener.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageReceiver.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageSender.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Resource.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Session.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/declareQueueOption.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/FieldTable.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/FieldTable.java deleted file mode 100644 index d79794e98d..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/FieldTable.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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.nclient; - -/** - * Created by Arnaud Simon - * Date: 23-Jul-2007 - * Time: 09:47:32 - */ -public interface FieldTable -{ -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/exception/QpidException.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/exception/QpidException.java deleted file mode 100644 index cacac98cc0..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/exception/QpidException.java +++ /dev/null @@ -1,48 +0,0 @@ -/* 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.nclient.exception; - -/** - * Created by Arnaud Simon - * Date: 20-Jul-2007 - * Time: 10:56:55 - */ -public class QpidException extends Exception -{ - /** - * This exception error code. - *

        This error code is used for internationalisation purpose. - *

        This error code is set from the AMQP ones. - * So we may want to use the AMQP error code directly. - */ - String _errorCode; - - /** - * Constructor for a Qpid Exception. - *

        This is the only provided constructor and the parameters have to be set to null when - * they are unknown. - * @param message A description of the reason of this exception . - * @param errorCode A string specifyin the error code of this exception. - * @param cause The linked Execption. - */ - public QpidException(String message, String errorCode, Throwable cause) - { - super(message, cause); - _errorCode = errorCode; - } -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Connection.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Connection.java deleted file mode 100644 index fd59b95c0f..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Connection.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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.nclient.qpidapi; - -import org.apache.qpid.nclient.exception.QpidException; - -import java.net.URL; - -/** - * This represents a physical connection to a broker. - *

        - * Created by Arnaud Simon - * Date: 20-Jul-2007 - * Time: 09:34:15 - */ -public interface Connection -{ - /** - * Establish the connection with the broker identified by the provided URL. - * - * @param url The URL of the broker. - * @throws QpidException If the communication layer fails to connect with the broker. - */ - public void connect(URL url) - throws - QpidException; - - /** - * Close this connection. - * - * @throws QpidException if the communication layer fails to close the connection. - */ - public void close() - throws - QpidException; - - - /** - * Create a session for this connection. - *

        The retuned session is suspended - * (i.e. this session is not attached with an underlying channel) - * - * @param expiryInSeconds Expiry time expressed in seconds, if the value is <= 0 then the session does not expire. - * @return A Newly created (suspended) session. - * @throws QpidException If the connection fails to create a session due to some internal error. - */ - public Session createSession(int expiryInSeconds) - throws - QpidException; - - /** - * Create a DtxSession for this connection. - *

        A Dtx Session must be used when resources have to be manipulated as - * part of a global transaction. - *

        The retuned DtxSession is suspended - * (i.e. this session is not attached with an underlying channel) - * - * @param expiryInSeconds Expiry time expressed in seconds, if the value is <= 0 then the session does not expire. - * @return A Newly created (suspended) DtxSession. - * @throws QpidException If the connection fails to create a DtxSession due to some internal error. - */ - public DtxSession createDTXSession(int expiryInSeconds) - throws - QpidException; -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/CreateReceiverOption.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/CreateReceiverOption.java deleted file mode 100644 index 4d8315c33b..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/CreateReceiverOption.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.apache.qpid.nclient.qpidapi; - -/** - * Enumeration of the options available when creating a receiver - * - * Created by Arnaud Simon - * Date: 20-Jul-2007 - * Time: 09:43:31 - */ -public enum CreateReceiverOption -{ - NO_LOCAL, - EXCLUSIVE, - NO_ACQUIRE, - CONFIRME; -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeclareExchangeOption.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeclareExchangeOption.java deleted file mode 100644 index 8674792252..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeclareExchangeOption.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.apache.qpid.nclient.qpidapi; - -/** - * Enumeration of the options available when declaring an exchange - * - * Created by Arnaud Simon - * Date: 20-Jul-2007 - * Time: 09:44:52 - */ -public enum DeclareExchangeOption -{ - AUTO_DELETE, - DURABLE, - INTERNAL, - NOWAIT, - PASSIVE; -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteExchangeOption.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteExchangeOption.java deleted file mode 100644 index 188d665c8c..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteExchangeOption.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.apache.qpid.nclient.qpidapi; - -/** - * Created by Arnaud Simon - * Date: 23-Jul-2007 - * Time: 12:55:55 - */ -public enum DeleteExchangeOption -{ - IF_UNUSED, - NOWAIT; -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteQueueOption.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteQueueOption.java deleted file mode 100644 index 0062218a70..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DeleteQueueOption.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.apache.qpid.nclient.qpidapi; - -/** - * Created by Arnaud Simon - * Date: 23-Jul-2007 - * Time: 12:44:43 - */ -public enum DeleteQueueOption -{ - IF_EMPTY, - IF_UNUSED, - NO_WAIT; -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DtxSession.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DtxSession.java deleted file mode 100644 index c361fdcf82..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/DtxSession.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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.nclient.qpidapi; - -import org.apache.qpid.nclient.exception.QpidException; - -/** - * This session’s resources are control under the scope of a distributed transaction. - * - * Created by Arnaud Simon - * Date: 20-Jul-2007 - * Time: 09:39:11 - */ -public interface DtxSession extends Session -{ - - /** - * Get the XA resource associated with this session. - * - * @return this session XA resource. - * @throws QpidException If the session fails to retrieve its associated XA resource - * due to some error. - */ - public javax.transaction.xa.XAResource getDTXResource() - throws - QpidException; -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Message.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Message.java deleted file mode 100644 index 6974d0cae2..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Message.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * 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.nclient.qpidapi; - - -import org.apache.qpid.nclient.FieldTable; -import org.apache.qpid.nclient.exception.QpidException; - -import java.nio.ByteBuffer; - -/** - * A message is sent and received by resources. It is composed of a set of header and a payload. - *

        - * Created by Arnaud Simon - * Date: 20-Jul-2007 - * Time: 09:40:49 - */ -public interface Message -{ - /** - * Get this message auto-allocated messageID. - * - * @return This message ID. - */ - public long getMessageID(); - - /** - * Set this message headers - *

        Previous headers are reset. - * - * @param headers The message headers as a field table. - * @see FieldTable - */ - public void setHeaders(FieldTable headers); - - /** - * Access to this message headers. - * - * @return This message headers as a field table. - */ - public FieldTable getHeaders(); - - /** - * Set this message payload. - * - * @param buffer This message payload. - */ - public void setBody(ByteBuffer buffer); - - /** - * Access this message body. - * - * @return The payload of this message. - */ - public ByteBuffer getBody(); - - /** - * Acknowledge the receipt of this message. - *

        The message must have been previously acquired either by receiving it in - * pre-acquire mode or by explicitly acquiring it. - * - * @throws QpidException If the acknowledgement of the message fails due to some error. - * @throws IllegalStateException If this messages is not acquired. - */ - public void acknowledge() - throws - QpidException, - IllegalStateException; - - /** - * Acknowledge the receipt of an acquired messages which IDs are within - * the interval [this.messageID, message.messageID] - * - * @param message The last message to be acknowledged. - * @throws QpidException If the acknowledgement of this set of messages fails due to some error. - * @throws IllegalStateException If some messages are not acquired. - */ - public void acknowledge(Message message) - throws - QpidException, - IllegalStateException; - - /** - * Reject a previously acquired message. - *

        A rejected message will not be delivered to any receiver - * and may be either discarded or moved to the broker dead letter queue. - * - * @throws QpidException If this message cannot be rejected dus to some error - * @throws IllegalStateException If this message is not acquired. - */ - public void reject() - throws - QpidException, - IllegalStateException; - - /** - * Try to acquire this message hence releasing it form the queue. This means that once acknowledged, - * this message will not be delivered to any other receiver. - *

        As this message may have been consumed by another receiver, message acquisition can fail. - * The outcome of the acquisition is returned as a Boolean. - * - * @return True if the message is successfully acquired, False otherwise. - * @throws QpidException If this message cannot be acquired dus to some error - * @throws IllegalStateException If this message has already been acquired. - */ - public boolean acquire() - throws - QpidException, - IllegalStateException; -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageListener.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageListener.java deleted file mode 100644 index d607d0a3c2..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageListener.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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.nclient.qpidapi; - -/** - * MessageListeners are used to asynchronously receive messages. - * - * Created by Arnaud Simon - * Date: 2o-Jul-2007 - * Time: 09:42:52 - */ -public interface MessageListener -{ - /** - * Deliver a message to the listener. - * - * @param message The message delivered to the listner. - */ - public void onMessage(Message message); -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageReceiver.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageReceiver.java deleted file mode 100644 index 6592857b2e..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageReceiver.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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.nclient.qpidapi; - -import org.apache.qpid.nclient.exception.QpidException; - -import java.util.Set; - -/** - * Used to receive messages from a queue - * - *

        - * Created by Arnaud Simon - * Date: 20-Jul-2007 - * Time: 09:42:37 - */ -public interface MessageReceiver extends Resource -{ - /** - * Get this receiver options. - * - * @return This receiver set of options. - */ - public Set getOptions(); - - /** - * Receive a message form this receiver queue. - *

        If the timeout is less or equal than 0 then this operation is blocking. - * Otherwise it blocks until a message arrives, the timeout expires, or this receiver is closed. - *

        To receive messages, a receiver must be started. - * - * @param timeout The timeout value (in milliseconds). - * @return A message or null if timeout expires or this receiver is concurrently closed. - * @throws QpidException If this receiver fails to receive a message due to some error. - * @throws IllegalStateException If this receiver is closed, not started or a MessageListener is set. - */ - public Message receive(long timeout) - throws - QpidException, - IllegalStateException; - - /** - * Stop the delivery of messages to this receiver. - * - * @throws QpidException If this receiver fails to be stopped due to some error. - * @throws IllegalStateException If this receiver is closed or already stopped. - */ - public void stop() - throws - QpidException, - IllegalStateException; - - /** - * Start the delivery of messages to this receiver. - * - * @throws QpidException If this receiver fails to be started due to some error. - * @throws IllegalStateException If this receiver is closed or already started. - */ - public void start() - throws - QpidException, - IllegalStateException; - - /** - * Set the receiver’s MessageListener. - * Setting the message listener to null is the equivalent of un-setting the message - * listener for this receiver. - *

        Once a message listener is set, a receiver cannot receive messages through its - * receive method. - * - * @param listener The message listner. - * @throws QpidException If this receiver fails to set the message listner due to some error. - * @throws IllegalStateException If this receiver is closed. - */ - public void setAsynchronous(MessageListener listener) - throws - QpidException, - IllegalStateException; -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageSender.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageSender.java deleted file mode 100644 index 545c06e67e..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/MessageSender.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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.nclient.qpidapi; - -import org.apache.qpid.nclient.exception.QpidException; - -/** - * A sender is used to send message to its queue. - *

        - * Created by Arnaud Simon - * Date: 22-Jul-2007 - * Time: 09:41:58 - */ -public interface MessageSender extends Resource -{ - - /** - * Sends a message to this sender queue. - * - * @param message The message to be sent - * @throws QpidException If the sender fails to send the message due to some error. - * @throws IllegalStateException If this sender was closed or its session suspended. - */ - public void send(Message message) - throws - QpidException, - IllegalStateException; -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Resource.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Resource.java deleted file mode 100644 index 29965e0045..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Resource.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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.nclient.qpidapi; - -import org.apache.qpid.nclient.exception.QpidException; - -/** - * A Resource is associated with a session and can be independently closed. - * - * Created by Arnaud Simon - * Date: 21-Jul-2007 - * Time: 09:41:30 - */ -public interface Resource -{ - - /** - * Close this resource. - * - * @throws QpidException If the session fails to close this resource due to some error - */ - public void close() throws - QpidException; - - /** - * Get this resource session. - * - * @return This resource's session. - */ - public Session getSession(); - - /** - * Get the queue name to which this resource is tied. - * - * @return The queue name of this resource. - */ - public String getQueueNAme(); -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Session.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Session.java deleted file mode 100644 index 24e47a7657..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/Session.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * 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.nclient.qpidapi; - -import org.apache.qpid.nclient.exception.QpidException; - -/** - * A session is associated with a connection. - *

        When created a Session is not attached with an underlying channel. Unsuspended a Session is - * equivalent to attaching a communication channel that can be used to communicate with the broker. - *

        - * Created by Arnaud Simon - * Date: 20-Jul-2007 - * Time: 09:36:24 - */ -public interface Session -{ - /** - * Close this session and any associated resources. - * - * @throws QpidException If the communication layer fails to close this session or if an internal error happens - * when closing this session resources. . - */ - public void close() - throws - QpidException; - - /** - * Suspend this session resulting in interrupting the traffic with the broker. - * When a session is suspend any operation of this session and of the associated resources is unavailable. - * - * @throws QpidException If the communication layer fails to suspend this session - */ - public void suspend() - throws - QpidException; - - /** - * Unsuspended a Session is equivalent to attaching a communication channel that can be used to - * communicate with the broker. All the operations of this session and of the associated resources - * are made available. - * - * @throws QpidException If the communication layer fails to unsuspend this session - */ - public void unsuspend() - throws - QpidException; - - /** - * Create a message sender for sending messages to queue queueName. - * - * @param queueName The queue this sender is sending messages. - * @return A sender for queue queueName - * @throws QpidException If the session fails to create the sended due to some error - */ - public MessageSender createSender(String queueName) - throws - QpidException; - //Todo: Do we need to define more specific exception like queue name not valid? - - /** - * Create a message receiver for receiving messages from queue queueName. - *

        see available options: {@link CreateReceiverOption} - *

        When non of the options are set then the receiver is created with: - *

          - *
        • no_local = false - *
        • non exclusive - *
        • pre-acquire mode - *
        • no confirmation - *
        - * - * @param queueName The queue this receiver is receiving messages from. - * @param options Set of Options. - * @return A receiver for queue queueName. - * @throws QpidException If the session fails to create the receiver due to some error. - * @see CreateReceiverOption - */ - public MessageReceiver createReceiver(String queueName, CreateReceiverOption... options) - throws - QpidException; - //Todo: Do we need to define more specific exceptions like queue name not valid? - - /** - * Commit the receipt and the delivery of all messages exchanged by this session resources. - * - * @throws QpidException If the session fails to commit due to some error. - * @throws IllegalStateException If this session is not transacted. - */ - public void commit() - throws - QpidException, - IllegalStateException; - - /** - * Rollback the receipt and the delivery of all messages exchanged by this session resources. - * - * @throws QpidException If the session fails to rollback due to some error. - * @throws IllegalStateException If this session is not transacted. - */ - public void rollback() - throws - QpidException, - IllegalStateException; - - /** - * Set this session as transacted. - *

        This operation is irreversible. - * - * @throws QpidException If the session fail to be transacted due to some error. - * @throws IllegalStateException If this session is already transacted. - */ - public void setTransacted() - throws - QpidException, - IllegalStateException; - - /** - * Declare a queue of name queueName - *

        see available options: {@link declareQueueOption} - *

        When non of the options are set then the receiver is created with: - *

          - *
        • auto_delete = false - *
        • non-durable - *
        • non-exccusive - *
        • nowait = false - *
        • not passive - *
        - * - * @param queueName The name of the delcared queue. - * @param options Set of Options. - * @throws QpidException If the session fails to declare the queue due to some error. - * @see declareQueueOption - */ - public void declareQueue(String queueName, declareQueueOption... options) - throws - QpidException; - //Todo: Do we need to define more specific exceptions like queue name already exist? - - /** - * Bind a queue with an exchange. - * - * @param queueName The queue to be bound. - * @param exchangeName The exchange name. - * @param routingKey The routing key. - * @param nowait nowait - * @throws QpidException If the session fails to bind the queue due to some error. - */ - public void bindQueue(String queueName, String exchangeName, String routingKey, boolean nowait) - throws - QpidException; - //Todo: Do we need to define more specific exceptions like exchange does not exist? - - /** - * Unbind a queue from an exchange. - * - * @param queueName The queue to be unbound. - * @param exchangeName The exchange name. - * @param routingKey The routing key. - * @throws QpidException If the session fails to unbind the queue due to some error. - */ - public void unbindQueue(String queueName, String exchangeName, String routingKey) - throws - QpidException; - //Todo: Do we need to define more specific exceptions like exchange does not exist? - - /** - * Purge a queue. i.e. delete all enqueued messages - * TODO: Define the exact semantic i.e. are message sent to a dead letter queue? - * - * @param queueName The queue to be purged - * @param nowait nowait - * @throws QpidException If the session fails to purge the queue due to some error. - */ - public void purgeQueue(String queueName, boolean nowait) - throws - QpidException; - - /** - * Delet a queue. - *

        see available options: {@link DeleteQueueOption} - *

        When non of the options are set then The queue is immediately deleted even - * if it still contains messages or if ti is used by another resource. - * - * @param queueName The name of the queue to be deleted - * @param options Set of options - * @throws QpidException If the session fails to delete the queue due to some error. - * @see DeleteQueueOption - */ - public void deleteQueue(String queueName, DeleteQueueOption options) - throws - QpidException; - - /** - * Declare an exchange. - *

        see available options: {@link DeclareExchangeOption} - *

        When non of the options are set then the exchange is declared with: - *

          - *
        • auto_delete = false - *
        • non-durable - *
        • internal = false - *
        • nowait = false - *
        • not passive - *
        - * - * @param exchangeName The exchange name. - * @param exchangeClass The fully qualified name of the exchange class. - * @param options Set of options. - * @throws QpidException If the session fails to declare the exchange due to some error. - * @see DeclareExchangeOption - */ - public void declareExchange(String exchangeName, String exchangeClass, DeclareExchangeOption... options) - throws - QpidException; - //Todo: Do we need to define more specific exceptions like exchange already exist? - - /** - * Delete an exchange. - *

        see available options: {@link DeclareExchangeOption} - *

        When non of the options are set then the exchange - * Immediately deleted even if it is used by another resources. - * - * @param exchangeName The name of exchange to be deleted. - * @param options Set of options. - * @throws QpidException If the session fails to delete the exchange due to some error. - * @see DeleteExchangeOption - */ - public void deleteExchange(String exchangeName, DeleteExchangeOption... options) - throws - QpidException; - //Todo: Do we need to define more specific exceptions like exchange does not exist? -} diff --git a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/declareQueueOption.java b/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/declareQueueOption.java deleted file mode 100644 index 5eb3b7927a..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpid/nclient/qpidapi/declareQueueOption.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.apache.qpid.nclient.qpidapi; - -/** - * Enumeration of the options available when declaring a queue - * - * Created by Arnaud Simon - * Date: 23-Jul-2007 - * Time: 09:44:36 - */ -public enum declareQueueOption -{ - AUTO_DELETE, - DURABLE, - EXCLUSIVE, - NOWAIT, - PASSIVE; -} -- cgit v1.2.1 From edf14006d9da4a9697c8354eaad8382f9b1bc1c0 Mon Sep 17 00:00:00 2001 From: "Rafael H. Schloming" Date: Tue, 24 Jul 2007 18:20:55 +0000 Subject: Initial submit of 0-10 communication layer. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@559151 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpidity/AbstractMethod.java | 31 +++++ .../main/java/org/apache/qpidity/BBDecoder.java | 109 +++++++++++++++++ .../main/java/org/apache/qpidity/BBEncoder.java | 110 +++++++++++++++++ .../main/java/org/apache/qpidity/BodyHandler.java | 38 ++++++ .../src/main/java/org/apache/qpidity/Channel.java | 91 ++++++++++++++ .../main/java/org/apache/qpidity/Connection.java | 59 +++++++++ .../java/org/apache/qpidity/ContentHandler.java | 42 +++++++ .../src/main/java/org/apache/qpidity/Decoder.java | 52 ++++++++ .../java/org/apache/qpidity/DelegateResolver.java | 36 ++++++ .../main/java/org/apache/qpidity/Delegator.java | 35 ++++++ .../src/main/java/org/apache/qpidity/Encoder.java | 52 ++++++++ .../src/main/java/org/apache/qpidity/Event.java | 44 +++++++ .../src/main/java/org/apache/qpidity/Frame.java | 135 +++++++++++++++++++++ .../src/main/java/org/apache/qpidity/Handler.java | 35 ++++++ .../src/main/java/org/apache/qpidity/Header.java | 30 +++++ .../java/org/apache/qpidity/HeaderHandler.java | 38 ++++++ .../src/main/java/org/apache/qpidity/Method.java | 34 ++++++ .../java/org/apache/qpidity/MethodDispatcher.java | 48 ++++++++ .../java/org/apache/qpidity/MethodHandler.java | 40 ++++++ .../src/main/java/org/apache/qpidity/Range.java | 51 ++++++++ .../src/main/java/org/apache/qpidity/Segment.java | 80 ++++++++++++ .../java/org/apache/qpidity/SegmentAssembler.java | 61 ++++++++++ .../src/main/java/org/apache/qpidity/Session.java | 70 +++++++++++ .../java/org/apache/qpidity/SessionResolver.java | 47 +++++++ .../src/main/java/org/apache/qpidity/Struct.java | 30 +++++ .../src/main/java/org/apache/qpidity/Stub.java | 78 ++++++++++++ .../src/main/java/org/apache/qpidity/Switch.java | 52 ++++++++ .../main/java/org/apache/qpidity/TrackSwitch.java | 39 ++++++ .../main/java/org/apache/qpidity/TypeSwitch.java | 39 ++++++ .../src/main/java/org/apache/qpidity/Writable.java | 34 ++++++ 30 files changed, 1640 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/AbstractMethod.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/BBEncoder.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/BodyHandler.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Channel.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Connection.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/ContentHandler.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Decoder.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/DelegateResolver.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Delegator.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Event.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Frame.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Handler.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Header.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/HeaderHandler.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Method.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/MethodDispatcher.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/MethodHandler.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Range.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Segment.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/SegmentAssembler.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Session.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/SessionResolver.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Struct.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Stub.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Switch.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/TrackSwitch.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/TypeSwitch.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Writable.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/AbstractMethod.java b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractMethod.java new file mode 100644 index 0000000000..663027e2d8 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractMethod.java @@ -0,0 +1,31 @@ +/* + * + * 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.qpidity; + +import java.nio.ByteBuffer; + +/** + * AbstractMethod + * + * @author Rafael H. Schloming + */ + +abstract class AbstractMethod implements Method {} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java new file mode 100644 index 0000000000..0a4c6ef063 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java @@ -0,0 +1,109 @@ +/* + * + * 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.qpidity; + +import java.nio.ByteBuffer; + +import java.util.Map; +import java.util.UUID; + +/** + * BBDecoder + * + * @author Rafael H. Schloming + */ + +class BBDecoder implements Decoder +{ + + private final ByteBuffer in; + + public BBDecoder(ByteBuffer in) { + this.in = in; + } + + public boolean readBit() + { + //throw new Error("TODO"); + return false; + } + + public byte readOctet() + { + throw new Error("TODO"); + } + + public short readShort() + { + return in.getShort(); + } + + public int readLong() + { + return in.getInt(); + } + + public long readLonglong() + { + throw new Error("TODO"); + } + + public long readTimestamp() + { + throw new Error("TODO"); + } + + + public String readShortstr() + { + byte size = in.get(); + byte[] bytes = new byte[size]; + in.get(bytes); + return new String(bytes); + } + + public String readLongstr() + { + throw new Error("TODO"); + } + + public Map readTable() + { + //throw new Error("TODO"); + return null; + } + + public Range[] readRfc1982LongSet() + { + throw new Error("TODO"); + } + + public UUID readUuid() + { + throw new Error("TODO"); + } + + public String readContent() + { + throw new Error("TODO"); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/BBEncoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/BBEncoder.java new file mode 100644 index 0000000000..36edf278f3 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/BBEncoder.java @@ -0,0 +1,110 @@ +/* + * + * 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.qpidity; + +import java.nio.ByteBuffer; + +import java.util.Map; +import java.util.UUID; + +/** + * BBEncoder + * + * @author Rafael H. Schloming + */ + +class BBEncoder implements Encoder +{ + + private final ByteBuffer out; + + public BBEncoder(ByteBuffer out) { + this.out = out; + } + + public void writeBit(boolean b) + { + //throw new Error("TODO"); + } + + public void writeOctet(byte b) + { + out.put(b); + } + + public void writeShort(short s) + { + out.putShort(s); + } + + public void writeLong(int i) + { + out.putInt(i); + } + + public void writeLonglong(long l) + { + throw new Error("TODO"); + } + + + public void writeTimestamp(long l) + { + throw new Error("TODO"); + } + + + public void writeShortstr(String s) + { + if (s.length() > 255) { + throw new IllegalArgumentException(s); + } + writeOctet((byte) s.length()); + out.put(s.getBytes()); + } + + public void writeLongstr(String s) + { + throw new Error("TODO"); + } + + + public void writeTable(Map table) + { + //throw new Error("TODO"); + } + + public void writeRfc1982LongSet(Range[] ranges) + { + throw new Error("TODO"); + } + + public void writeUuid(UUID uuid) + { + throw new Error("TODO"); + } + + public void writeContent(String c) + { + throw new Error("TODO"); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/BodyHandler.java b/qpid/java/common/src/main/java/org/apache/qpidity/BodyHandler.java new file mode 100644 index 0000000000..0b772c6f04 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/BodyHandler.java @@ -0,0 +1,38 @@ +/* + * + * 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.qpidity; + + +/** + * BodyHandler + * + * @author Rafael H. Schloming + */ + +class BodyHandler implements Handler> +{ + + public void handle(Event event) + { + System.out.println("got body frame: " + event.target); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Channel.java b/qpid/java/common/src/main/java/org/apache/qpidity/Channel.java new file mode 100644 index 0000000000..a9060622e8 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Channel.java @@ -0,0 +1,91 @@ +/* + * + * 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.qpidity; + + +/** + * Channel + * + * @author Rafael H. Schloming + */ + +class Channel extends Invoker + implements Handler, DelegateResolver +{ + + final private Connection connection; + final private TrackSwitch tracks; + + + // session may be null + private Session session; + + public Channel(Connection connection) + { + this.connection = connection; + tracks = new TrackSwitch(); + tracks.map(Frame.L1, new MethodHandler()); + tracks.map(Frame.L2, new MethodHandler()); + tracks.map(Frame.L3, new SessionResolver(new MethodHandler())); + tracks.map(Frame.L4, new SessionResolver(new ContentHandler())); + } + + public Session getSession() + { + return session; + } + + void setSession(Session session) + { + this.session = session; + } + + public void handle(Frame frame) + { + tracks.handle(new Event(this, frame)); + } + + public void write(Writable writable) + { + System.out.println("writing: " + writable); + } + + protected StructFactory getFactory() + { + return connection.getFactory(); + } + + public Delegate resolve(Struct struct) + { + return new ChannelDelegate(); + } + + protected void invoke(Method m) + { + write(m); + } + + protected void invoke(Method m, Handler handler) + { + throw new UnsupportedOperationException(); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Connection.java b/qpid/java/common/src/main/java/org/apache/qpidity/Connection.java new file mode 100644 index 0000000000..bb8b945051 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Connection.java @@ -0,0 +1,59 @@ +/* + * + * 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.qpidity; + +import java.util.HashMap; +import java.util.Map; + +/** + * Connection + * + * @author Rafael H. Schloming + * + * @todo the channels map should probably be replaced with something + * more efficient, e.g. an array or a map implementation that can use + * short instead of Short + */ + +class Connection implements Handler +{ + + final private Map channels = new HashMap(); + final private StructFactory factory = new StructFactory_v0_10(); + + public void handle(Frame frame) + { + Channel channel = channels.get(frame.getChannel()); + if (channel == null) + { + channel = new Channel(this); + channels.put(frame.getChannel(), channel); + } + + channel.handle(frame); + } + + public StructFactory getFactory() + { + return factory; + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/ContentHandler.java b/qpid/java/common/src/main/java/org/apache/qpidity/ContentHandler.java new file mode 100644 index 0000000000..ea73a3574d --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/ContentHandler.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.qpidity; + + +/** + * ContentHandler is a stateful handler that aggregates and dispatches + * method and header frames, and passes body frames through to another + * handler. + * + * @author Rafael H. Schloming + */ + +class ContentHandler> extends TypeSwitch +{ + + public ContentHandler() + { + map(Frame.METHOD, new SegmentAssembler(new MethodDispatcher())); + map(Frame.HEADER, new SegmentAssembler(new HeaderHandler())); + map(Frame.BODY, new BodyHandler()); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Decoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/Decoder.java new file mode 100644 index 0000000000..5001d3ebee --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Decoder.java @@ -0,0 +1,52 @@ +/* + * + * 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.qpidity; + +import java.util.Map; +import java.util.UUID; + +/** + * Decoder + * + * @author Rafael H. Schloming + */ + +public interface Decoder +{ + + boolean readBit(); + byte readOctet(); + short readShort(); + int readLong(); + long readLonglong(); + + long readTimestamp(); + + String readShortstr(); + String readLongstr(); + + Map readTable(); + Range[] readRfc1982LongSet(); + UUID readUuid(); + + String readContent(); + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/DelegateResolver.java b/qpid/java/common/src/main/java/org/apache/qpidity/DelegateResolver.java new file mode 100644 index 0000000000..632781847e --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/DelegateResolver.java @@ -0,0 +1,36 @@ +/* + * + * 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.qpidity; + + +/** + * A DelegateResolver locates the desired delegate to use for handling + * a given Struct. + * + * @author Rafael H. Schloming + */ + +interface DelegateResolver +{ + + Delegate resolve(Struct struct); + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Delegator.java b/qpid/java/common/src/main/java/org/apache/qpidity/Delegator.java new file mode 100644 index 0000000000..00e769e0f2 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Delegator.java @@ -0,0 +1,35 @@ +/* + * + * 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.qpidity; + + +/** + * Delegator + * + * @author Rafael H. Schloming + */ + +interface Delegator +{ + + void delegate(C context, Delegate delegate); + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java new file mode 100644 index 0000000000..27360a551a --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java @@ -0,0 +1,52 @@ +/* + * + * 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.qpidity; + +import java.util.Map; +import java.util.UUID; + +/** + * Encoder + * + * @author Rafael H. Schloming + */ + +public interface Encoder +{ + + void writeBit(boolean b); + void writeOctet(byte b); + void writeShort(short s); + void writeLong(int i); + void writeLonglong(long l); + + void writeTimestamp(long l); + + void writeShortstr(String s); + void writeLongstr(String s); + + void writeTable(Map table); + void writeRfc1982LongSet(Range[] ranges); + void writeUuid(UUID uuid); + + void writeContent(String c); + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Event.java b/qpid/java/common/src/main/java/org/apache/qpidity/Event.java new file mode 100644 index 0000000000..ae210f4c20 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Event.java @@ -0,0 +1,44 @@ +/* + * + * 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.qpidity; + + +/** + * Events are a common class of thing to handle. An event has a + * context and a target. This division permits the same target + * instance to be used in a variety of contexts. + * + * @author Rafael H. Schloming + */ + +public class Event +{ + + C context; + T target; + + public Event(C context, T target) + { + this.context = context; + this.target = target; + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Frame.java b/qpid/java/common/src/main/java/org/apache/qpidity/Frame.java new file mode 100644 index 0000000000..298400d511 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Frame.java @@ -0,0 +1,135 @@ +/* + * + * 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.qpidity; + +import java.nio.ByteBuffer; +import java.nio.ShortBuffer; + +/** + * Frame + * + * @author Rafael H. Schloming + */ + +class Frame +{ + + public static final short L1 = 0; + public static final short L2 = 1; + public static final short L3 = 2; + public static final short L4 = 3; + + public static final short METHOD = 1; + public static final short HEADER = 2; + public static final short BODY = 3; + + final private short channel; + final private short track; + final private short type; + final private boolean firstSegment; + final private boolean lastSegment; + final private boolean firstFrame; + final private boolean lastFrame; + final private ByteBuffer payload; + + // XXX + final private int sequence = 0; + + public Frame(short channel, short track, short type, boolean firstSegment, + boolean lastSegment, boolean firstFrame, boolean lastFrame, + ByteBuffer payload) + { + this.channel = channel; + this.track = track; + this.type = type; + this.firstSegment = firstSegment; + this.lastSegment = lastSegment; + this.firstFrame = firstFrame; + this.lastFrame = lastFrame; + this.payload = payload; + } + + public short getChannel() + { + return channel; + } + + public short getTrack() + { + return track; + } + + public short getType() + { + return type; + } + + public boolean isFirstSegment() + { + return firstSegment; + } + + public boolean isLastSegment() + { + return lastSegment; + } + + public boolean isFirstFrame() + { + return firstFrame; + } + + public boolean isLastFrame() + { + return lastFrame; + } + + public ByteBuffer getPayload() + { + return payload.slice(); + } + + public int getSize() + { + return payload.remaining(); + } + + public String toString() + { + StringBuilder str = new StringBuilder(); + str.append(String.format + ("[%05d %05d %1d %1d %d%d%d%d]", channel, track, type, + getSize(), + firstSegment ? 1 : 0, lastSegment ? 1 : 0, + firstFrame ? 1 : 0, lastFrame ? 1 : 0)); + ShortBuffer shorts = payload.asShortBuffer(); + for (int i = 0; i < shorts.limit(); i++) { + str.append(String.format(" %04x", shorts.get(i))); + if (str.length() > 70) { + str.append(" ..."); + break; + } + } + + return str.toString(); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Handler.java b/qpid/java/common/src/main/java/org/apache/qpidity/Handler.java new file mode 100644 index 0000000000..0ff949cc1d --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Handler.java @@ -0,0 +1,35 @@ +/* + * + * 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.qpidity; + +/** + * Handler is a basic interface used throughout this library for + * callbacks, listeners, event handlers, etc. + * + * @author Rafael H. Schloming + */ + +public interface Handler +{ + + void handle(E event); + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Header.java b/qpid/java/common/src/main/java/org/apache/qpidity/Header.java new file mode 100644 index 0000000000..1d494c6d41 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Header.java @@ -0,0 +1,30 @@ +/* + * + * 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.qpidity; + + +/** + * Header + * + * @author Rafael H. Schloming + */ + +interface Header extends Struct {} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/HeaderHandler.java b/qpid/java/common/src/main/java/org/apache/qpidity/HeaderHandler.java new file mode 100644 index 0000000000..a63c032e38 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/HeaderHandler.java @@ -0,0 +1,38 @@ +/* + * + * 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.qpidity; + + +/** + * HeaderHandler + * + * @author Rafael H. Schloming + */ + +class HeaderHandler implements Handler> +{ + + public void handle(Event event) + { + System.out.println("got header segment:\n " + event.target); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Method.java b/qpid/java/common/src/main/java/org/apache/qpidity/Method.java new file mode 100644 index 0000000000..12a7b48f94 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Method.java @@ -0,0 +1,34 @@ +/* + * + * 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.qpidity; + + +/** + * Method + * + * @author Rafael H. Schloming + */ + +interface Method extends Struct { + + int getEncodingType(); + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/MethodDispatcher.java b/qpid/java/common/src/main/java/org/apache/qpidity/MethodDispatcher.java new file mode 100644 index 0000000000..a2a4ebb0fc --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/MethodDispatcher.java @@ -0,0 +1,48 @@ +/* + * + * 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.qpidity; + +import java.nio.ByteBuffer; + +/** + * A MethodDispatcher parses and dispatches a method segment. + * + * @author Rafael H. Schloming + */ + +class MethodDispatcher> + implements Handler> +{ + + // XXX: should be passed in + final private StructFactory factory = new StructFactory_v0_10(); + + public void handle(Event event) + { + System.out.println("got method segment:\n " + event.target); + ByteBuffer bb = event.target.getPayload(); + int type = bb.getInt(); + Struct struct = factory.create(type, new BBDecoder(bb)); + Delegate delegate = event.context.resolve(struct); + struct.delegate(event.context, delegate); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/MethodHandler.java b/qpid/java/common/src/main/java/org/apache/qpidity/MethodHandler.java new file mode 100644 index 0000000000..ebc7471622 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/MethodHandler.java @@ -0,0 +1,40 @@ +/* + * + * 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.qpidity; + + +/** + * MethodHandler is a stateful handler that aggregates frames into + * method segments and dispatches the resulting method. It does not + * accept any segment type other than Frame.METHOD. + * + * @author Rafael H. Schloming + */ + +class MethodHandler> extends TypeSwitch +{ + + public MethodHandler() + { + map(Frame.METHOD, new SegmentAssembler(new MethodDispatcher())); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Range.java b/qpid/java/common/src/main/java/org/apache/qpidity/Range.java new file mode 100644 index 0000000000..4766ecb471 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Range.java @@ -0,0 +1,51 @@ +/* + * + * 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.qpidity; + + +/** + * Range + * + * @author Rafael H. Schloming + */ + +public class Range +{ + private final C lower; + private final C upper; + + public Range(C lower, C upper) + { + this.lower = lower; + this.upper = upper; + } + + public C getLower() + { + return lower; + } + + public C getUpper() + { + return upper; + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Segment.java b/qpid/java/common/src/main/java/org/apache/qpidity/Segment.java new file mode 100644 index 0000000000..cd1d4ab05d --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Segment.java @@ -0,0 +1,80 @@ +/* + * + * 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.qpidity; + +import java.nio.ByteBuffer; + +import java.util.ArrayList; +import java.util.Collection; + +/** + * Segment + * + * @author Rafael H. Schloming + */ + +class Segment +{ + + private final Collection frames = new ArrayList(); + + public void add(Frame frame) + { + frames.add(frame); + } + + public ByteBuffer getPayload() + { + // we should probably use our own decoder interface here so + // that we can directly read from the incoming frame objects + // and automatically skip frame boundaries without copying + // everything in order to get a contiguous byte buffer + int capacity = 0; + for (Frame frame : frames) + { + capacity += frame.getSize(); + } + ByteBuffer buf = ByteBuffer.allocate(capacity); + for (Frame frame : frames) + { + buf.put(frame.getPayload()); + } + buf.flip(); + return buf; + } + + public String toString() + { + StringBuffer buf = new StringBuffer(); + String sep = ",\n "; + + for (Frame f : frames) + { + buf.append(f.toString()); + buf.append(sep); + } + + buf.setLength(buf.length() - sep.length()); + + return buf.toString(); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/SegmentAssembler.java b/qpid/java/common/src/main/java/org/apache/qpidity/SegmentAssembler.java new file mode 100644 index 0000000000..2d47e760c1 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/SegmentAssembler.java @@ -0,0 +1,61 @@ +/* + * + * 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.qpidity; + +import java.nio.ByteBuffer; + +/** + * SegmentAssembler is a stateful handler that aggregates Frame events + * into Segment events. This should only be used where it is necessary + * to assemble a Segment before processing, e.g. for Method and Header + * segments. + * + * @author Rafael H. Schloming + */ + +class SegmentAssembler implements Handler> +{ + + final private Handler> handler; + private Segment segment; + + public SegmentAssembler(Handler> handler) + { + this.handler = handler; + } + + public void handle(Event event) + { + Frame frame = event.target; + if (frame.isFirstFrame()) + { + segment = new Segment(); + } + + segment.add(frame); + + if (frame.isLastFrame()) + { + handler.handle(new Event(event.context, segment)); + } + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Session.java b/qpid/java/common/src/main/java/org/apache/qpidity/Session.java new file mode 100644 index 0000000000..32da625070 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Session.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.qpidity; + +import java.util.HashMap; +import java.util.Map; + +/** + * Session + * + * @author Rafael H. Schloming + */ + +public class Session extends Invoker implements DelegateResolver +{ + + // channel may be null + Channel channel; + private int command_id = 0; + // XXX + final Map> handlers = new HashMap>(); + final private Delegate delegate = new SessionDelegate(); + + public void attach(Channel channel) + { + this.channel = channel; + channel.setSession(this); + } + + protected void invoke(Method m) + { + command_id++; + channel.write(m); + } + + protected void invoke(Method m, Handler handler) + { + invoke(m); + handlers.put(command_id, handler); + } + + protected StructFactory getFactory() + { + return channel.getFactory(); + } + + public Delegate resolve(Struct struct) + { + return delegate; + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/SessionResolver.java b/qpid/java/common/src/main/java/org/apache/qpidity/SessionResolver.java new file mode 100644 index 0000000000..24e52839fd --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/SessionResolver.java @@ -0,0 +1,47 @@ +/* + * + * 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.qpidity; + + +/** + * SessionResolver is a stateless handler that accepts incoming events + * whose context is a Channel, and produces an event whose context is + * a Session. + * + * @author Rafael H. Schloming + */ + +class SessionResolver implements Handler> +{ + + final private Handler> handler; + + public SessionResolver(Handler> handler) + { + this.handler = handler; + } + + public void handle(Event event) + { + handler.handle(new Event(event.context.getSession(), event.target)); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Struct.java b/qpid/java/common/src/main/java/org/apache/qpidity/Struct.java new file mode 100644 index 0000000000..6d9913b042 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Struct.java @@ -0,0 +1,30 @@ +/* + * + * 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.qpidity; + + +/** + * Struct + * + * @author Rafael H. Schloming + */ + +interface Struct extends Delegator, Writable {} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java new file mode 100644 index 0000000000..d8de56f8b1 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java @@ -0,0 +1,78 @@ +package org.apache.qpidity; + +import java.nio.ByteBuffer; +import java.util.*; +import java.lang.annotation.*; + +public class Stub { + + private static Connection conn = new Connection(); + + private static void frame(short track, short type, boolean first, boolean last) { + frame(track, type, first, last, null); + } + + private static void frame(short track, short type, boolean first, boolean last, Method m) { + ByteBuffer buf = ByteBuffer.allocate(512); + if (m != null) { + buf.putInt(m.getEncodingType()); + m.write(new BBEncoder(buf)); + } + buf.flip(); + Frame frame = new Frame((short)0, track, type, true, true, first, last, buf); + conn.handle(frame); + } + + public static final void main(String[] args) { + StructFactory f = new StructFactory_v0_10(); + frame(Frame.L2, Frame.METHOD, true, true, f.newSessionOpen(0)); + frame(Frame.L4, Frame.METHOD, true, false, f.newQueueDeclare((short) 0, "asdf", "alternate", false, false, false, false, false, null)); + frame(Frame.L4, Frame.METHOD, false, false); + frame(Frame.L3, Frame.METHOD, true, true, f.newExchangeDeclare((short) 0, "exchange", "type", "alternate", false, false, false, null)); + frame(Frame.L4, Frame.METHOD, false, true); + frame(Frame.L4, Frame.HEADER, true, false); + frame(Frame.L4, Frame.HEADER, false, false); + frame(Frame.L4, Frame.HEADER, false, true); + frame(Frame.L4, Frame.BODY, true, false); + frame(Frame.L4, Frame.BODY, false, false); + frame(Frame.L4, Frame.BODY, false, false); + frame(Frame.L1, Frame.METHOD, true, true, f.newExchangeDeclare((short) 0, "exchange", "type", "alternate", false, false, false, null)); + frame(Frame.L4, Frame.BODY, false, false); + frame(Frame.L4, Frame.BODY, false, true); + } + +} + +//====: Channel and Session Delegates :=======================================// + +class ChannelDelegate extends Delegate { + + public @Override void sessionOpen(Channel channel, SessionOpen open) { + Session ssn = new Session(); + ssn.attach(channel); + System.out.println("Session Open"); + } + +} + +class SessionDelegate extends Delegate { + + public @Override void queueDeclare(Session session, QueueDeclare qd) { + System.out.println("got a queue declare: " + qd.getQueue()); + } + + public @Override void exchangeDeclare(Session session, ExchangeDeclare ed) { + System.out.println("got an exchange declare: " + ed.getExchange() + ", " + ed.getType()); + session.queueDeclare((short) 0, "asdf", "alternate", false, false, false, false, false, null); + } + + /* + public @Override void executionResult(Session session, ExecutionResult result) { + Handler handler = session.handlers.get(result.getCommandId()); + if (handler != null) { + handler.handle(result.getData()); + } + } + */ + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Switch.java b/qpid/java/common/src/main/java/org/apache/qpidity/Switch.java new file mode 100644 index 0000000000..a84ae1507b --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Switch.java @@ -0,0 +1,52 @@ +/* + * + * 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.qpidity; + +import java.util.HashMap; +import java.util.Map; + +/** + * A Switch performs generic event dispatch. + * + * @author Rafael H. Schloming + */ + +abstract class Switch implements Handler +{ + + final private Map> handlers = + new HashMap>(); + + public void map(K key, Handler handler) + { + handlers.put(key, handler); + } + + public void handle(E event) + { + K key = resolve(event); + Handler handler = handlers.get(key); + handler.handle(event); + } + + abstract K resolve(E event); + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/TrackSwitch.java b/qpid/java/common/src/main/java/org/apache/qpidity/TrackSwitch.java new file mode 100644 index 0000000000..c9b3cda032 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/TrackSwitch.java @@ -0,0 +1,39 @@ +/* + * + * 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.qpidity; + + +/** + * A TrackSwitch sends incoming frames to a different handler based on + * track. + * + * @author Rafael H. Schloming + */ + +class TrackSwitch extends Switch> +{ + + public Short resolve(Event event) + { + return event.target.getTrack(); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/TypeSwitch.java b/qpid/java/common/src/main/java/org/apache/qpidity/TypeSwitch.java new file mode 100644 index 0000000000..a5073486c7 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/TypeSwitch.java @@ -0,0 +1,39 @@ +/* + * + * 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.qpidity; + + +/** + * A TypeSwitch sends incoming frames to a different handler based on + * type. + * + * @author Rafael H. Schloming + */ + +class TypeSwitch extends Switch> +{ + + public Short resolve(Event event) + { + return event.target.getType(); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Writable.java b/qpid/java/common/src/main/java/org/apache/qpidity/Writable.java new file mode 100644 index 0000000000..9554da880a --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Writable.java @@ -0,0 +1,34 @@ +/* + * + * 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.qpidity; + +/** + * Writable + * + * @author Rafael H. Schloming + */ + +interface Writable +{ + + void write(Encoder enc); + +} -- cgit v1.2.1 From f6ce4582d32b38dee7139dd286a7abcc4f8695cc Mon Sep 17 00:00:00 2001 From: "Rafael H. Schloming" Date: Tue, 24 Jul 2007 19:25:43 +0000 Subject: Switched over to using enums instead of booleans for fields of type bit. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@559167 13f79535-47bb-0310-9956-ffa450edef68 --- qpid/java/common/src/main/java/org/apache/qpidity/Stub.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java index d8de56f8b1..25700e43ca 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java @@ -4,6 +4,8 @@ import java.nio.ByteBuffer; import java.util.*; import java.lang.annotation.*; +import static org.apache.qpidity.Option.*; + public class Stub { private static Connection conn = new Connection(); @@ -26,9 +28,11 @@ public class Stub { public static final void main(String[] args) { StructFactory f = new StructFactory_v0_10(); frame(Frame.L2, Frame.METHOD, true, true, f.newSessionOpen(0)); - frame(Frame.L4, Frame.METHOD, true, false, f.newQueueDeclare((short) 0, "asdf", "alternate", false, false, false, false, false, null)); + frame(Frame.L4, Frame.METHOD, true, false, + f.newQueueDeclare((short) 0, "asdf", "alternate", null, DURABLE)); frame(Frame.L4, Frame.METHOD, false, false); - frame(Frame.L3, Frame.METHOD, true, true, f.newExchangeDeclare((short) 0, "exchange", "type", "alternate", false, false, false, null)); + frame(Frame.L3, Frame.METHOD, true, true, + f.newExchangeDeclare((short) 0, "exchange", "type", "alternate", null)); frame(Frame.L4, Frame.METHOD, false, true); frame(Frame.L4, Frame.HEADER, true, false); frame(Frame.L4, Frame.HEADER, false, false); @@ -36,7 +40,8 @@ public class Stub { frame(Frame.L4, Frame.BODY, true, false); frame(Frame.L4, Frame.BODY, false, false); frame(Frame.L4, Frame.BODY, false, false); - frame(Frame.L1, Frame.METHOD, true, true, f.newExchangeDeclare((short) 0, "exchange", "type", "alternate", false, false, false, null)); + frame(Frame.L1, Frame.METHOD, true, true, + f.newExchangeDeclare((short) 0, "exchange", "type", "alternate", null)); frame(Frame.L4, Frame.BODY, false, false); frame(Frame.L4, Frame.BODY, false, true); } @@ -63,7 +68,7 @@ class SessionDelegate extends Delegate { public @Override void exchangeDeclare(Session session, ExchangeDeclare ed) { System.out.println("got an exchange declare: " + ed.getExchange() + ", " + ed.getType()); - session.queueDeclare((short) 0, "asdf", "alternate", false, false, false, false, false, null); + session.queueDeclare((short) 0, "asdf", "alternate", null); } /* -- cgit v1.2.1 From 0451496093c7d07807f9181d3bc89434f5034aa8 Mon Sep 17 00:00:00 2001 From: "Rafael H. Schloming" Date: Wed, 25 Jul 2007 14:08:08 +0000 Subject: added support for precomputing sizes git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@559465 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpidity/AbstractMethod.java | 2 +- .../java/org/apache/qpidity/AbstractStruct.java | 30 +++++ .../src/main/java/org/apache/qpidity/Frame.java | 3 +- .../src/main/java/org/apache/qpidity/Method.java | 2 +- .../main/java/org/apache/qpidity/SizeEncoder.java | 122 +++++++++++++++++++++ .../src/main/java/org/apache/qpidity/Stub.java | 10 +- 6 files changed, 162 insertions(+), 7 deletions(-) create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/AbstractStruct.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/SizeEncoder.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/AbstractMethod.java b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractMethod.java index 663027e2d8..7db1aeea43 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/AbstractMethod.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractMethod.java @@ -28,4 +28,4 @@ import java.nio.ByteBuffer; * @author Rafael H. Schloming */ -abstract class AbstractMethod implements Method {} +abstract class AbstractMethod extends AbstractStruct implements Method {} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/AbstractStruct.java b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractStruct.java new file mode 100644 index 0000000000..6e70fe3db4 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractStruct.java @@ -0,0 +1,30 @@ +/* + * + * 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.qpidity; + + +/** + * AbstractStruct + * + * @author Rafael H. Schloming + */ + +public abstract class AbstractStruct implements Struct {} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Frame.java b/qpid/java/common/src/main/java/org/apache/qpidity/Frame.java index 298400d511..d1bebd8365 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Frame.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Frame.java @@ -116,8 +116,7 @@ class Frame { StringBuilder str = new StringBuilder(); str.append(String.format - ("[%05d %05d %1d %1d %d%d%d%d]", channel, track, type, - getSize(), + ("[%05d %05d %1d %1d %d%d%d%d]", channel, getSize(), track, type, firstSegment ? 1 : 0, lastSegment ? 1 : 0, firstFrame ? 1 : 0, lastFrame ? 1 : 0)); ShortBuffer shorts = payload.asShortBuffer(); diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Method.java b/qpid/java/common/src/main/java/org/apache/qpidity/Method.java index 12a7b48f94..75e3bdfbaa 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Method.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Method.java @@ -29,6 +29,6 @@ package org.apache.qpidity; interface Method extends Struct { - int getEncodingType(); + int getEncodedType(); } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/SizeEncoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/SizeEncoder.java new file mode 100644 index 0000000000..53cc055e72 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/SizeEncoder.java @@ -0,0 +1,122 @@ +/* + * + * 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.qpidity; + +import java.nio.ByteBuffer; + +import java.util.Map; +import java.util.UUID; + +/** + * SizeEncoder + * + * @author Rafael H. Schloming + */ + +class SizeEncoder implements Encoder +{ + + private int size; + + public SizeEncoder() { + this(0); + } + + public SizeEncoder(int size) { + this.size = size; + } + + public int getSize() { + return size; + } + + public void setSize(int size) { + this.size = size; + } + + public void writeBit(boolean b) + { + //throw new Error("TODO"); + } + + public void writeOctet(byte b) + { + size += 1; + } + + public void writeShort(short s) + { + size += 2; + } + + public void writeLong(int i) + { + size += 4; + } + + public void writeLonglong(long l) + { + size += 8; + } + + + public void writeTimestamp(long l) + { + size += 8; + } + + + public void writeShortstr(String s) + { + if (s.length() > 255) { + throw new IllegalArgumentException(s); + } + writeOctet((byte) s.length()); + size += s.length(); + } + + public void writeLongstr(String s) + { + throw new Error("TODO"); + } + + + public void writeTable(Map table) + { + //throw new Error("TODO"); + } + + public void writeRfc1982LongSet(Range[] ranges) + { + throw new Error("TODO"); + } + + public void writeUuid(UUID uuid) + { + throw new Error("TODO"); + } + + public void writeContent(String c) + { + throw new Error("TODO"); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java index 25700e43ca..1e42096462 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java @@ -15,9 +15,13 @@ public class Stub { } private static void frame(short track, short type, boolean first, boolean last, Method m) { - ByteBuffer buf = ByteBuffer.allocate(512); + SizeEncoder sizer = new SizeEncoder(); if (m != null) { - buf.putInt(m.getEncodingType()); + m.write(sizer); + } + ByteBuffer buf = ByteBuffer.allocate(sizer.getSize() + 4); + if (m != null) { + buf.putInt(m.getEncodedType()); m.write(new BBEncoder(buf)); } buf.flip(); @@ -29,7 +33,7 @@ public class Stub { StructFactory f = new StructFactory_v0_10(); frame(Frame.L2, Frame.METHOD, true, true, f.newSessionOpen(0)); frame(Frame.L4, Frame.METHOD, true, false, - f.newQueueDeclare((short) 0, "asdf", "alternate", null, DURABLE)); + f.newQueueDeclare((short) 0, "asdf", "alternate", null, DURABLE)); frame(Frame.L4, Frame.METHOD, false, false); frame(Frame.L3, Frame.METHOD, true, true, f.newExchangeDeclare((short) 0, "exchange", "type", "alternate", null)); -- cgit v1.2.1 From 1d41acbbe7f13db8e91bf55337c0e7d660b5e169 Mon Sep 17 00:00:00 2001 From: "Rafael H. Schloming" Date: Wed, 25 Jul 2007 16:44:32 +0000 Subject: fixed Encoder/Decoder to do the property type conversion for unsigned types git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@559520 13f79535-47bb-0310-9956-ffa450edef68 --- .../main/java/org/apache/qpidity/BBDecoder.java | 40 ++++++++++++++++------ .../main/java/org/apache/qpidity/BBEncoder.java | 22 +++++++----- .../src/main/java/org/apache/qpidity/Decoder.java | 8 ++--- .../src/main/java/org/apache/qpidity/Encoder.java | 8 ++--- .../main/java/org/apache/qpidity/SizeEncoder.java | 8 ++--- 5 files changed, 55 insertions(+), 31 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java index 0a4c6ef063..9c5da34cd1 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java @@ -34,9 +34,25 @@ import java.util.UUID; class BBDecoder implements Decoder { + private static final short unsigned(byte b) + { + return (short) ((0x100 + b) & 0xFF); + } + + private static final int unsigned(short s) + { + return (0x10000 + s) & 0xFFFF; + } + + private static final long unsigned(int i) + { + return (0x1000000000L + i) & 0xFFFFFFFFL; + } + private final ByteBuffer in; - public BBDecoder(ByteBuffer in) { + public BBDecoder(ByteBuffer in) + { this.in = in; } @@ -46,19 +62,19 @@ class BBDecoder implements Decoder return false; } - public byte readOctet() + public short readOctet() { - throw new Error("TODO"); + return unsigned(in.get()); } - public short readShort() + public int readShort() { - return in.getShort(); + return unsigned(in.getShort()); } - public int readLong() + public long readLong() { - return in.getInt(); + return unsigned(in.getInt()); } public long readLonglong() @@ -74,7 +90,7 @@ class BBDecoder implements Decoder public String readShortstr() { - byte size = in.get(); + short size = readOctet(); byte[] bytes = new byte[size]; in.get(bytes); return new String(bytes); @@ -82,7 +98,11 @@ class BBDecoder implements Decoder public String readLongstr() { - throw new Error("TODO"); + long size = readLong(); + assert size <= Integer.MAX_VALUE; + byte[] bytes = new byte[(int) size]; + in.get(bytes); + return new String(bytes); } public Map readTable() @@ -91,7 +111,7 @@ class BBDecoder implements Decoder return null; } - public Range[] readRfc1982LongSet() + public Range[] readRfc1982LongSet() { throw new Error("TODO"); } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/BBEncoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/BBEncoder.java index 36edf278f3..50b8659fd7 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/BBEncoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/BBEncoder.java @@ -45,19 +45,22 @@ class BBEncoder implements Encoder //throw new Error("TODO"); } - public void writeOctet(byte b) + public void writeOctet(short b) { - out.put(b); + assert b < 0x100; + out.put((byte) b); } - public void writeShort(short s) + public void writeShort(int s) { - out.putShort(s); + assert s < 0x10000; + out.putShort((short) s); } - public void writeLong(int i) + public void writeLong(long i) { - out.putInt(i); + assert i < 0x100000000L; + out.putInt((int) i); } public void writeLonglong(long l) @@ -77,13 +80,14 @@ class BBEncoder implements Encoder if (s.length() > 255) { throw new IllegalArgumentException(s); } - writeOctet((byte) s.length()); + writeOctet((short) s.length()); out.put(s.getBytes()); } public void writeLongstr(String s) { - throw new Error("TODO"); + writeLong(s.length()); + out.put(s.getBytes()); } @@ -92,7 +96,7 @@ class BBEncoder implements Encoder //throw new Error("TODO"); } - public void writeRfc1982LongSet(Range[] ranges) + public void writeRfc1982LongSet(Range[] ranges) { throw new Error("TODO"); } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Decoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/Decoder.java index 5001d3ebee..26191fa7ba 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Decoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Decoder.java @@ -33,9 +33,9 @@ public interface Decoder { boolean readBit(); - byte readOctet(); - short readShort(); - int readLong(); + short readOctet(); + int readShort(); + long readLong(); long readLonglong(); long readTimestamp(); @@ -44,7 +44,7 @@ public interface Decoder String readLongstr(); Map readTable(); - Range[] readRfc1982LongSet(); + Range[] readRfc1982LongSet(); UUID readUuid(); String readContent(); diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java index 27360a551a..716df97397 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java @@ -33,9 +33,9 @@ public interface Encoder { void writeBit(boolean b); - void writeOctet(byte b); - void writeShort(short s); - void writeLong(int i); + void writeOctet(short b); + void writeShort(int s); + void writeLong(long i); void writeLonglong(long l); void writeTimestamp(long l); @@ -44,7 +44,7 @@ public interface Encoder void writeLongstr(String s); void writeTable(Map table); - void writeRfc1982LongSet(Range[] ranges); + void writeRfc1982LongSet(Range[] ranges); void writeUuid(UUID uuid); void writeContent(String c); diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/SizeEncoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/SizeEncoder.java index 53cc055e72..745f58fd6d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/SizeEncoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/SizeEncoder.java @@ -57,17 +57,17 @@ class SizeEncoder implements Encoder //throw new Error("TODO"); } - public void writeOctet(byte b) + public void writeOctet(short b) { size += 1; } - public void writeShort(short s) + public void writeShort(int s) { size += 2; } - public void writeLong(int i) + public void writeLong(long i) { size += 4; } @@ -104,7 +104,7 @@ class SizeEncoder implements Encoder //throw new Error("TODO"); } - public void writeRfc1982LongSet(Range[] ranges) + public void writeRfc1982LongSet(Range[] ranges) { throw new Error("TODO"); } -- cgit v1.2.1 From fe3a5a511ff1e5d099b2b8a0089cc81aedcb103b Mon Sep 17 00:00:00 2001 From: Rajith Muditha Attapattu Date: Wed, 25 Jul 2007 19:34:17 +0000 Subject: first attempt at isolating session functions common to both broker and client git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@559570 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpidity/CommonSessionDelegate.java | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java b/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java new file mode 100644 index 0000000000..b8efa857f6 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java @@ -0,0 +1,27 @@ +package org.apache.qpidity; + +public class CommonSessionDelegate extends Delegate +{ + + public void sessionAttached(Session session, SessionAttached struct) {} + + public void sessionFlow(Session session, SessionFlow struct) {} + + public void sessionFlowOk(Session session, SessionFlowOk struct) {} + + public void sessionClose(Session session, SessionClose struct) {} + + public void sessionClosed(Session session, SessionClosed struct) {} + + public void sessionResume(Session session, SessionResume struct) {} + + public void sessionPing(Session session, SessionPing struct) {} + + public void sessionPong(Session session, SessionPong struct) {} + + public void sessionSuspend(Session session, SessionSuspend struct) {} + + public void sessionDetached(Session session, SessionDetached struct) {} + + +} -- cgit v1.2.1 From 609cb1359a12e7cc7f476d4a5e8a05bdcb9a3c22 Mon Sep 17 00:00:00 2001 From: "Rafael H. Schloming" Date: Thu, 26 Jul 2007 13:44:17 +0000 Subject: exclude ticket arguments and extraneous classes git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@559815 13f79535-47bb-0310-9956-ffa450edef68 --- qpid/java/common/src/main/java/org/apache/qpidity/Stub.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java index 1e42096462..34a4e4bd44 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java @@ -33,10 +33,10 @@ public class Stub { StructFactory f = new StructFactory_v0_10(); frame(Frame.L2, Frame.METHOD, true, true, f.newSessionOpen(0)); frame(Frame.L4, Frame.METHOD, true, false, - f.newQueueDeclare((short) 0, "asdf", "alternate", null, DURABLE)); + f.newQueueDeclare("asdf", "alternate", null, DURABLE)); frame(Frame.L4, Frame.METHOD, false, false); frame(Frame.L3, Frame.METHOD, true, true, - f.newExchangeDeclare((short) 0, "exchange", "type", "alternate", null)); + f.newExchangeDeclare("exchange", "type", "alternate", null)); frame(Frame.L4, Frame.METHOD, false, true); frame(Frame.L4, Frame.HEADER, true, false); frame(Frame.L4, Frame.HEADER, false, false); @@ -45,7 +45,7 @@ public class Stub { frame(Frame.L4, Frame.BODY, false, false); frame(Frame.L4, Frame.BODY, false, false); frame(Frame.L1, Frame.METHOD, true, true, - f.newExchangeDeclare((short) 0, "exchange", "type", "alternate", null)); + f.newExchangeDeclare("exchange", "type", "alternate", null)); frame(Frame.L4, Frame.BODY, false, false); frame(Frame.L4, Frame.BODY, false, true); } @@ -72,7 +72,7 @@ class SessionDelegate extends Delegate { public @Override void exchangeDeclare(Session session, ExchangeDeclare ed) { System.out.println("got an exchange declare: " + ed.getExchange() + ", " + ed.getType()); - session.queueDeclare((short) 0, "asdf", "alternate", null); + session.queueDeclare("asdf", "alternate", null); } /* -- cgit v1.2.1 From 302ff4e537cd1b6335b09fe915f6f36c0c81b99d Mon Sep 17 00:00:00 2001 From: Rajith Muditha Attapattu Date: Fri, 27 Jul 2007 14:38:59 +0000 Subject: moved the QpidException to common from client git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@560250 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpidity/QpidException.java | 59 ++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/QpidException.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/QpidException.java b/qpid/java/common/src/main/java/org/apache/qpidity/QpidException.java new file mode 100644 index 0000000000..4ab99b677f --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/QpidException.java @@ -0,0 +1,59 @@ +/* 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.qpidity; + +/** + * Created by Arnaud Simon + * Date: 20-Jul-2007 + * Time: 10:56:55 + */ +public class QpidException extends Exception +{ + /** + * This exception error code. + *

        This error code is used for internationalisation purpose. + *

        This error code is set from the AMQP ones. + * So we may want to use the AMQP error code directly. + */ + private String _errorCode; + + /** + * Constructor for a Qpid Exception. + *

        This is the only provided constructor and the parameters have to be set to null when + * they are unknown. + * @param message A description of the reason of this exception . + * @param errorCode A string specifyin the error code of this exception. + * @param cause The linked Execption. + */ + public QpidException(String message, String errorCode, Throwable cause) + { + super(message, cause); + _errorCode = errorCode; + } + + /** + * Get this execption error code. + * + * @return This exception error code. + */ + public String getErrorCode() + { + return _errorCode; + } +} + -- cgit v1.2.1 From 23854471da707ba6541291587f05fb08d2ce5f3f Mon Sep 17 00:00:00 2001 From: Rajith Muditha Attapattu Date: Fri, 27 Jul 2007 22:13:15 +0000 Subject: modified the generate script to add throws QpidException to the methods in Invoker git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@560406 13f79535-47bb-0310-9956-ffa450edef68 --- qpid/java/common/src/main/java/org/apache/qpidity/Stub.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java index 34a4e4bd44..be246d325b 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java @@ -72,7 +72,14 @@ class SessionDelegate extends Delegate { public @Override void exchangeDeclare(Session session, ExchangeDeclare ed) { System.out.println("got an exchange declare: " + ed.getExchange() + ", " + ed.getType()); - session.queueDeclare("asdf", "alternate", null); + try + { + session.queueDeclare("asdf", "alternate", null); + } + catch(Exception e) + { + + } } /* -- cgit v1.2.1 From e484a2bd3e5801fcf0332d791abe3e71fa0d2927 Mon Sep 17 00:00:00 2001 From: Rajith Muditha Attapattu Date: Mon, 30 Jul 2007 17:50:38 +0000 Subject: made the Header interface public, so I could use that in the Qpid API git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@561066 13f79535-47bb-0310-9956-ffa450edef68 --- qpid/java/common/src/main/java/org/apache/qpidity/Header.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Header.java b/qpid/java/common/src/main/java/org/apache/qpidity/Header.java index 1d494c6d41..57e04cacdf 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Header.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Header.java @@ -27,4 +27,4 @@ package org.apache.qpidity; * @author Rafael H. Schloming */ -interface Header extends Struct {} +public interface Header extends Struct {} -- cgit v1.2.1 From 4fbd28b6078d6b3fbfe528a99d6e27963c68f99b Mon Sep 17 00:00:00 2001 From: Martin Ritchie Date: Tue, 31 Jul 2007 15:53:37 +0000 Subject: Merged revisions 1-447993,447995-448007,448009-448141,448143-448157,448161-448194,448196-448210,448212-448218,448220-448223,448225-448233,448235,448237-448241,448243-448596,448598-448623,448625-448850,448852-448880,448882-448982,448984-449635,449637-449639,449641-449642,449644-449645,449647-449674,449676-449719,449721-449749,449751-449762,449764-449933,449935-449941,449943-450383,450385,450387-450400,450402-450433,450435-450503,450505-450555,450557-450860,450862-451024,451026-451149,451151-451316,451318-451931,451933-452139,452141-452162,452164-452320,452322,452324-452325,452327-452333,452335-452429,452431-452528,452530-452545,452547-453192,453194-453195,453197-453536,453538,453540-453656,453658-454676,454678-454735,454737,454739-454781,454783-462728,462730-462819,462821-462833,462835-462839,462841-463071,463073-463178,463180-463308,463310-463362,463364-463375,463377-463396,463398-463402,463404-463409,463411-463661,463663-463670,463672-463673,463675-464493,464495-464502,464504-464576,464578-464613,464615-464628,464630,464632-464866,464868-464899,464901-464942,464944-464949,464951-465004,465006-465016,465018-465053,465055-465165,465167-465321,465323-465406,465408-465427,465429-465431,465433-465548,465550-466044,466047-466075,466077,466079-466081,466083-466099,466101-466112,466114-466126,466128-466240,466242-466971,466973-466978,466980-467309,467311-467312,467316-467328,467330-467485,467487-467588,467590-467604,467606-467699,467701-467706,467708-467749,467751-468069,468071-468537,468539-469241,469244-469246,469248-469318,469320-469421,469423,469425-469429,469431-469435,469437-469462,469464-469469,469472-469477,469479-469490,469492-469503,469505-469529,469531-469598,469600-469624,469626-469737,469739-469752,469754-469806,469808-469928,469930-469953,469955-470011,470013-470109,470111-470335,470338-470339,470341-470379,470381,470383-470399,470401-470446,470448-470741,470743-470758,470760-470809,470811-470817,470819-470993,470995-471001,471003-471788,471790-471792,471794-472028,472030-472032,472034-472036,472038,472040,472043,472045-472059,472061,472063,472065-472066,472068,472070-472072,472074-472080,472082,472084-472092,472094-472107,472109-472123,472125-472158,472160-472165,472167-472172,472174-472457,472459-472460,472462-472464,472466-472470,472472-472483,472486-472491,472493-472494,472496-472497,472499,472501-472503,472505-472512,472514-472544,472546-472556,472558-472560,472562-472572,472574-472587,472589-472591,472593-472605,472607,472609-472731,472733-472786,472788-472843,472845-472849,472851-472859,472861-472878,472880-472903,472905,472907-472988,472990-472991,472993-473071,473073-473086,473088-473090,473093,473095-473096,473098-473106,473108-473110,473112-473185,473187-473260,473262,473268-473270,473275-473279,473281,473284-473287,473289-473295,473297-473306,473308-473330,473332-473335,473337,473339-473344,473346-473351,473353-473355,473357-473358,473361-473471,473473-473497,473499-473535,473537-473567,473569-473888,473890-474451,474454-474492,474494-474563,474565-474843,474845-474865,474867-474932,474934-475035,475037-475144,475146-475180,475182-475265,475267-475285,475287,475289-475293,475295-475296,475298-475302,475304-475631,475633-475649,475651-475748,475750-475752,475754-476107,476109-476302,476304-476413,476415-476430,476432-476700,476702-476868,476870-477147,477149-477213,477215-477263,477265-477340,477342-477635,477637-477789,477791-477825,477827-477841,477843,477846-477852,477854,477856,477858-477865,477867-477894,477896-478022,478024-478182,478184-478211,478213-478233,478235-478236,478238-478241,478243-478252,478254-478259,478261-478263,478265,478267-478269,478271-478286,478288-478342,478344-478379,478381-478412,478414-478443,478445-478636,478639-478658,478660-478821,478823-478853,478855-478922,478924-478962,478965-478974,478976-479029,479031-479049,479051-479210,479212-479214,479216-479407,479409-479415,479417-479425,479427-479559,479561-479639,479641-479676,479678-479685,479687-480030,480033-480086,480091-480093,480095-480118,480120-480139,480141,480143-480148,480150-480156,480158-480163,480165-480177,480179-480189,480191-480193,480195-480198,480200-480220,480222-480282,480284-480292,480294-480308,480310-480317,480320-480422,480424,480426-480581,480583-480656,480658-480692,480695-480702,480704,480706-480710,480712-480910,480913-480933,480935-480945,480947-480972,480974-480993,480995-481034,481036-481158,481161-481174,481176-481220,481222-481234,481236-481260,481263-481264,481266-481296,481298-481304,481306-481311,481313-481332,481334,481336-481380,481382-481441,481443-482144,482146-482180,482182-482193,482195-482232,482234-482236,482239,482241-482242,482244-482247,482250-482251,482253,482256-482261,482264-482288,482290-482364,482366,482368,482370-482554,482556,482558-482569,482572-482636,482638,482640-482696,482698-482722,482724-482732,482734-482771,482774-482957,482959-483045,483047-483105,483108,483110-483115,483117,483119-483127,483130-483134,483136-483148,483150-483158,483160-483164,483166-483178,483180-483391,483393-483400,483402-483403,483405-483418,483420-483421,483425-483436,483438-483470,483472-483502,483504-483558,483560-483599,483601-483637,483639-483644,483646-483659,483661-483670,483672-483878,483880-483910,483912-483915,483917-483940,483942,483944-483968,483970-483972,483974-483976,483978,483980-484612,484614-484657,484659-484693,484695-484718,484720-484842,484844-484847,484849-484986,484988-485019,485021-485489,485491-485544,485546-485591,485593,485595-485697,485699-485729,485731-485734,485736-485779,485781-485787,485789-485851,485853,485855-486007,486009,486011-486020,486022-486083,486085-486097,486099-486117,486120-486131,486133-486148,486150-486161,486163-486164,486166-486197,486199-486205,486208-486247,486249-486253,486256-486427,486429-486431,486433-486554,486556-486573,486575-486593,486595,486597-486609,486611-486619,486622,486625,486627-486641,486643-486645,486649-486687,486689-486721,486723-486730,486732-486746,486748-486759,486761,486763-486777,486779-486782,486784-486788,486790,486792,486794-486796,486798-487175,487178,487180-487213,487215,487217-487267,487269-487284,487286-487298,487300-487358,487360-487367,487369-487382,487384-487434,487436-487480,487482-487547,487549-487561,487563-487565,487567-487578,487580-487615,487617-487622,487624,487626,487628,487630-487635,487637-487703,487705-487777,487780-487781,487783-487800,487802-487803,487805-487820,487822-487848,487850-487902,487904-488103,488105-488133,488135-488158,488160-488163,488165-488187,488189-488216,488218-488248,488250-488278,488280,488282-488303,488305-488313,488315-488342,488344-488351,488353-488376,488378-488449,488451-488593,488595,488597-488623,488625-488700,488702-488704,488706-488710,488714,488716-488725,488727-488744,488746-488770,488772-488798,488800,488802-488807,488809,488811-488829,488831-488843,488845-488851,488853-489069,489071-489077,489079-489081,489084-489102,489104-489105,489107-489109,489111-489112,489114-489139,489141-489178,489181-489203,489205-489211,489213,489216-489329,489332-489402,489404-489417,489419-489421,489423-489643,489645-489690,489692-489703,489705-489714,489716-489747,489749-489753,489755-489803,489805-489904,489906-490372,490374-490504,490506-490604,490606-490707,490710-490733,490735-490871,490873-490984,490986-491028,491030,491032-491071,491073-491119,491121-491576,491578-491672,491674-491800,491802-491838,491840-491878,491880-492183,492185-492279,492281-492317,492319-492513,492515-492584,492586-492587,492589-492601,492603-492635,492637-492640,492642-492717,492719-492723,492725-492729,492731-492755,492757-492901,492903-492955,492957-492962,492964-492997,492999-493002,493004-493041,493043-493059,493062-493063,493065-493086,493088-493125,493127-493139,493141-493150,493152-493871,493873-494017,494019-494030,494032-494041,494043-494091,494093-494120,494122-494354,494356-494436,494438-494539,494541-494552,494554-494586,494588-494649,494651,494653-494654,494656-494657,494659-494764,494766-494768,494770-494796,494798-494799,494802,494804-494860,494862-494903,494905-494906,494908-495019,495021-495160,495162-495168,495171-495188,495190-495229,495231-495254,495256-495303,495305-495313,495315-495336,495338-495372,495374-495379,495381-495454,495457-495459,495462-495516,495518-495524,495526-495531,495533-495548,495551-495553,495555,495557-495558,495560,495562-495573,495575-495583,495585-495594,495596-495628,495630-495638,495640-495651,495653-495660,495662-495753,495755-496259,496261-496262,496264-496269,496271-496275,496277-496301,496303-496316,496318-496383,496385-496413,496415-496495,496497-496625,496627-496636,496638-496640,496642-496647,496650-496657,496659-496660,496663-496664,496666-496677,496679-496681,496683-496730,496732-496750,496752,496754-496784,496786-496832,496834-496840,496842-496990,496992-496995,496997-497340,497343-497351,497353-497403,497405-497424,497426-497438,497440-497481,497483-497497,497499-497765,497767-497769,497771-497775,497777-497778,497780,497782-497783,497785,497787-497812,497814-497871,497873-497877,497879-498573,498575-498588,498590,498592,498594-498636,498638-498669,498671-498686,498688-498689,498691-498719,498721-498964,498966-498969,498971-498973,498975-498982,498985-499035,499037-499040,499042,499044-499048,499050-499082,499084-499086,499088-499164,499167-499169,499171-499355,499357-499370,499372-499373,499375-499391,499393,499395-499425,499428,499430-499445,499447-499455,499457-499460,499462-499465,499467,499469-499489,499491-499492,499494-499531,499533-499562,499566-499627,499629-499715,499717-499732,499734-499755,499758-499763,499765-499780,499782-499795,499797-499802,499804-499844,499846,499848-499850,499852-499863,499865-499873,499875-499974,499976-499978,499980-500263,500265-500283,500285-500309,500311-501000,501002,501012-501057,501059-501095,501097-501390,501392-501410,501413-501447,501449-501454,501456,501458-501464,501466-501471,501473-501803,501805-501913,501915-501916,501918-501919,501921-501944,501946-502171,502173-502177,502181,502183-502247,502250-502252,502254-502260,502262-502267,502270,502272,502274-502575,502577-502609,502611-502619,502621-502626,502628-502654,502656-503592,503594-503603,503605-503608,503610-503636,503638-503645,503647-503705,503707-503789,503791-504024,504026-504111,504113-504506,504508-504735,504737-504863,504865-504867,504869-504914,504916-505241,505243-505254,505257-505267,505269-505354,505356-505891,505893-505971,505973-506400,506402-506404,506407-506438,506440-506516,506518-506541,506543-506966,506968-506971,506973-507095,507097-507108,507111-507454,507456,507459-507471,507473-507556,507558,507560-507581,507585-507594,507597,507599-507608,507610-507728,507730-507893,507895-507937,507940-508234,508236-508350,508352-508365,508367-508380,508383,508386-508415,508417-508648,508650-508941,508943-509146,509148-509171,509173-509175,509179-509201,509203-509207,509209-509215,509217-509222,509224-509477,509480-509627,509629-509634,509636-509641,509643-509736,509738-509931,509933-510059,510061-510075,510077-510158,510161-510896,510898-510938,510940-511388,511390-511922,511924-512287,512289-512698,512702-512813,512815-512817,512819-513359,513361-513370,513372-514702,514704-514886,514888-514902,514904-515126,515129-515141,515143-515516,515518-515534,515536-515538,515540-515648,515650-515651,515653-516070,516072-516411,516413-516448,516450,516452-517637,517639-517647,517649-517659,517661-517663,517665-517677,517679-517682,517684-517744,517746-518085,518087-518175,518177-518558,518560-518568,518571-518666,518668,518670-518699,518701-518987,518990-518992,518994-519908,519910-519932,519934-520414,520416-520842,520844-520937,520939-521362,521364-521681,521683-521704,521706-521709,521711-521714,521716-521781,521783-521792,521794-522462,522464-522527,522529-522534,522536-522566,522568-522958,522960,522962-522966,522968-522976,522978-522980,522982-522988,522992-522993,522995-523244,523246-523746,523748-524049,524051-524738,524741-524742,524744-524762,524764,524766,524768-525486,525488-525530,525532,525534,525537-525552,525554-525765,525767-525776,525778-525784,525789-525803,525805-525816,525818-525828,525830-525861,525863-525866,525868-526090,526092-526112,526114-526116,526119-526121,526123-526149,526151-526153,526155-526156,526160-526165,526167-526186,526188-526193,526196-526197,526200-526665,526667-526682,526686-526690,526693,526695-526708,526710-526713,526715-526775,526777-526802,526804-526806,526808-527048,527051-527052,527054-527181,527183-527486,527488-527492,527494-527498,527500-527508,527510-527517,527519-527536,527538-527555,527559-527802,527804-527842,527844-527847,527849-527875,527877-527940,527942-527958,527960-527971,527973-528002,528004,528006-528423,528425-529232,529234-529245,529247-529296,529298-529634,529636-529658,529660-529665,529667-529668,529670-530033,530035-530036,530038-530040,530045-530046,530050-530051,530053-530431,530433-530436,530439-530440,530443,530445-530446,530448,530450-530682,530684,530687-530696,530698-530733,530735-530776,530778-530795,530799,530801-530811,530813-530818,530820-530837,530839-531436,531438-531455,531457,531459-531511,531514,531516,531519-531523,531525,531528-531858,531860-531864,531866-531907,531909-531916,531918-531936,531938-531988,531990-532001,532003-532371,532373-532465,532467-532727,532729-532765,532767-532785,532788-532790,532792-532793,532795-533064,533066-533074,533076,533080-533130,533132-533139,533142-533703,533705-533720,533722-533763,533766-533818,533820-533839,533841-533859,533862-534035,534037-534112,534114-534116,534118-534472,534474-534477,534479-534762,534764-534896,534898-534902,534904-535253,535255-535308,535310-535808,535810-535873,535875-536007,536009-536140,536142-536162,536165-536242,536244-536252,536254-536278,536280-536338,536340-536448,536450-536479,536481-536482,536484-536485,536487-536495,536497,536500-536505,536507-536561,536563-536570,536572,536574-536583,536586-536823,536825-537014,537016-537018,537020-537025,537027-537028,537030-537160,537162-537170,537172-537672,537674-537781,537783-537833,537836-537840,537842-537844,537846-537953,537955-538034,538036-538078,538080-538083,538085-538097,538099-538108,538110-538239,538241-538881,538883-538906,538908-538911,538913-538921,538923-539177,539179-539190,539192-539469,539471-539475,539477-539480,539482-539483,539485-539500,539502-539593,539595-539782,539784-539787,539789-540106,540108-540168,540170-540510,540512-541246,541248-542483,542485-542788,542790-543495,543497-544108,544110-544421,544423-544507,544509-544865,544867-545145,545147-546095,546097-546189,546191-546440,546442-546457,546459-547177,547179-547626,547628-548275,548277-548278,548280-548301,548303-548307,548309-548311,548313-548314,548316,548318,548320-548380,548382-549010,549012-549529,549531-549848,549850-550508,550510-550747,550749-550772,550774-550848,550850-551116,551122-553446,553448-561282 via svnmerge from https://svn.apache.org/repos/asf/incubator/qpid/branches/M2 ........ r541920 | tomasr | 2007-05-26 18:35:51 +0100 (Sat, 26 May 2007) | 1 line QPID-136 Initial Prefetch Implementation ........ r549112 | arnaudsimon | 2007-06-20 15:11:03 +0100 (Wed, 20 Jun 2007) | 1 line changed setText to use UTF8 as default encoder ........ r551167 | arnaudsimon | 2007-06-27 15:08:50 +0100 (Wed, 27 Jun 2007) | 1 line added public void declareAndBind(AMQDestination amqd) ........ r551174 | ritchiem | 2007-06-27 15:23:21 +0100 (Wed, 27 Jun 2007) | 3 lines Caused each of these tests to run 10 times to help identify any race conditions that were occuring. Updated the CommitRollbackTest to be more robust in the detection of failure. ........ r551175 | ritchiem | 2007-06-27 15:23:52 +0100 (Wed, 27 Jun 2007) | 1 line Allowed more of the constants to be set via system properties. ........ r551176 | ritchiem | 2007-06-27 15:25:13 +0100 (Wed, 27 Jun 2007) | 1 line renamed the passwd programme qpid-passwd to match the change in bin directory. ........ r552441 | rupertlssmith | 2007-07-02 10:23:54 +0100 (Mon, 02 Jul 2007) | 1 line Added log4j as slfj logger for perftests. ........ r552499 | rupertlssmith | 2007-07-02 15:17:45 +0100 (Mon, 02 Jul 2007) | 1 line Added some documentation. ........ r553172 | rupertlssmith | 2007-07-04 12:11:04 +0100 (Wed, 04 Jul 2007) | 1 line Messages moved by management console now commited on the message store. ........ r553248 | ritchiem | 2007-07-04 17:05:55 +0100 (Wed, 04 Jul 2007) | 6 lines Addition of the MessageStore Tool. Small changes to the Exchanges to allow the extraction of currently listed items. Extracted initial broker configuration mechanism to a reusable class. Have modified broker to use it. Move the Passwd.java to new tools package structure on the broker. ........ r553265 | ritchiem | 2007-07-04 17:42:59 +0100 (Wed, 04 Jul 2007) | 1 line Tidied up some extranious logging. ........ r553432 | rupertlssmith | 2007-07-05 10:28:33 +0100 (Thu, 05 Jul 2007) | 1 line Fixed test state carrying over to mandatory message test from immediate. Also added in-vm clean up to other tests. ........ r553480 | ritchiem | 2007-07-05 13:40:50 +0100 (Thu, 05 Jul 2007) | 2 lines Minor changes and tidy up when running via command line. Added Copy command. ........ r553482 | ritchiem | 2007-07-05 13:44:42 +0100 (Thu, 05 Jul 2007) | 2 lines Forgot to compile before committing. Missed a method change in the Select command. ........ r554964 | rupertlssmith | 2007-07-10 15:40:04 +0100 (Tue, 10 Jul 2007) | 1 line Added message copy method. ........ r555249 | rupertlssmith | 2007-07-11 12:52:39 +0100 (Wed, 11 Jul 2007) | 1 line Update perftests to center better around current performance. ........ r556011 | rupertlssmith | 2007-07-13 15:24:03 +0100 (Fri, 13 Jul 2007) | 1 line Moved test framework into its own package and cleaned it up. ........ r556024 | rupertlssmith | 2007-07-13 16:02:06 +0100 (Fri, 13 Jul 2007) | 1 line Completed javadoc for test framework. ........ r556628 | rgodfrey | 2007-07-16 14:50:57 +0100 (Mon, 16 Jul 2007) | 1 line QPID-537 : Make AMQMessage.incrementReference public ........ r556675 | cctrieloff | 2007-07-16 18:36:21 +0100 (Mon, 16 Jul 2007) | 2 lines added notice entries ........ r556680 | cctrieloff | 2007-07-16 18:56:40 +0100 (Mon, 16 Jul 2007) | 2 lines clean up ........ r556682 | cctrieloff | 2007-07-16 18:58:37 +0100 (Mon, 16 Jul 2007) | 2 lines removed optional cppunit as not in distributed packages ........ r556845 | ritchiem | 2007-07-17 09:26:33 +0100 (Tue, 17 Jul 2007) | 3 lines Additional logging in case of broker failure at startup. Use broker logger at error level as well as System.out ........ r556847 | ritchiem | 2007-07-17 09:35:35 +0100 (Tue, 17 Jul 2007) | 3 lines Update to the MessageStore Tool to provide Move and Purge functionality. Updated to remove the AMQExceptions that will be removed from the Exchange class. ........ r556861 | ritchiem | 2007-07-17 10:26:47 +0100 (Tue, 17 Jul 2007) | 2 lines QPID-538 Check to ensure a duplicate binding is not created. ........ r556868 | ritchiem | 2007-07-17 10:55:56 +0100 (Tue, 17 Jul 2007) | 1 line Addition of simple pub/sub examples. ........ r556869 | ritchiem | 2007-07-17 10:56:17 +0100 (Tue, 17 Jul 2007) | 1 line QPID-540 Prevent NPE when purging message from the main _message queue in the ConcurrentSelectorDeliveryManager that have been delivered via a Subscribers _messageQueue. Ensuring that any expired messages are still correctly handled. i.e. the Queue size/depth is reduced and the message correctly dequeued from the underlying store. ........ r556871 | ritchiem | 2007-07-17 10:57:35 +0100 (Tue, 17 Jul 2007) | 1 line White space & code formatting change ........ r556872 | ritchiem | 2007-07-17 10:58:35 +0100 (Tue, 17 Jul 2007) | 3 lines Added additional information to hard-error logging in exceptionReceived. Fully expanded imports ........ r556888 | ritchiem | 2007-07-17 12:33:08 +0100 (Tue, 17 Jul 2007) | 1 line Change to allow the management port to be specified on the command line, via -m or --mport ........ r556890 | ritchiem | 2007-07-17 12:38:10 +0100 (Tue, 17 Jul 2007) | 4 lines QPID-541 A large portion of memory was being wasted in 32k ByteBuffers being held by the AMQShortStrings. Patch submitted by Robert Godfrey to intern() the AMQSSs to reduce memory usage. Current implementation *will* impact performance due to the usage of a static Map for storage. However, a thread local implementation is in the works. ........ r556898 | rgodfrey | 2007-07-17 13:00:57 +0100 (Tue, 17 Jul 2007) | 1 line QPID-541 : Change to use threadlocal maps for intern for the common case to avoid excessive synchronization. In the uncommon case will require more lookup. ........ r556958 | rupertlssmith | 2007-07-17 17:22:16 +0100 (Tue, 17 Jul 2007) | 1 line Refactored the distributed test clients and coordinator to support different distribution and sequencing engines. ........ r556967 | rupertlssmith | 2007-07-17 17:40:14 +0100 (Tue, 17 Jul 2007) | 1 line Removed unused package. ........ r556968 | rupertlssmith | 2007-07-17 17:42:00 +0100 (Tue, 17 Jul 2007) | 1 line Retired old interop tests. ........ r556969 | rupertlssmith | 2007-07-17 17:43:49 +0100 (Tue, 17 Jul 2007) | 1 line Properties file not needed any more. Test properties all driven from MessagingTestConfigProperties. ........ r557276 | ritchiem | 2007-07-18 15:36:11 +0100 (Wed, 18 Jul 2007) | 1 line Updates to pom files and Licensing/Notice files for M2 release. ........ r557279 | ritchiem | 2007-07-18 15:51:42 +0100 (Wed, 18 Jul 2007) | 1 line This is left over from ANT ........ r557281 | ritchiem | 2007-07-18 15:54:06 +0100 (Wed, 18 Jul 2007) | 1 line updated comment to refelect property values ........ r557286 | ritchiem | 2007-07-18 16:02:22 +0100 (Wed, 18 Jul 2007) | 1 line Set default mvn build to assembly:assembly ........ r557288 | ritchiem | 2007-07-18 16:09:07 +0100 (Wed, 18 Jul 2007) | 1 line Ensure the top level release-docs directory is included in the builds ........ r557306 | ritchiem | 2007-07-18 17:01:58 +0100 (Wed, 18 Jul 2007) | 1 line Update fix incorrect license headers. ........ r557312 | ritchiem | 2007-07-18 17:07:01 +0100 (Wed, 18 Jul 2007) | 1 line added license ........ r557314 | ritchiem | 2007-07-18 17:11:17 +0100 (Wed, 18 Jul 2007) | 1 line added license ........ r557452 | aconway | 2007-07-19 03:03:02 +0100 (Thu, 19 Jul 2007) | 14 lines * lib/broker/Daemon.cpp, .h - Rewrote to remove libdaemon dependency. - PID file stored in /var/run if root, /tmp otherwise. * src/qpidd.cpp: Use new Daemon.cpp. - lock files stored in /var/run (for root) or /tmp. - updated to trunk daemon flag behavior. * lib/broker/Makefile.am (libqpidbroker_la_LIBADD): - Daemon.cpp now needs -lboost_iostreams * NOTICE, README: Removed mention of libdaemon. ........ r558027 | ritchiem | 2007-07-20 17:08:05 +0100 (Fri, 20 Jul 2007) | 1 line Added a logger but only used to control the toString inclusion of password. If in debug mode it will include password otherwise the password is "********". ........ r558072 | astitcher | 2007-07-20 18:49:41 +0100 (Fri, 20 Jul 2007) | 2 lines Fixed the license from the "old" apache copyright notice ........ r558083 | aconway | 2007-07-20 19:29:08 +0100 (Fri, 20 Jul 2007) | 2 lines Remove -ldaemon, we no longer require libdaemon. ........ r558099 | aconway | 2007-07-20 20:20:01 +0100 (Fri, 20 Jul 2007) | 2 lines Ignore QPID_ env variables that don't correspond to known options. ........ r558108 | cctrieloff | 2007-07-20 20:55:40 +0100 (Fri, 20 Jul 2007) | 2 lines typo fix ........ r558114 | rajith | 2007-07-20 21:11:03 +0100 (Fri, 20 Jul 2007) | 1 line added release notes ........ r558115 | rajith | 2007-07-20 21:12:20 +0100 (Fri, 20 Jul 2007) | 1 line Checking in the release notes ........ r558116 | aconway | 2007-07-20 21:16:20 +0100 (Fri, 20 Jul 2007) | 3 lines Removed .txt from RELEASE_NOTES Added RELEASE_NOTES to EXTRA_DIST in Makefile.am ........ r558168 | rajith | 2007-07-20 23:03:42 +0100 (Fri, 20 Jul 2007) | 1 line added release notes ........ r558170 | rajith | 2007-07-20 23:04:11 +0100 (Fri, 20 Jul 2007) | 1 line added release notes ........ r558630 | gsim | 2007-07-23 08:21:49 +0100 (Mon, 23 Jul 2007) | 3 lines Revised release notes: removed bug fixed on this branch, removed outstanding feature lists as it is not terribly accurate or helpful. ........ r559419 | rupertlssmith | 2007-07-25 13:17:59 +0100 (Wed, 25 Jul 2007) | 1 line Refactored interop tests into general distributed test framework. Moved framework under systests from integrationtests. ........ r559427 | ritchiem | 2007-07-25 13:40:24 +0100 (Wed, 25 Jul 2007) | 2 lines AMQMessage - added //todo-s and removed unused parameter StoreContext from expired() method call. ConcurrentSelectorDeliveryManager - Update to reflect expired() call change. Created new _reaperContextStore to be used when performing reaper operations such as message dequeue due to expiration. Removed old commented code. ........ r559455 | rupertlssmith | 2007-07-25 14:40:16 +0100 (Wed, 25 Jul 2007) | 1 line Added to comments. ........ r559456 | rupertlssmith | 2007-07-25 14:41:21 +0100 (Wed, 25 Jul 2007) | 1 line Removed redundant method. ........ r559458 | rupertlssmith | 2007-07-25 14:57:21 +0100 (Wed, 25 Jul 2007) | 1 line Refactored packaging of test framework. ........ r559461 | rupertlssmith | 2007-07-25 15:00:16 +0100 (Wed, 25 Jul 2007) | 1 line Removed redundant packages. ........ r559943 | rhs | 2007-07-26 20:15:17 +0100 (Thu, 26 Jul 2007) | 1 line adding missing ack ........ r559944 | rhs | 2007-07-26 20:15:44 +0100 (Thu, 26 Jul 2007) | 1 line removed old script ........ r560198 | ritchiem | 2007-07-27 12:30:34 +0100 (Fri, 27 Jul 2007) | 1 line Added files to ignore list ........ r560225 | ritchiem | 2007-07-27 14:33:50 +0100 (Fri, 27 Jul 2007) | 1 line Converted namespaces from Qpid.* to Apache.Qpid.* ........ r560471 | tomasr | 2007-07-28 03:35:41 +0100 (Sat, 28 Jul 2007) | 1 line Removed using directives causing compilation failure in .NET 1.1 ........ r561278 | ritchiem | 2007-07-31 10:07:57 +0100 (Tue, 31 Jul 2007) | 8 lines Changes to POMs. Client pom now builds a single jar with all dependancies included in the single bundle. systests/pom.xml adjusted to include only *Test.class items. This will fix the current Error on OptOutTestCase management/eclipse-plugin/pom.xml - editied to include there required MANIFEST.MF to identify plugin to eclipse distribution/src/main/assembly/management-eclipse-plugin.xml editied to include there required MANIFEST.MF to identify the plugin distribution/pom.xml - white space Also updated log4j.xml default to create an alert.log file from the AMQQueue alerting. Added a debug.log4j.xml that gives example of debugging the broker via log4j. ........ git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@561365 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/framing/AMQShortString.java | 56 ++++++++++++++++++++++ .../abstraction/MessagePublishInfoConverter.java | 25 +++++----- .../ProtocolVersionMethodConverter.java | 25 +++++----- .../org/apache/qpid/util/CommandLineParser.java | 14 +++--- 4 files changed, 92 insertions(+), 28 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java index 05e9473463..df99f6589d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java @@ -26,6 +26,10 @@ import org.apache.mina.common.ByteBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Map; +import java.util.WeakHashMap; +import java.lang.ref.WeakReference; + /** * A short string is a representation of an AMQ Short String * Short strings differ from the Java String class by being limited to on ASCII characters (0-127) @@ -34,6 +38,19 @@ import org.slf4j.LoggerFactory; */ public final class AMQShortString implements CharSequence, Comparable { + + private static final ThreadLocal>> _localInternMap = + new ThreadLocal>>() + { + protected Map> initialValue() + { + return new WeakHashMap>(); + }; + }; + + private static final Map> _globalInternMap = + new WeakHashMap>(); + private static final Logger _logger = LoggerFactory.getLogger(AMQShortString.class); private final ByteBuffer _data; @@ -376,4 +393,43 @@ public final class AMQShortString implements CharSequence, Comparable> localMap = + _localInternMap.get(); + + WeakReference ref = localMap.get(this); + AMQShortString internString; + + if(ref != null) + { + internString = ref.get(); + if(internString != null) + { + return internString; + } + } + + + synchronized(_globalInternMap) + { + + ref = _globalInternMap.get(this); + if((ref == null) || ((internString = ref.get()) == null)) + { + internString = new AMQShortString(getBytes()); + ref = new WeakReference(internString); + _globalInternMap.put(internString, ref); + } + + } + localMap.put(internString, ref); + return internString; + + } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java index c9e15f18e3..42e2f7ad97 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java @@ -1,18 +1,21 @@ /* * - * Copyright (c) 2006 The Apache Software Foundation + * 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 * - * Licensed 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 * - * 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. + * 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. * */ diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java index 52e82cdf07..99588a0908 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java @@ -1,18 +1,21 @@ /* * - * Copyright (c) 2006 The Apache Software Foundation + * 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 * - * Licensed 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 * - * 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. + * 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. * */ diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java b/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java index 9bb4a6635f..64e61fe5ff 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java @@ -483,9 +483,9 @@ public class CommandLineParser } /** - * If a command line has been parsed, calling this method sets all of its parsed options as system properties. + * If a command line has been parsed, calling this method sets all of its parsed options into the specified properties. */ - public void addCommandLineToSysProperties() + public void addCommandLineToProperties(Properties properties) { if (parsedProperties != null) { @@ -494,7 +494,7 @@ public class CommandLineParser String name = (String) propKey; String value = parsedProperties.getProperty(name); - System.setProperty(name, value); + properties.setProperty(name, value); } } } @@ -607,7 +607,9 @@ public class CommandLineParser * instrucitons and calling System.exit on errors. Extracts all trailing name=value pairs from the command line, * and sets them all as system properties and also returns a map of properties containing them. * - * @param args The command line. + * @param args The command line. + * @param commandLine The command line parser. + * @param properties The properties object to inject all parsed properties into (optional may be null). * * @return A set of properties containing all name=value pairs from the command line. * @@ -619,7 +621,7 @@ public class CommandLineParser * @todo Allow the Properties to add trailing options to be specified as an argument rather than hard coding * system properties. Again, gives the caller the option to decide. */ - public static Properties processCommandLine(String[] args, CommandLineParser commandLine) + public static Properties processCommandLine(String[] args, CommandLineParser commandLine, Properties properties) { // Capture the command line arguments or display errors and correct usage and then exit. Properties options = null; @@ -630,7 +632,7 @@ public class CommandLineParser // Add all the trailing command line options (name=value pairs) to system properties. They may be picked up // from there. - commandLine.addCommandLineToSysProperties(); + commandLine.addCommandLineToProperties(properties); } catch (IllegalArgumentException e) { -- cgit v1.2.1 From c06860ce45b4f52be1ba934fd4d92da10c9cc25f Mon Sep 17 00:00:00 2001 From: "Rafael H. Schloming" Date: Tue, 31 Jul 2007 22:34:12 +0000 Subject: Rolled back revision 561365 and commented out some broken code in ClientSession.java. The trunk should now build. git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@561578 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpid/framing/AMQShortString.java | 56 ---------------------- .../abstraction/MessagePublishInfoConverter.java | 25 +++++----- .../ProtocolVersionMethodConverter.java | 25 +++++----- .../org/apache/qpid/util/CommandLineParser.java | 14 +++--- 4 files changed, 28 insertions(+), 92 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java index df99f6589d..05e9473463 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java @@ -26,10 +26,6 @@ import org.apache.mina.common.ByteBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Map; -import java.util.WeakHashMap; -import java.lang.ref.WeakReference; - /** * A short string is a representation of an AMQ Short String * Short strings differ from the Java String class by being limited to on ASCII characters (0-127) @@ -38,19 +34,6 @@ import java.lang.ref.WeakReference; */ public final class AMQShortString implements CharSequence, Comparable { - - private static final ThreadLocal>> _localInternMap = - new ThreadLocal>>() - { - protected Map> initialValue() - { - return new WeakHashMap>(); - }; - }; - - private static final Map> _globalInternMap = - new WeakHashMap>(); - private static final Logger _logger = LoggerFactory.getLogger(AMQShortString.class); private final ByteBuffer _data; @@ -393,43 +376,4 @@ public final class AMQShortString implements CharSequence, Comparable> localMap = - _localInternMap.get(); - - WeakReference ref = localMap.get(this); - AMQShortString internString; - - if(ref != null) - { - internString = ref.get(); - if(internString != null) - { - return internString; - } - } - - - synchronized(_globalInternMap) - { - - ref = _globalInternMap.get(this); - if((ref == null) || ((internString = ref.get()) == null)) - { - internString = new AMQShortString(getBytes()); - ref = new WeakReference(internString); - _globalInternMap.put(internString, ref); - } - - } - localMap.put(internString, ref); - return internString; - - } } diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java index 42e2f7ad97..c9e15f18e3 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/MessagePublishInfoConverter.java @@ -1,21 +1,18 @@ /* * - * 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 + * Copyright (c) 2006 The Apache Software Foundation * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed 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 * - * 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. + * 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. * */ diff --git a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java index 99588a0908..52e82cdf07 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/framing/abstraction/ProtocolVersionMethodConverter.java @@ -1,21 +1,18 @@ /* * - * 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 + * Copyright (c) 2006 The Apache Software Foundation * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed 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 * - * 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. + * 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. * */ diff --git a/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java b/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java index 64e61fe5ff..9bb4a6635f 100644 --- a/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java +++ b/qpid/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java @@ -483,9 +483,9 @@ public class CommandLineParser } /** - * If a command line has been parsed, calling this method sets all of its parsed options into the specified properties. + * If a command line has been parsed, calling this method sets all of its parsed options as system properties. */ - public void addCommandLineToProperties(Properties properties) + public void addCommandLineToSysProperties() { if (parsedProperties != null) { @@ -494,7 +494,7 @@ public class CommandLineParser String name = (String) propKey; String value = parsedProperties.getProperty(name); - properties.setProperty(name, value); + System.setProperty(name, value); } } } @@ -607,9 +607,7 @@ public class CommandLineParser * instrucitons and calling System.exit on errors. Extracts all trailing name=value pairs from the command line, * and sets them all as system properties and also returns a map of properties containing them. * - * @param args The command line. - * @param commandLine The command line parser. - * @param properties The properties object to inject all parsed properties into (optional may be null). + * @param args The command line. * * @return A set of properties containing all name=value pairs from the command line. * @@ -621,7 +619,7 @@ public class CommandLineParser * @todo Allow the Properties to add trailing options to be specified as an argument rather than hard coding * system properties. Again, gives the caller the option to decide. */ - public static Properties processCommandLine(String[] args, CommandLineParser commandLine, Properties properties) + public static Properties processCommandLine(String[] args, CommandLineParser commandLine) { // Capture the command line arguments or display errors and correct usage and then exit. Properties options = null; @@ -632,7 +630,7 @@ public class CommandLineParser // Add all the trailing command line options (name=value pairs) to system properties. They may be picked up // from there. - commandLine.addCommandLineToProperties(properties); + commandLine.addCommandLineToSysProperties(); } catch (IllegalArgumentException e) { -- cgit v1.2.1 From d92fc4e4d70b467a6167d981392430573b93fc59 Mon Sep 17 00:00:00 2001 From: "Rafael H. Schloming" Date: Wed, 1 Aug 2007 05:28:01 +0000 Subject: plumbed the input/output into MINA and filled out more of the encoding/decoding git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@561665 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpidity/AbstractDecoder.java | 149 +++++++++++++ .../java/org/apache/qpidity/AbstractEncoder.java | 163 +++++++++++++++ .../java/org/apache/qpidity/AbstractMethod.java | 18 +- .../main/java/org/apache/qpidity/BBDecoder.java | 85 +------- .../main/java/org/apache/qpidity/BBEncoder.java | 73 +------ .../src/main/java/org/apache/qpidity/Channel.java | 54 +++-- .../org/apache/qpidity/CommonSessionDelegate.java | 64 ++++-- .../main/java/org/apache/qpidity/Connection.java | 69 ++++++- .../java/org/apache/qpidity/ConsoleOutput.java | 42 ++++ .../java/org/apache/qpidity/ContentHandler.java | 7 +- .../src/main/java/org/apache/qpidity/Encoder.java | 2 + .../java/org/apache/qpidity/FragmentDecoder.java | 91 ++++++++ .../src/main/java/org/apache/qpidity/Frame.java | 138 ++++++++----- .../main/java/org/apache/qpidity/Functions.java | 80 +++++++ .../main/java/org/apache/qpidity/InputHandler.java | 230 +++++++++++++++++++++ .../src/main/java/org/apache/qpidity/Method.java | 4 + .../java/org/apache/qpidity/MethodDispatcher.java | 25 ++- .../java/org/apache/qpidity/MethodHandler.java | 7 +- .../main/java/org/apache/qpidity/MinaHandler.java | 123 +++++++++++ .../java/org/apache/qpidity/ProtocolActions.java | 39 ++++ .../java/org/apache/qpidity/ProtocolError.java | 47 +++++ .../java/org/apache/qpidity/ProtocolHandler.java | 39 ++++ .../java/org/apache/qpidity/ProtocolHeader.java | 64 ++++++ .../src/main/java/org/apache/qpidity/Segment.java | 54 +++-- .../java/org/apache/qpidity/SegmentAssembler.java | 6 +- .../java/org/apache/qpidity/SegmentEncoder.java | 173 ++++++++++++++++ .../src/main/java/org/apache/qpidity/Session.java | 8 +- .../org/apache/qpidity/SimpleDelegateResolver.java | 45 ++++ .../main/java/org/apache/qpidity/SizeEncoder.java | 60 +----- .../java/org/apache/qpidity/SliceIterator.java | 59 ++++++ .../src/main/java/org/apache/qpidity/Stub.java | 50 +++-- .../src/main/java/org/apache/qpidity/Switch.java | 6 + .../main/java/org/apache/qpidity/TrackSwitch.java | 4 +- .../main/java/org/apache/qpidity/TypeSwitch.java | 4 +- 34 files changed, 1714 insertions(+), 368 deletions(-) create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/AbstractDecoder.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/AbstractEncoder.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/ConsoleOutput.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/FragmentDecoder.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/Functions.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/InputHandler.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/MinaHandler.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/ProtocolActions.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/ProtocolError.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/ProtocolHandler.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/ProtocolHeader.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/SegmentEncoder.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/SimpleDelegateResolver.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/SliceIterator.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/AbstractDecoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractDecoder.java new file mode 100644 index 0000000000..42da09f2d9 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractDecoder.java @@ -0,0 +1,149 @@ +/* + * + * 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.qpidity; + +import java.util.Map; +import java.util.UUID; + +import static org.apache.qpidity.Functions.*; + + +/** + * AbstractDecoder + * + * @author Rafael H. Schloming + */ + +abstract class AbstractDecoder implements Decoder +{ + + protected abstract byte get(); + + protected abstract void get(byte[] bytes); + + private byte bits = 0x0; + private byte nbits = 0; + + public boolean readBit() + { + if (nbits == 0) + { + bits = get(); + nbits = 8; + } + + nbits -= 1; + + boolean result = ((bits >>> nbits) & 0x01) != 0; + return result; + } + + private void clearBits() + { + bits = 0x0; + nbits = 0; + } + + public short readOctet() + { + clearBits(); + return unsigned(get()); + } + + public int readShort() + { + clearBits(); + int i = get() << 8; + i |= get(); + return i; + } + + public long readLong() + { + clearBits(); + long l = get() << 24; + l |= get() << 16; + l |= get() << 8; + l |= get(); + return l; + } + + public long readLonglong() + { + clearBits(); + long l = get() << 56; + l |= get() << 48; + l |= get() << 40; + l |= get() << 32; + l |= get() << 24; + l |= get() << 16; + l |= get() << 8; + l |= get(); + return l; + } + + public long readTimestamp() + { + return readLonglong(); + } + + + public String readShortstr() + { + short size = readOctet(); + byte[] bytes = new byte[size]; + get(bytes); + return new String(bytes); + } + + public String readLongstr() + { + long size = readLong(); + assert size <= Integer.MAX_VALUE; + byte[] bytes = new byte[(int) size]; + get(bytes); + return new String(bytes); + } + + public Map readTable() + { + //throw new Error("TODO"); + return null; + } + + public Range[] readRfc1982LongSet() + { + throw new Error("TODO"); + } + + public UUID readUuid() + { + long msb = readLong(); + long lsb = readLong(); + return new UUID(msb, lsb); + } + + public String readContent() + { + throw new Error("Deprecated"); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/AbstractEncoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractEncoder.java new file mode 100644 index 0000000000..5ca68fe564 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractEncoder.java @@ -0,0 +1,163 @@ +/* + * + * 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.qpidity; + +import java.nio.ByteBuffer; + +import java.util.Map; +import java.util.UUID; + +import static org.apache.qpidity.Functions.*; + + +/** + * AbstractEncoder + * + * @author Rafael H. Schloming + */ + +abstract class AbstractEncoder implements Encoder +{ + + protected abstract void put(byte b); + + protected abstract void put(ByteBuffer src); + + private byte bits = 0x0; + private byte nbits = 0; + + public void writeBit(boolean b) + { + if (b) + { + bits |= 1 << nbits; + } + + nbits += 1; + + if (nbits == 8) + { + flushBits(); + } + } + + private void flushBits() + { + if (nbits > 0) + { + put(bits); + bits = 0x0; + nbits = 0; + } + } + + public void writeOctet(short b) + { + assert b < 0x100; + + flushBits(); + put((byte) b); + } + + public void writeShort(int s) + { + assert s < 0x10000; + + flushBits(); + put(lsb(s >> 8)); + put(lsb(s)); + } + + public void writeLong(long i) + { + assert i < 0x100000000L; + + flushBits(); + put(lsb(i >> 24)); + put(lsb(i >> 16)); + put(lsb(i >> 8)); + put(lsb(i)); + } + + public void writeLonglong(long l) + { + flushBits(); + put(lsb(l >> 56)); + put(lsb(l >> 48)); + put(lsb(l >> 40)); + put(lsb(l >> 32)); + put(lsb(l >> 24)); + put(lsb(l >> 16)); + put(lsb(l >> 8)); + put(lsb(l)); + } + + + public void writeTimestamp(long l) + { + flushBits(); + writeLonglong(l); + } + + + public void writeShortstr(String s) + { + if (s.length() > 255) { + throw new IllegalArgumentException(s); + } + writeOctet((short) s.length()); + put(ByteBuffer.wrap(s.getBytes())); + } + + public void writeLongstr(String s) + { + writeLong(s.length()); + put(ByteBuffer.wrap(s.getBytes())); + } + + + public void writeTable(Map table) + { + //throw new Error("TODO"); + } + + public void writeRfc1982LongSet(Range[] ranges) + { + throw new Error("TODO"); + } + + public void writeUuid(UUID uuid) + { + writeLong(uuid.getMostSignificantBits()); + writeLong(uuid.getLeastSignificantBits()); + } + + public void writeContent(String c) + { + throw new Error("Deprecated"); + } + + public void flush() + { + flushBits(); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/AbstractMethod.java b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractMethod.java index 7db1aeea43..258c33d715 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/AbstractMethod.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractMethod.java @@ -20,7 +20,6 @@ */ package org.apache.qpidity; -import java.nio.ByteBuffer; /** * AbstractMethod @@ -28,4 +27,19 @@ import java.nio.ByteBuffer; * @author Rafael H. Schloming */ -abstract class AbstractMethod extends AbstractStruct implements Method {} +abstract class AbstractMethod extends AbstractStruct implements Method { + + public byte getEncodedTrack() + { + // XXX + return Frame.L2; + } + + // XXX: do we need a segment base type? + public byte getSegmentType() + { + // XXX + return Frame.METHOD; + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java index 9c5da34cd1..08ac03113f 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java @@ -22,8 +22,6 @@ package org.apache.qpidity; import java.nio.ByteBuffer; -import java.util.Map; -import java.util.UUID; /** * BBDecoder @@ -31,24 +29,9 @@ import java.util.UUID; * @author Rafael H. Schloming */ -class BBDecoder implements Decoder +class BBDecoder extends AbstractDecoder { - private static final short unsigned(byte b) - { - return (short) ((0x100 + b) & 0xFF); - } - - private static final int unsigned(short s) - { - return (0x10000 + s) & 0xFFFF; - } - - private static final long unsigned(int i) - { - return (0x1000000000L + i) & 0xFFFFFFFFL; - } - private final ByteBuffer in; public BBDecoder(ByteBuffer in) @@ -56,74 +39,14 @@ class BBDecoder implements Decoder this.in = in; } - public boolean readBit() - { - //throw new Error("TODO"); - return false; - } - - public short readOctet() - { - return unsigned(in.get()); - } - - public int readShort() - { - return unsigned(in.getShort()); - } - - public long readLong() - { - return unsigned(in.getInt()); - } - - public long readLonglong() + protected byte get() { - throw new Error("TODO"); + return in.get(); } - public long readTimestamp() + protected void get(byte[] bytes) { - throw new Error("TODO"); - } - - - public String readShortstr() - { - short size = readOctet(); - byte[] bytes = new byte[size]; - in.get(bytes); - return new String(bytes); - } - - public String readLongstr() - { - long size = readLong(); - assert size <= Integer.MAX_VALUE; - byte[] bytes = new byte[(int) size]; in.get(bytes); - return new String(bytes); - } - - public Map readTable() - { - //throw new Error("TODO"); - return null; - } - - public Range[] readRfc1982LongSet() - { - throw new Error("TODO"); - } - - public UUID readUuid() - { - throw new Error("TODO"); - } - - public String readContent() - { - throw new Error("TODO"); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/BBEncoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/BBEncoder.java index 50b8659fd7..947a461ab3 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/BBEncoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/BBEncoder.java @@ -22,8 +22,6 @@ package org.apache.qpidity; import java.nio.ByteBuffer; -import java.util.Map; -import java.util.UUID; /** * BBEncoder @@ -31,7 +29,7 @@ import java.util.UUID; * @author Rafael H. Schloming */ -class BBEncoder implements Encoder +class BBEncoder extends AbstractEncoder { private final ByteBuffer out; @@ -40,75 +38,14 @@ class BBEncoder implements Encoder this.out = out; } - public void writeBit(boolean b) + @Override protected void put(byte b) { - //throw new Error("TODO"); + out.put(b); } - public void writeOctet(short b) + @Override protected void put(ByteBuffer src) { - assert b < 0x100; - out.put((byte) b); - } - - public void writeShort(int s) - { - assert s < 0x10000; - out.putShort((short) s); - } - - public void writeLong(long i) - { - assert i < 0x100000000L; - out.putInt((int) i); - } - - public void writeLonglong(long l) - { - throw new Error("TODO"); - } - - - public void writeTimestamp(long l) - { - throw new Error("TODO"); - } - - - public void writeShortstr(String s) - { - if (s.length() > 255) { - throw new IllegalArgumentException(s); - } - writeOctet((short) s.length()); - out.put(s.getBytes()); - } - - public void writeLongstr(String s) - { - writeLong(s.length()); - out.put(s.getBytes()); - } - - - public void writeTable(Map table) - { - //throw new Error("TODO"); - } - - public void writeRfc1982LongSet(Range[] ranges) - { - throw new Error("TODO"); - } - - public void writeUuid(UUID uuid) - { - throw new Error("TODO"); - } - - public void writeContent(String c) - { - throw new Error("TODO"); + out.put(src); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Channel.java b/qpid/java/common/src/main/java/org/apache/qpidity/Channel.java index a9060622e8..4f23112da3 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Channel.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Channel.java @@ -20,32 +20,43 @@ */ package org.apache.qpidity; - /** * Channel * * @author Rafael H. Schloming */ -class Channel extends Invoker - implements Handler, DelegateResolver +class Channel extends Invoker implements Handler { final private Connection connection; + final private int channel; final private TrackSwitch tracks; - // session may be null private Session session; - public Channel(Connection connection) + public Channel(Connection connection, int channel) { this.connection = connection; + this.channel = channel; + + DelegateResolver chDR = + new SimpleDelegateResolver(new ChannelDelegate()); + DelegateResolver ssnDR = + new SimpleDelegateResolver(new SessionDelegate()); + tracks = new TrackSwitch(); - tracks.map(Frame.L1, new MethodHandler()); - tracks.map(Frame.L2, new MethodHandler()); - tracks.map(Frame.L3, new SessionResolver(new MethodHandler())); - tracks.map(Frame.L4, new SessionResolver(new ContentHandler())); + tracks.map(Frame.L1, new MethodHandler(getFactory(), chDR)); + tracks.map(Frame.L2, new MethodHandler(getFactory(), chDR)); + tracks.map(Frame.L3, new SessionResolver + (new MethodHandler(getFactory(), ssnDR))); + tracks.map(Frame.L4, new SessionResolver + (new ContentHandler(getFactory(), ssnDR))); + } + + public int getEncodedChannel() { + return channel; } public Session getSession() @@ -63,9 +74,25 @@ class Channel extends Invoker tracks.handle(new Event(this, frame)); } - public void write(Writable writable) + public void write(Method m) { - System.out.println("writing: " + writable); + SizeEncoder sizer = new SizeEncoder(); + sizer.writeLong(m.getEncodedType()); + m.write(sizer); + sizer.flush(); + int size = sizer.getSize(); + + // XXX: need to set header flags properly + SegmentEncoder enc = new SegmentEncoder(connection.getOutputHandler(), + connection.getMaxFrame(), + (byte) 0x0, + m.getEncodedTrack(), + m.getSegmentType(), + channel, + size); + enc.writeLong(m.getEncodedType()); + m.write(enc); + enc.flush(); } protected StructFactory getFactory() @@ -73,11 +100,6 @@ class Channel extends Invoker return connection.getFactory(); } - public Delegate resolve(Struct struct) - { - return new ChannelDelegate(); - } - protected void invoke(Method m) { write(m); diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java b/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java index b8efa857f6..e9173a5c5b 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java @@ -1,27 +1,51 @@ +/* + * + * 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.qpidity; + +/** + * CommonSessionDelegate + */ + public class CommonSessionDelegate extends Delegate { - public void sessionAttached(Session session, SessionAttached struct) {} - - public void sessionFlow(Session session, SessionFlow struct) {} - - public void sessionFlowOk(Session session, SessionFlowOk struct) {} - - public void sessionClose(Session session, SessionClose struct) {} - - public void sessionClosed(Session session, SessionClosed struct) {} - - public void sessionResume(Session session, SessionResume struct) {} - - public void sessionPing(Session session, SessionPing struct) {} - - public void sessionPong(Session session, SessionPong struct) {} - - public void sessionSuspend(Session session, SessionSuspend struct) {} - - public void sessionDetached(Session session, SessionDetached struct) {} - + @Override public void sessionAttached(Session session, SessionAttached struct) {} + + @Override public void sessionFlow(Session session, SessionFlow struct) {} + + @Override public void sessionFlowOk(Session session, SessionFlowOk struct) {} + + @Override public void sessionClose(Session session, SessionClose struct) {} + + @Override public void sessionClosed(Session session, SessionClosed struct) {} + + @Override public void sessionResume(Session session, SessionResume struct) {} + + @Override public void sessionPing(Session session, SessionPing struct) {} + + @Override public void sessionPong(Session session, SessionPong struct) {} + + @Override public void sessionSuspend(Session session, SessionSuspend struct) {} + + @Override public void sessionDetached(Session session, SessionDetached struct) {} } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Connection.java b/qpid/java/common/src/main/java/org/apache/qpidity/Connection.java index bb8b945051..7e31ca9b57 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Connection.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Connection.java @@ -23,6 +23,9 @@ package org.apache.qpidity; import java.util.HashMap; import java.util.Map; +import java.nio.ByteBuffer; + + /** * Connection * @@ -33,27 +36,79 @@ import java.util.Map; * short instead of Short */ -class Connection implements Handler +class Connection implements ProtocolActions { - final private Map channels = new HashMap(); - final private StructFactory factory = new StructFactory_v0_10(); + final private Handler input; + final private Handler output; + + final private Map channels = new HashMap(); + private StructFactory factory; + + // XXX + private int maxFrame = 64*1024; + + public Connection(Handler output) + { + this.input = new InputHandler(this); + this.output = output; + } + + public Handler getInputHandler() + { + return input; + } + + public Handler getOutputHandler() + { + return output; + } + + public StructFactory getFactory() + { + return factory; + } + + public int getMaxFrame() + { + return maxFrame; + } - public void handle(Frame frame) + public void init(ProtocolHeader header) + { + System.out.println(header); + // XXX: hardcoded versions + if (header.getMajor() != 0 && header.getMinor() != 10) + { + ByteBuffer buf = ByteBuffer.allocate(8); + buf.put("AMQP".getBytes()); + buf.put((byte) 1); + buf.put((byte) 1); + buf.put((byte) 0); + buf.put((byte) 10); + buf.flip(); + output.handle(buf); + // XXX: how do we close the connection? + } else { + factory = new StructFactory_v0_10(); + } + } + + public void frame(Frame frame) { Channel channel = channels.get(frame.getChannel()); if (channel == null) { - channel = new Channel(this); + channel = new Channel(this, frame.getChannel()); channels.put(frame.getChannel(), channel); } channel.handle(frame); } - public StructFactory getFactory() + public void error(ProtocolError error) { - return factory; + throw new RuntimeException(error.getMessage()); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/ConsoleOutput.java b/qpid/java/common/src/main/java/org/apache/qpidity/ConsoleOutput.java new file mode 100644 index 0000000000..fa35e9332f --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/ConsoleOutput.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.qpidity; + +import java.nio.ByteBuffer; + +import static org.apache.qpidity.Functions.*; + + +/** + * ConsoleOutput + * + * @author Rafael H. Schloming + */ + +class ConsoleOutput implements Handler +{ + + public void handle(ByteBuffer buf) + { + System.out.println(str(buf)); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/ContentHandler.java b/qpid/java/common/src/main/java/org/apache/qpidity/ContentHandler.java index ea73a3574d..241d265bc4 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/ContentHandler.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/ContentHandler.java @@ -29,12 +29,13 @@ package org.apache.qpidity; * @author Rafael H. Schloming */ -class ContentHandler> extends TypeSwitch +class ContentHandler extends TypeSwitch { - public ContentHandler() + public ContentHandler(StructFactory factory, DelegateResolver resolver) { - map(Frame.METHOD, new SegmentAssembler(new MethodDispatcher())); + MethodDispatcher md = new MethodDispatcher(factory, resolver); + map(Frame.METHOD, new SegmentAssembler(md)); map(Frame.HEADER, new SegmentAssembler(new HeaderHandler())); map(Frame.BODY, new BodyHandler()); } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java index 716df97397..954b690dc2 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java @@ -49,4 +49,6 @@ public interface Encoder void writeContent(String c); + void flush(); + } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/FragmentDecoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/FragmentDecoder.java new file mode 100644 index 0000000000..dcf1c19c38 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/FragmentDecoder.java @@ -0,0 +1,91 @@ +/* + * + * 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.qpidity; + +import java.nio.BufferUnderflowException; +import java.nio.ByteBuffer; + +import java.util.Iterator; + +import static java.lang.Math.*; + + +/** + * FragmentDecoder + * + * @author Rafael H. Schloming + */ + +class FragmentDecoder extends AbstractDecoder +{ + + private final Iterator fragments; + private ByteBuffer current; + + public FragmentDecoder(Iterator fragments) + { + this.fragments = fragments; + this.current = null; + } + + private void preRead() + { + if (current == null) + { + if (!fragments.hasNext()) + { + throw new BufferUnderflowException(); + } + + current = fragments.next(); + } + } + + private void postRead() + { + if (current.remaining() == 0) + { + current = null; + } + } + + @Override protected byte get() + { + preRead(); + byte b = current.get(); + postRead(); + return b; + } + + @Override protected void get(byte[] bytes) + { + int remaining = bytes.length; + while (remaining > 0) + { + preRead(); + int size = min(remaining, current.remaining()); + current.get(bytes, 0, size); + remaining -= size; + postRead(); + } + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Frame.java b/qpid/java/common/src/main/java/org/apache/qpidity/Frame.java index d1bebd8365..1c8bb64fcf 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Frame.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Frame.java @@ -21,7 +21,13 @@ package org.apache.qpidity; import java.nio.ByteBuffer; -import java.nio.ShortBuffer; + +import java.util.ArrayList; +import java.util.List; +import java.util.Iterator; + +import static org.apache.qpidity.Functions.*; + /** * Frame @@ -29,103 +35,127 @@ import java.nio.ShortBuffer; * @author Rafael H. Schloming */ -class Frame +class Frame implements Iterable { + public static final int HEADER_SIZE = 12; + + // XXX: enums? + public static final byte L1 = 0; + public static final byte L2 = 1; + public static final byte L3 = 2; + public static final byte L4 = 3; + + public static final byte METHOD = 1; + public static final byte HEADER = 2; + public static final byte BODY = 3; + + public static final byte RESERVED = 0x0; + + public static final byte FIRST_SEG = 0x8; + public static final byte LAST_SEG = 0x4; + public static final byte FIRST_FRAME = 0x2; + public static final byte LAST_FRAME = 0x1; - public static final short L1 = 0; - public static final short L2 = 1; - public static final short L3 = 2; - public static final short L4 = 3; - - public static final short METHOD = 1; - public static final short HEADER = 2; - public static final short BODY = 3; - - final private short channel; - final private short track; - final private short type; - final private boolean firstSegment; - final private boolean lastSegment; - final private boolean firstFrame; - final private boolean lastFrame; - final private ByteBuffer payload; - - // XXX - final private int sequence = 0; - - public Frame(short channel, short track, short type, boolean firstSegment, - boolean lastSegment, boolean firstFrame, boolean lastFrame, - ByteBuffer payload) + final private byte flags; + final private byte type; + final private byte track; + final private int channel; + final private List fragments; + private int size; + + public Frame(byte flags, byte type, byte track, int channel) { - this.channel = channel; - this.track = track; + this.flags = flags; this.type = type; - this.firstSegment = firstSegment; - this.lastSegment = lastSegment; - this.firstFrame = firstFrame; - this.lastFrame = lastFrame; - this.payload = payload; + this.track = track; + this.channel = channel; + this.size = 0; + this.fragments = new ArrayList(); } - public short getChannel() + public void addFragment(ByteBuffer fragment) + { + fragments.add(fragment); + size += fragment.remaining(); + } + + public int getChannel() { return channel; } - public short getTrack() + public int getSize() { - return track; + return size; } - public short getType() + public byte getType() { return type; } + public byte getTrack() + { + return track; + } + + private boolean flag(byte mask) + { + return (flags & mask) != 0; + } + public boolean isFirstSegment() { - return firstSegment; + return flag(FIRST_SEG); } public boolean isLastSegment() { - return lastSegment; + return flag(LAST_SEG); } public boolean isFirstFrame() { - return firstFrame; + return flag(FIRST_FRAME); } public boolean isLastFrame() { - return lastFrame; + return flag(LAST_FRAME); } - public ByteBuffer getPayload() + public Iterator getFragments() { - return payload.slice(); + return new SliceIterator(fragments.iterator()); } - public int getSize() + public Iterator iterator() { - return payload.remaining(); + return getFragments(); } public String toString() { StringBuilder str = new StringBuilder(); str.append(String.format - ("[%05d %05d %1d %1d %d%d%d%d]", channel, getSize(), track, type, - firstSegment ? 1 : 0, lastSegment ? 1 : 0, - firstFrame ? 1 : 0, lastFrame ? 1 : 0)); - ShortBuffer shorts = payload.asShortBuffer(); - for (int i = 0; i < shorts.limit(); i++) { - str.append(String.format(" %04x", shorts.get(i))); - if (str.length() > 70) { - str.append(" ..."); - break; + ("[%05d %05d %1d %1d %d%d%d%d]", getChannel(), getSize(), + getTrack(), getType(), + isFirstSegment() ? 1 : 0, isLastSegment() ? 1 : 0, + isFirstFrame() ? 1 : 0, isLastFrame() ? 1 : 0)); + + boolean first = true; + for (ByteBuffer buf : this) + { + if (first) + { + first = false; + } + else + { + str.append(" | "); } + + str.append(str(buf)); } return str.toString(); diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Functions.java b/qpid/java/common/src/main/java/org/apache/qpidity/Functions.java new file mode 100644 index 0000000000..f5217bf038 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Functions.java @@ -0,0 +1,80 @@ +/* + * + * 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.qpidity; + +import java.nio.ByteBuffer; + + +/** + * Functions + * + * @author Rafael H. Schloming + */ + +class Functions +{ + + public static final short unsigned(byte b) + { + return (short) ((0x100 + b) & 0xFF); + } + + public static final int unsigned(short s) + { + return (0x10000 + s) & 0xFFFF; + } + + public static final long unsigned(int i) + { + return (0x1000000000L + i) & 0xFFFFFFFFL; + } + + public static final byte lsb(int i) + { + return (byte) (0xFF & i); + } + + public static final byte lsb(long l) + { + return (byte) (0xFF & l); + } + + public static final String str(ByteBuffer buf) + { + return str(buf, buf.limit()); + } + + public static final String str(ByteBuffer buf, int limit) + { + StringBuilder str = new StringBuilder(); + for (int i = 0; i < limit; i++) + { + if (i > 0 && i % 2 == 0) + { + str.append(" "); + } + str.append(String.format("%02x", buf.get(i))); + } + + return str.toString(); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/InputHandler.java b/qpid/java/common/src/main/java/org/apache/qpidity/InputHandler.java new file mode 100644 index 0000000000..5cd4fe87c1 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/InputHandler.java @@ -0,0 +1,230 @@ +/* + * + * 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.qpidity; + +import java.nio.ByteBuffer; + +import static org.apache.qpidity.InputHandler.State.*; + + +/** + * InputHandler + * + * @author Rafael H. Schloming + */ + +class InputHandler implements Handler +{ + + enum State + { + PROTO_HDR, + PROTO_HDR_M, + PROTO_HDR_Q, + PROTO_HDR_P, + PROTO_HDR_CLASS, + PROTO_HDR_INSTANCE, + PROTO_HDR_MAJOR, + PROTO_HDR_MINOR, + FRAME_HDR, + FRAME_HDR_TYPE, + FRAME_HDR_SIZE1, + FRAME_HDR_SIZE2, + FRAME_HDR_RSVD1, + FRAME_HDR_TRACK, + FRAME_HDR_CH1, + FRAME_HDR_CH2, + FRAME_HDR_RSVD2, + FRAME_HDR_RSVD3, + FRAME_HDR_RSVD4, + FRAME_HDR_RSVD5, + FRAME_PAYLOAD, + FRAME_FRAGMENT, + ERROR; + } + + private final ProtocolActions actions; + private State state; + + private byte instance; + private byte major; + private byte minor; + + private byte flags; + private byte type; + private byte track; + private int channel; + private int size; + private Frame frame; + + public InputHandler(ProtocolActions actions, State state) + { + this.actions = actions; + this.state = state; + } + + public InputHandler(ProtocolActions actions) + { + this(actions, PROTO_HDR); + } + + private void init() + { + actions.init(new ProtocolHeader(instance, major, minor)); + } + + private void frame() + { + assert size == frame.getSize(); + actions.frame(frame); + frame = null; + } + + private void error(String fmt, Object ... args) + { + actions.error(new ProtocolError(fmt, args)); + } + + public void handle(ByteBuffer buf) + { + while (buf.hasRemaining()) + { + state = next(buf); + } + } + + private State next(ByteBuffer buf) + { + switch (state) { + case PROTO_HDR: + return expect(buf, 'A', PROTO_HDR_M); + case PROTO_HDR_M: + return expect(buf, 'M', PROTO_HDR_Q); + case PROTO_HDR_Q: + return expect(buf, 'Q', PROTO_HDR_P); + case PROTO_HDR_P: + return expect(buf, 'P', PROTO_HDR_CLASS); + case PROTO_HDR_CLASS: + return expect(buf, 1, PROTO_HDR_INSTANCE); + case PROTO_HDR_INSTANCE: + instance = buf.get(); + return PROTO_HDR_MAJOR; + case PROTO_HDR_MAJOR: + major = buf.get(); + return PROTO_HDR_MINOR; + case PROTO_HDR_MINOR: + minor = buf.get(); + init(); + return FRAME_HDR; + case FRAME_HDR: + flags = buf.get(); + return FRAME_HDR_TYPE; + case FRAME_HDR_TYPE: + type = buf.get(); + return FRAME_HDR_SIZE1; + case FRAME_HDR_SIZE1: + size = buf.get() << 8; + return FRAME_HDR_SIZE2; + case FRAME_HDR_SIZE2: + size += buf.get(); + size -= 12; + return FRAME_HDR_RSVD1; + case FRAME_HDR_RSVD1: + return expect(buf, 0, FRAME_HDR_TRACK); + case FRAME_HDR_TRACK: + byte b = buf.get(); + if ((b & 0xF0) != 0) { + error("non-zero reserved bits in upper nibble of " + + "frame header byte 5: '%x'", b); + return ERROR; + } else { + track = (byte) (b & 0xF); + return FRAME_HDR_CH1; + } + case FRAME_HDR_CH1: + channel = buf.get() << 8; + return FRAME_HDR_CH2; + case FRAME_HDR_CH2: + channel += buf.get(); + return FRAME_HDR_RSVD2; + case FRAME_HDR_RSVD2: + return expect(buf, 0, FRAME_HDR_RSVD3); + case FRAME_HDR_RSVD3: + return expect(buf, 0, FRAME_HDR_RSVD4); + case FRAME_HDR_RSVD4: + return expect(buf, 0, FRAME_HDR_RSVD5); + case FRAME_HDR_RSVD5: + return expect(buf, 0, FRAME_PAYLOAD); + case FRAME_PAYLOAD: + frame = new Frame(flags, type, track, channel); + if (size > buf.remaining()) { + frame.addFragment(buf.slice()); + buf.position(buf.limit()); + return FRAME_FRAGMENT; + } else { + ByteBuffer payload = buf.slice(); + payload.limit(size); + buf.position(buf.position() + size); + frame.addFragment(payload); + frame(); + return FRAME_HDR; + } + case FRAME_FRAGMENT: + int delta = size - frame.getSize(); + if (delta > buf.remaining()) { + frame.addFragment(buf.slice()); + buf.position(buf.limit()); + return FRAME_FRAGMENT; + } else { + ByteBuffer fragment = buf.slice(); + fragment.limit(delta); + buf.position(buf.position() + delta); + frame.addFragment(fragment); + frame(); + return FRAME_HDR; + } + default: + throw new IllegalStateException(); + } + } + + private State expect(ByteBuffer buf, int expected, State next) + { + return expect(buf, (byte) expected, next); + } + + private State expect(ByteBuffer buf, char expected, State next) + { + return expect(buf, (byte) expected, next); + } + + private State expect(ByteBuffer buf, byte expected, State next) + { + byte b = buf.get(); + if (b == expected) { + return next; + } else { + error("expecting '%x', got '%x'", expected, b); + return ERROR; + } + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Method.java b/qpid/java/common/src/main/java/org/apache/qpidity/Method.java index 75e3bdfbaa..a3926b572e 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Method.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Method.java @@ -31,4 +31,8 @@ interface Method extends Struct { int getEncodedType(); + byte getEncodedTrack(); + + byte getSegmentType(); + } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/MethodDispatcher.java b/qpid/java/common/src/main/java/org/apache/qpidity/MethodDispatcher.java index a2a4ebb0fc..8fbc6f547d 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/MethodDispatcher.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/MethodDispatcher.java @@ -22,26 +22,35 @@ package org.apache.qpidity; import java.nio.ByteBuffer; +import java.util.Iterator; + + /** * A MethodDispatcher parses and dispatches a method segment. * * @author Rafael H. Schloming */ -class MethodDispatcher> - implements Handler> +class MethodDispatcher implements Handler> { - // XXX: should be passed in - final private StructFactory factory = new StructFactory_v0_10(); + final private StructFactory factory; + final private DelegateResolver resolver; + + public MethodDispatcher(StructFactory factory, DelegateResolver resolver) + { + this.factory = factory; + this.resolver = resolver; + } public void handle(Event event) { System.out.println("got method segment:\n " + event.target); - ByteBuffer bb = event.target.getPayload(); - int type = bb.getInt(); - Struct struct = factory.create(type, new BBDecoder(bb)); - Delegate delegate = event.context.resolve(struct); + Iterator fragments = event.target.getFragments(); + Decoder dec = new FragmentDecoder(fragments); + int type = (int) dec.readLong(); + Struct struct = factory.create(type, dec); + Delegate delegate = resolver.resolve(struct); struct.delegate(event.context, delegate); } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/MethodHandler.java b/qpid/java/common/src/main/java/org/apache/qpidity/MethodHandler.java index ebc7471622..8f43f4c06f 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/MethodHandler.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/MethodHandler.java @@ -29,12 +29,13 @@ package org.apache.qpidity; * @author Rafael H. Schloming */ -class MethodHandler> extends TypeSwitch +class MethodHandler extends TypeSwitch { - public MethodHandler() + public MethodHandler(StructFactory factory, DelegateResolver resolver) { - map(Frame.METHOD, new SegmentAssembler(new MethodDispatcher())); + MethodDispatcher md = new MethodDispatcher(factory, resolver); + map(Frame.METHOD, new SegmentAssembler(md)); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/MinaHandler.java b/qpid/java/common/src/main/java/org/apache/qpidity/MinaHandler.java new file mode 100644 index 0000000000..b54f53dd80 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/MinaHandler.java @@ -0,0 +1,123 @@ +/* + * + * 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.qpidity; + +import java.io.IOException; +import java.net.InetSocketAddress; + +import org.apache.mina.common.ByteBuffer; +import org.apache.mina.common.ConnectFuture; +import org.apache.mina.common.IdleStatus; +import org.apache.mina.common.IoAcceptor; +import org.apache.mina.common.IoConnector; +import org.apache.mina.common.IoHandler; +import org.apache.mina.common.IoSession; +import org.apache.mina.common.SimpleByteBufferAllocator; + +import org.apache.mina.transport.socket.nio.SocketAcceptor; +import org.apache.mina.transport.socket.nio.SocketConnector; + + +/** + * MinaHandler + * + * @author Rafael H. Schloming + */ + +class MinaHandler implements IoHandler +{ + + public void messageReceived(IoSession ssn, Object obj) + { + Connection conn = (Connection) ssn.getAttachment(); + ByteBuffer buf = (ByteBuffer) obj; + conn.getInputHandler().handle(buf.buf()); + } + + public void messageSent(IoSession ssn, Object obj) + { + System.out.println("TX: " + obj); + } + + public void exceptionCaught(IoSession ssn, Throwable e) + { + e.printStackTrace(); + } + + public void sessionCreated(IoSession ssn) + { + System.out.println("created " + ssn); + } + + public void sessionOpened(final IoSession ssn) + { + Connection conn = new Connection(new Handler() + { + public void handle(java.nio.ByteBuffer buf) + { + ssn.write(ByteBuffer.wrap(buf)); + } + }); + ssn.setAttachment(conn); + } + + public void sessionClosed(IoSession ssn) + { + System.out.println("closed " + ssn); + ssn.setAttachment(null); + } + + public void sessionIdle(IoSession ssn, IdleStatus status) + { + System.out.println(status); + } + + public static final void main(String[] args) throws IOException + { + ByteBuffer.setAllocator(new SimpleByteBufferAllocator()); + if (args[0].equals("accept")) { + accept(args); + } else if (args[0].equals("connect")) { + connect(args); + } + } + + public static final void accept(String[] args) throws IOException + { + IoAcceptor acceptor = new SocketAcceptor(); + acceptor.bind(new InetSocketAddress("0.0.0.0", 5672), new MinaHandler()); + } + + public static final void connect(String[] args) + { + IoConnector connector = new SocketConnector(); + ConnectFuture cf = connector.connect(new InetSocketAddress("0.0.0.0", 5672), new MinaHandler()); + cf.join(); + IoSession ssn = cf.getSession(); + ByteBuffer bb = ByteBuffer.allocate(1024); + bb.put("AMQP".getBytes()); + bb.flip(); + for (int i = 0; i < 10; i++) { + ssn.write(bb); + } + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/ProtocolActions.java b/qpid/java/common/src/main/java/org/apache/qpidity/ProtocolActions.java new file mode 100644 index 0000000000..c658320989 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/ProtocolActions.java @@ -0,0 +1,39 @@ +/* + * + * 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.qpidity; + + +/** + * ProtocolActions + * + * @author Rafael H. Schloming + */ + +interface ProtocolActions +{ + + void init(ProtocolHeader header); + + void frame(Frame frame); + + void error(ProtocolError error); + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/ProtocolError.java b/qpid/java/common/src/main/java/org/apache/qpidity/ProtocolError.java new file mode 100644 index 0000000000..a4a83fad35 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/ProtocolError.java @@ -0,0 +1,47 @@ +/* + * + * 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.qpidity; + + +/** + * ProtocolError + * + * @author Rafael H. Schloming + */ + +class ProtocolError +{ + + private final String format; + private final Object[] args; + + public ProtocolError(String format, Object ... args) + { + this.format = format; + this.args = args; + } + + public String getMessage() + { + return String.format(format, args); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/ProtocolHandler.java b/qpid/java/common/src/main/java/org/apache/qpidity/ProtocolHandler.java new file mode 100644 index 0000000000..526ef50211 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/ProtocolHandler.java @@ -0,0 +1,39 @@ +/* + * + * 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.qpidity; + + +/** + * ProtocolHandler + * + * @author Rafael H. Schloming + */ + +interface ProtocolHandler +{ + + void init(ProtocolHeader header); + + void frame(Frame frame); + + void error(ProtocolError error); + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/ProtocolHeader.java b/qpid/java/common/src/main/java/org/apache/qpidity/ProtocolHeader.java new file mode 100644 index 0000000000..1f12e285e4 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/ProtocolHeader.java @@ -0,0 +1,64 @@ +/* + * + * 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.qpidity; + + +/** + * ProtocolHeader + * + * @author Rafael H. Schloming + */ + +class ProtocolHeader +{ + + final private byte instance; + final private byte major; + final private byte minor; + + public ProtocolHeader(byte instance, byte major, byte minor) + { + this.instance = instance; + this.major = major; + this.minor = minor; + } + + public byte getInstance() + { + return instance; + } + + public byte getMajor() + { + return major; + } + + public byte getMinor() + { + return minor; + } + + public String toString() + { + return String.format("AMQP.%d %d-%d", instance, major, minor); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Segment.java b/qpid/java/common/src/main/java/org/apache/qpidity/Segment.java index cd1d4ab05d..ee9f60fad8 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Segment.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Segment.java @@ -20,10 +20,14 @@ */ package org.apache.qpidity; -import java.nio.ByteBuffer; - import java.util.ArrayList; import java.util.Collection; +import java.util.Iterator; + +import java.nio.ByteBuffer; + +import static org.apache.qpidity.Functions.*; + /** * Segment @@ -31,50 +35,40 @@ import java.util.Collection; * @author Rafael H. Schloming */ -class Segment +class Segment implements Iterable { - private final Collection frames = new ArrayList(); + private final Collection fragments = new ArrayList(); - public void add(Frame frame) + public void add(ByteBuffer fragment) { - frames.add(frame); + fragments.add(fragment); } - public ByteBuffer getPayload() + public Iterator getFragments() { - // we should probably use our own decoder interface here so - // that we can directly read from the incoming frame objects - // and automatically skip frame boundaries without copying - // everything in order to get a contiguous byte buffer - int capacity = 0; - for (Frame frame : frames) - { - capacity += frame.getSize(); - } - ByteBuffer buf = ByteBuffer.allocate(capacity); - for (Frame frame : frames) - { - buf.put(frame.getPayload()); - } - buf.flip(); - return buf; + return new SliceIterator(fragments.iterator()); + } + + public Iterator iterator() + { + return getFragments(); } public String toString() { - StringBuffer buf = new StringBuffer(); - String sep = ",\n "; + StringBuilder str = new StringBuilder(); + String sep = " | "; - for (Frame f : frames) + for (ByteBuffer buf : this) { - buf.append(f.toString()); - buf.append(sep); + str.append(str(buf)); + str.append(sep); } - buf.setLength(buf.length() - sep.length()); + str.setLength(str.length() - sep.length()); - return buf.toString(); + return str.toString(); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/SegmentAssembler.java b/qpid/java/common/src/main/java/org/apache/qpidity/SegmentAssembler.java index 2d47e760c1..0fb90a2f53 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/SegmentAssembler.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/SegmentAssembler.java @@ -22,6 +22,7 @@ package org.apache.qpidity; import java.nio.ByteBuffer; + /** * SegmentAssembler is a stateful handler that aggregates Frame events * into Segment events. This should only be used where it is necessary @@ -50,7 +51,10 @@ class SegmentAssembler implements Handler> segment = new Segment(); } - segment.add(frame); + for (ByteBuffer fragment : frame) + { + segment.add(fragment); + } if (frame.isLastFrame()) { diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/SegmentEncoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/SegmentEncoder.java new file mode 100644 index 0000000000..7d4e5aabe4 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/SegmentEncoder.java @@ -0,0 +1,173 @@ +/* + * + * 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.qpidity; + +import java.nio.BufferOverflowException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import static java.lang.Math.*; + +import static org.apache.qpidity.Frame.*; + + +/** + * SegmentEncoder + * + * @author Rafael H. Schloming + */ + +class SegmentEncoder extends AbstractEncoder +{ + + private final Handler handler; + private final int max; + private final byte flags; + private final byte track; + private final byte type; + private final int channel; + + private int remaining; + private ByteBuffer frame; + private boolean first; + + public SegmentEncoder(Handler handler, int max, + byte flags, + byte track, + byte type, + int channel, + int remaining) + { + if (max < HEADER_SIZE + 1) + { + throw new IllegalArgumentException + ("max frame size must be large enough to include header"); + } + + this.handler = handler; + this.max = max; + this.flags = flags; + this.track = track; + this.type = type; + this.channel = channel; + this.remaining = remaining; + this.frame = null; + this.first = true; + } + + private void preWrite() { + if (remaining == 0) + { + throw new BufferOverflowException(); + } + + if (frame == null) + { + frame = ByteBuffer.allocate(min(max, remaining + HEADER_SIZE)); + frame.order(ByteOrder.BIG_ENDIAN); + + byte frameFlags = flags; + if (first) { frameFlags |= FIRST_FRAME; first = false; } + if (remaining <= (frame.remaining() - HEADER_SIZE)) + { + frameFlags |= LAST_FRAME; + } + + frame.put(frameFlags); + frame.put(type); + frame.putShort((short) frame.limit()); + frame.put(RESERVED); + frame.put(track); + frame.putShort((short) channel); + frame.put(RESERVED); + frame.put(RESERVED); + frame.put(RESERVED); + frame.put(RESERVED); + + assert frame.position() == HEADER_SIZE; + } + } + + private void postWrite() { + if (!frame.hasRemaining()) + { + frame.flip(); + handler.handle(frame); + frame = null; + } + } + + @Override protected void put(byte b) + { + preWrite(); + frame.put(b); + remaining -= 1; + postWrite(); + } + + @Override protected void put(ByteBuffer src) + { + if (src.remaining() > remaining) + { + throw new BufferOverflowException(); + } + + while (src.hasRemaining()) + { + preWrite(); + int limit = src.limit(); + src.limit(src.position() + min(frame.remaining(), src.remaining())); + remaining -= src.remaining(); + frame.put(src); + src.limit(limit); + postWrite(); + } + } + + public static final void main(String[] args) { + ByteBuffer buf = ByteBuffer.allocate(1024); + buf.put("AMQP_PROTOCOL_HEADER".getBytes()); + buf.flip(); + + SegmentEncoder enc = new SegmentEncoder(new Handler() + { + public void handle(ByteBuffer frame) + { + System.out.println(frame); + } + }, + 16, + (byte) 0x0, + (byte) Frame.L1, + (byte) Frame.METHOD, + 0, + 7 + buf.remaining()); + enc.put((byte)0); + enc.put((byte)1); + enc.put((byte)2); + enc.put((byte)3); + enc.put((byte)4); + enc.put((byte)5); + enc.put((byte)6); + enc.put(buf); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Session.java b/qpid/java/common/src/main/java/org/apache/qpidity/Session.java index 32da625070..7d74849b0b 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Session.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Session.java @@ -29,7 +29,7 @@ import java.util.Map; * @author Rafael H. Schloming */ -public class Session extends Invoker implements DelegateResolver +public class Session extends Invoker { // channel may be null @@ -37,7 +37,6 @@ public class Session extends Invoker implements DelegateResolver private int command_id = 0; // XXX final Map> handlers = new HashMap>(); - final private Delegate delegate = new SessionDelegate(); public void attach(Channel channel) { @@ -62,9 +61,4 @@ public class Session extends Invoker implements DelegateResolver return channel.getFactory(); } - public Delegate resolve(Struct struct) - { - return delegate; - } - } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/SimpleDelegateResolver.java b/qpid/java/common/src/main/java/org/apache/qpidity/SimpleDelegateResolver.java new file mode 100644 index 0000000000..fe52f0c90b --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/SimpleDelegateResolver.java @@ -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. + * + */ +package org.apache.qpidity; + + +/** + * SimpleDelegateResolver + * + * @author Rafael H. Schloming + */ + +class SimpleDelegateResolver implements DelegateResolver +{ + + private final Delegate delegate; + + public SimpleDelegateResolver(Delegate delegate) + { + this.delegate = delegate; + } + + public Delegate resolve(Struct struct) + { + return delegate; + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/SizeEncoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/SizeEncoder.java index 745f58fd6d..b6ecdd2818 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/SizeEncoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/SizeEncoder.java @@ -23,7 +23,7 @@ package org.apache.qpidity; import java.nio.ByteBuffer; import java.util.Map; -import java.util.UUID; + /** * SizeEncoder @@ -31,7 +31,7 @@ import java.util.UUID; * @author Rafael H. Schloming */ -class SizeEncoder implements Encoder +class SizeEncoder extends AbstractEncoder { private int size; @@ -52,39 +52,17 @@ class SizeEncoder implements Encoder this.size = size; } - public void writeBit(boolean b) - { - //throw new Error("TODO"); - } - - public void writeOctet(short b) + @Override protected void put(byte b) { size += 1; } - public void writeShort(int s) + @Override protected void put(ByteBuffer src) { - size += 2; + size += src.remaining(); } - public void writeLong(long i) - { - size += 4; - } - - public void writeLonglong(long l) - { - size += 8; - } - - - public void writeTimestamp(long l) - { - size += 8; - } - - - public void writeShortstr(String s) + @Override public void writeShortstr(String s) { if (s.length() > 255) { throw new IllegalArgumentException(s); @@ -93,30 +71,10 @@ class SizeEncoder implements Encoder size += s.length(); } - public void writeLongstr(String s) + @Override public void writeLongstr(String s) { - throw new Error("TODO"); - } - - - public void writeTable(Map table) - { - //throw new Error("TODO"); - } - - public void writeRfc1982LongSet(Range[] ranges) - { - throw new Error("TODO"); - } - - public void writeUuid(UUID uuid) - { - throw new Error("TODO"); - } - - public void writeContent(String c) - { - throw new Error("TODO"); + writeLong(s.length()); + size += s.length(); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/SliceIterator.java b/qpid/java/common/src/main/java/org/apache/qpidity/SliceIterator.java new file mode 100644 index 0000000000..9b4a8f90f7 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/SliceIterator.java @@ -0,0 +1,59 @@ +/* + * + * 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.qpidity; + +import java.nio.ByteBuffer; + +import java.util.Iterator; + + +/** + * SliceIterator + * + * @author Rafael H. Schloming + */ + +class SliceIterator implements Iterator +{ + + final private Iterator iterator; + + public SliceIterator(Iterator iterator) + { + this.iterator = iterator; + } + + public boolean hasNext() + { + return iterator.hasNext(); + } + + public ByteBuffer next() + { + return iterator.next().slice(); + } + + public void remove() + { + throw new UnsupportedOperationException(); + } + +} diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java index be246d325b..e27fc89a59 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java @@ -1,32 +1,47 @@ package org.apache.qpidity; -import java.nio.ByteBuffer; import java.util.*; import java.lang.annotation.*; +import java.nio.ByteBuffer; + import static org.apache.qpidity.Option.*; + public class Stub { - private static Connection conn = new Connection(); + private static Connection conn = new Connection(new ConsoleOutput()); + + static + { + conn.init(new ProtocolHeader((byte) 1, (byte) 0, (byte) 10)); + } - private static void frame(short track, short type, boolean first, boolean last) { + private static void frame(byte track, byte type, boolean first, boolean last) { frame(track, type, first, last, null); } - private static void frame(short track, short type, boolean first, boolean last, Method m) { + private static void frame(byte track, byte type, boolean first, boolean last, Method m) { SizeEncoder sizer = new SizeEncoder(); if (m != null) { + sizer.writeLong(m.getEncodedType()); m.write(sizer); + sizer.flush(); } - ByteBuffer buf = ByteBuffer.allocate(sizer.getSize() + 4); + ByteBuffer buf = ByteBuffer.allocate(sizer.getSize()); if (m != null) { - buf.putInt(m.getEncodedType()); - m.write(new BBEncoder(buf)); + Encoder enc = new BBEncoder(buf); + enc.writeLong(m.getEncodedType()); + m.write(enc); + enc.flush(); } buf.flip(); - Frame frame = new Frame((short)0, track, type, true, true, first, last, buf); - conn.handle(frame); + byte flags = 0; + if (first) { flags |= Frame.FIRST_FRAME; } + if (last) { flags |= Frame.LAST_FRAME; } + Frame frame = new Frame(flags, type, track, 0); + frame.addFragment(buf); + conn.frame(frame); } public static final void main(String[] args) { @@ -59,7 +74,16 @@ class ChannelDelegate extends Delegate { public @Override void sessionOpen(Channel channel, SessionOpen open) { Session ssn = new Session(); ssn.attach(channel); - System.out.println("Session Open"); + long lifetime = open.getDetachedlifetime(); + System.out.println("Session Opened lifetime = " + lifetime); + try + { + ssn.sessionAttached(UUID.randomUUID(), lifetime); + } + catch (QpidException e) + { + throw new RuntimeException(e); + } } } @@ -74,11 +98,11 @@ class SessionDelegate extends Delegate { System.out.println("got an exchange declare: " + ed.getExchange() + ", " + ed.getType()); try { - session.queueDeclare("asdf", "alternate", null); + session.queueDeclare("asdf", "alternate", null); } - catch(Exception e) + catch(QpidException e) { - + throw new RuntimeException(e); } } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Switch.java b/qpid/java/common/src/main/java/org/apache/qpidity/Switch.java index a84ae1507b..166dc33134 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Switch.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Switch.java @@ -44,6 +44,12 @@ abstract class Switch implements Handler { K key = resolve(event); Handler handler = handlers.get(key); + if (handler == null) + { + throw new IllegalStateException("no such key: " + key + + " this = " + this + + " handlers = " + handlers); + } handler.handle(event); } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/TrackSwitch.java b/qpid/java/common/src/main/java/org/apache/qpidity/TrackSwitch.java index c9b3cda032..28a7d75f05 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/TrackSwitch.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/TrackSwitch.java @@ -28,10 +28,10 @@ package org.apache.qpidity; * @author Rafael H. Schloming */ -class TrackSwitch extends Switch> +class TrackSwitch extends Switch> { - public Short resolve(Event event) + public Byte resolve(Event event) { return event.target.getTrack(); } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/TypeSwitch.java b/qpid/java/common/src/main/java/org/apache/qpidity/TypeSwitch.java index a5073486c7..fc53b0b9b4 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/TypeSwitch.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/TypeSwitch.java @@ -28,10 +28,10 @@ package org.apache.qpidity; * @author Rafael H. Schloming */ -class TypeSwitch extends Switch> +class TypeSwitch extends Switch> { - public Short resolve(Event event) + public Byte resolve(Event event) { return event.target.getType(); } -- cgit v1.2.1 From 2c5548009056f0372d97876493ab1c8748d22d97 Mon Sep 17 00:00:00 2001 From: Rajith Muditha Attapattu Date: Wed, 1 Aug 2007 22:27:03 +0000 Subject: StreamingMessageListener - was added to deliver message parts as an when they are available as opposed to sending a completed message (as in MessageListener) Message - was added to abstract the message data underneath. this can be used in both broker and client git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@561980 13f79535-47bb-0310-9956-ffa450edef68 --- .../main/java/org/apache/qpidity/api/Message.java | 62 ++++++++++++++++++++++ .../qpidity/api/StreamingMessageListener.java | 60 +++++++++++++++++++++ 2 files changed, 122 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/api/Message.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/api/StreamingMessageListener.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/api/Message.java b/qpid/java/common/src/main/java/org/apache/qpidity/api/Message.java new file mode 100644 index 0000000000..6086cc6a49 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/api/Message.java @@ -0,0 +1,62 @@ +package org.apache.qpidity.api; + +import org.apache.qpidity.ApplicationProperties; +import org.apache.qpidity.DeliveryProperties; + +/* + * 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. + */ + +public interface Message +{ + public ApplicationProperties getApplicationProperties(); + + public DeliveryProperties getDeliveryProperties(); + + /** + * This will abstract the underlying message data. + * The Message implementation may not hold all message + * data in memory (especially in the case of large messages) + * + * The appendData function might write data to + *

          + *
        • Memory (Ex: ByteBuffer) + *
        • To Disk + *
        • To Socket (Stream) + *
        + * @param src + */ + public void appendData(byte[] src); + + /** + * This will abstract the underlying message data. + * The Message implementation may not hold all message + * data in memory (especially in the case of large messages) + * + * The read function might copy data from a + *
          + *
        • From memory (Ex: ByteBuffer) + *
        • From Disk + *
        • From Socket as and when it gets streamed + *
        + * @param target + */ + public void readData(byte[] target); + +} + diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/api/StreamingMessageListener.java b/qpid/java/common/src/main/java/org/apache/qpidity/api/StreamingMessageListener.java new file mode 100644 index 0000000000..b361e2ac82 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/api/StreamingMessageListener.java @@ -0,0 +1,60 @@ +package org.apache.qpidity.api; + +import org.apache.qpidity.Header; +import org.apache.qpidity.Option; + +/** + *

        This message listener is useful if u need to + * know when each message part becomes available + * as opposed to knowing when the whole message arrives.

        + * + */ +public interface StreamingMessageListener +{ + /** + * Transfer the given message. + *

        Following are the valid options for messageTransfer + *

          + *
        • CONFIRM + *
        • PRE_ACQUIRE + *
        + *

        + * + *

        In the absence of a particular option, the defaul value is: + *

          + *
        • CONFIRM = false + *
        • NO-ACCQUIRE + *
        + *

        + * + * @param destination The exchange the message being sent. + * @return options set of options + * @throws QpidException If the session fails to send the message due to some error + */ + public void messageTransfer(String destination,Option... options); + + /** + * Add the following headers to content bearing frame + * + * @param Header Either DeliveryProperties or ApplicationProperties + * @throws QpidException If the session fails to execute the method due to some error + */ + public void messageHeaders(Header ... headers); + + /** + * Add the following byte array to the content. + * This method is useful when streaming large messages + * + * @param src data to be added or streamed + * @throws QpidException If the session fails to execute the method due to some error + */ + public void data(byte[] src); + + /** + * Signals the end of data for the message. * + * This method is useful when streaming large messages + * + * @throws QpidException If the session fails to execute the method due to some error + */ + public void endData(); +} -- cgit v1.2.1 From 03d56e9ac9b87e35096a7efe6649985eec1b1894 Mon Sep 17 00:00:00 2001 From: Rajith Muditha Attapattu Date: Wed, 1 Aug 2007 22:27:55 +0000 Subject: added wiring to Rafi's comm stack git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@561981 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpidity/CommonSessionDelegate.java | 33 +++++++++++ .../java/org/apache/qpidity/HeaderHandler.java | 1 + .../src/main/java/org/apache/qpidity/Session.java | 64 ++++++++++++++++++++++ 3 files changed, 98 insertions(+) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java b/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java index e9173a5c5b..3bca6116a4 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java @@ -20,6 +20,8 @@ */ package org.apache.qpidity; +import org.apache.qpidity.api.StreamingMessageListener; + /** * CommonSessionDelegate @@ -48,4 +50,35 @@ public class CommonSessionDelegate extends Delegate @Override public void sessionDetached(Session session, SessionDetached struct) {} + @Override + public void messageTransfer(Session context, MessageTransfer struct) + { + StreamingMessageListener l = context.messagListeners.get(struct.getDestination()); + l.messageTransfer(struct.getDestination(),new Option[0]); + } + + // --------------------------------------------------------------- + // Non generated methods - but would like if they are also generated. + // These methods should be called from Body and Header Handlers. + // If these methods are generated as part of the delegate then + // I can call these methods from the BodyHandler and HeaderHandler + // in a generic way + // ---------------------------------------------------------------- + public void data(Session context,String destination,byte[] src) throws QpidException + { + StreamingMessageListener l = context.messagListeners.get(destination); + l.data(src); + } + + public void endData(Session context,String destination) throws QpidException + { + StreamingMessageListener l = context.messagListeners.get(destination); + l.endData(); + } + + public void messageHeaders(Session context,String destination,Header... headers) throws QpidException + { + StreamingMessageListener l = context.messagListeners.get(destination); + l.endData(); + } } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/HeaderHandler.java b/qpid/java/common/src/main/java/org/apache/qpidity/HeaderHandler.java index a63c032e38..8a407cd9f6 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/HeaderHandler.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/HeaderHandler.java @@ -33,6 +33,7 @@ class HeaderHandler implements Handler> public void handle(Event event) { System.out.println("got header segment:\n " + event.target); + } } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Session.java b/qpid/java/common/src/main/java/org/apache/qpidity/Session.java index 7d74849b0b..48860309a0 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Session.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Session.java @@ -23,6 +23,9 @@ package org.apache.qpidity; import java.util.HashMap; import java.util.Map; +import org.apache.qpidity.api.Message; +import org.apache.qpidity.api.StreamingMessageListener; + /** * Session * @@ -37,6 +40,8 @@ public class Session extends Invoker private int command_id = 0; // XXX final Map> handlers = new HashMap>(); + + Map messagListeners = new HashMap(); public void attach(Channel channel) { @@ -61,4 +66,63 @@ public class Session extends Invoker return channel.getFactory(); } + // ----------------------------------------- + // Messaging Methods + // ------------------------------------------ + public void messageTransfer(String destination, Message msg) throws QpidException + { + + } + + public void data(byte[] src) throws QpidException + { + // TODO Auto-generated method stub + + } + + public void endData() throws QpidException + { + // TODO Auto-generated method stub + + } + + public void messageHeaders(Header... headers) throws QpidException + { + // TODO Auto-generated method stub + + } + + public void messageTransfer(String destination,Option... options) throws QpidException + { + // TODO Auto-generated method stub + + } + + public void messageAcknowledge() throws QpidException + { + // TODO Auto-generated method stub + } + + public boolean messageAcquire() throws QpidException + { + // TODO Auto-generated method stub + return false; + } + + public void messageReject() throws QpidException + { + // TODO Auto-generated method stub + + } + + public void messageRelease() throws QpidException + { + // TODO Auto-generated method stub + } + + public void addMessageListener(String destination,StreamingMessageListener listener) + { + messagListeners.put(destination, listener); + } + } -- cgit v1.2.1 From 08da3f648daf8cd878293e6c0cec36f63bb383d6 Mon Sep 17 00:00:00 2001 From: Rajith Muditha Attapattu Date: Wed, 1 Aug 2007 23:12:38 +0000 Subject: added more comments to the CommonSessionDelegate git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@561986 13f79535-47bb-0310-9956-ffa450edef68 --- .../src/main/java/org/apache/qpidity/CommonSessionDelegate.java | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java b/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java index 3bca6116a4..80d54ef173 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java @@ -63,6 +63,11 @@ public class CommonSessionDelegate extends Delegate // If these methods are generated as part of the delegate then // I can call these methods from the BodyHandler and HeaderHandler // in a generic way + + + // I have used destination to indicate my intent of receiving + // some form of correlation to know which consumer this data belongs to. + // It can be anything as long as I can make the right correlation // ---------------------------------------------------------------- public void data(Session context,String destination,byte[] src) throws QpidException { -- cgit v1.2.1 From 8eab2c30ae3cc0e523954d317517aab264923286 Mon Sep 17 00:00:00 2001 From: "Rafael H. Schloming" Date: Fri, 3 Aug 2007 04:00:41 +0000 Subject: fixed build failures caused by sloppy checkins and SNAPSHOT dependencies, changed the junit-toolkit version from 0.6-SNAPSHOT to 0.6-20070718.144514-11 git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@562323 13f79535-47bb-0310-9956-ffa450edef68 --- .../src/main/java/org/apache/qpidity/Session.java | 101 ++++++++++----------- 1 file changed, 48 insertions(+), 53 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Session.java b/qpid/java/common/src/main/java/org/apache/qpidity/Session.java index 48860309a0..32fa5f55b3 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Session.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Session.java @@ -69,60 +69,55 @@ public class Session extends Invoker // ----------------------------------------- // Messaging Methods // ------------------------------------------ - public void messageTransfer(String destination, Message msg) throws QpidException - { - - } - - public void data(byte[] src) throws QpidException - { - // TODO Auto-generated method stub - - } - - public void endData() throws QpidException - { - // TODO Auto-generated method stub - - } - - public void messageHeaders(Header... headers) throws QpidException - { - // TODO Auto-generated method stub - - } - - public void messageTransfer(String destination,Option... options) throws QpidException - { - // TODO Auto-generated method stub - - } - - public void messageAcknowledge() throws QpidException - { - // TODO Auto-generated method stub - } - - public boolean messageAcquire() throws QpidException - { - // TODO Auto-generated method stub - return false; - } - - public void messageReject() throws QpidException - { - // TODO Auto-generated method stub - - } - - public void messageRelease() throws QpidException - { - // TODO Auto-generated method stub - } + public void messageTransfer(String destination, Message msg, Option ... _options) throws QpidException + { - public void addMessageListener(String destination,StreamingMessageListener listener) + } + + public void data(byte[] src) throws QpidException + { + // TODO Auto-generated method stub + } + + public void endData() throws QpidException + { + // TODO Auto-generated method stub + } + + public void messageHeaders(Header... headers) throws QpidException + { + // TODO Auto-generated method stub + } + + public void messageTransfer(String destination,Option... options) throws QpidException + { + // TODO Auto-generated method stub + } + + public void messageAcknowledge() throws QpidException + { + // TODO Auto-generated method stub + } + + public boolean messageAcquire() throws QpidException + { + // TODO Auto-generated method stub + return false; + } + + public void messageReject() throws QpidException + { + // TODO Auto-generated method stub + } + + public void messageRelease() throws QpidException + { + // TODO Auto-generated method stub + } + + public void setMessageListener(String destination,StreamingMessageListener listener) { messagListeners.put(destination, listener); - } - + } + } -- cgit v1.2.1 From 1a683c482dc7e4961a68733e6b5c63f343264594 Mon Sep 17 00:00:00 2001 From: "Rafael H. Schloming" Date: Fri, 3 Aug 2007 04:25:25 +0000 Subject: added amqp.0-10-preview.xml and switched the qpidity codegen over to use it git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@562325 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpidity/AbstractDecoder.java | 14 ++++ .../java/org/apache/qpidity/AbstractEncoder.java | 10 +++ .../main/java/org/apache/qpidity/BBDecoder.java | 3 +- .../org/apache/qpidity/CommonSessionDelegate.java | 75 ++++++++++------------ .../src/main/java/org/apache/qpidity/Decoder.java | 2 + .../src/main/java/org/apache/qpidity/Encoder.java | 2 + .../java/org/apache/qpidity/FragmentDecoder.java | 3 +- .../src/main/java/org/apache/qpidity/Method.java | 5 +- .../java/org/apache/qpidity/MethodDispatcher.java | 2 +- .../src/main/java/org/apache/qpidity/Struct.java | 7 +- 10 files changed, 76 insertions(+), 47 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/AbstractDecoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractDecoder.java index 42da09f2d9..ee350ac343 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/AbstractDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractDecoder.java @@ -35,6 +35,13 @@ import static org.apache.qpidity.Functions.*; abstract class AbstractDecoder implements Decoder { + private final StructFactory factory; + + protected AbstractDecoder(StructFactory factory) + { + this.factory = factory; + } + protected abstract byte get(); protected abstract void get(byte[] bytes); @@ -146,4 +153,11 @@ abstract class AbstractDecoder implements Decoder throw new Error("Deprecated"); } + public Struct readLongStruct() + { + long size = readLong(); + int type = readShort(); + return factory.create(type, this); + } + } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/AbstractEncoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractEncoder.java index 5ca68fe564..deca409788 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/AbstractEncoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/AbstractEncoder.java @@ -155,6 +155,16 @@ abstract class AbstractEncoder implements Encoder throw new Error("Deprecated"); } + public void writeLongStruct(Struct s) + { + SizeEncoder sizer = new SizeEncoder(); + sizer.writeShort(s.getEncodedType()); + s.write(sizer); + writeLong(sizer.getSize()); + writeShort(s.getEncodedType()); + s.write(this); + } + public void flush() { flushBits(); diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java index 08ac03113f..49255de4be 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/BBDecoder.java @@ -34,8 +34,9 @@ class BBDecoder extends AbstractDecoder private final ByteBuffer in; - public BBDecoder(ByteBuffer in) + public BBDecoder(StructFactory factory, ByteBuffer in) { + super(factory); this.in = in; } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java b/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java index 80d54ef173..7ae9a99fd2 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java @@ -42,48 +42,43 @@ public class CommonSessionDelegate extends Delegate @Override public void sessionResume(Session session, SessionResume struct) {} - @Override public void sessionPing(Session session, SessionPing struct) {} - - @Override public void sessionPong(Session session, SessionPong struct) {} - @Override public void sessionSuspend(Session session, SessionSuspend struct) {} @Override public void sessionDetached(Session session, SessionDetached struct) {} - @Override - public void messageTransfer(Session context, MessageTransfer struct) - { - StreamingMessageListener l = context.messagListeners.get(struct.getDestination()); - l.messageTransfer(struct.getDestination(),new Option[0]); - } - - // --------------------------------------------------------------- - // Non generated methods - but would like if they are also generated. - // These methods should be called from Body and Header Handlers. - // If these methods are generated as part of the delegate then - // I can call these methods from the BodyHandler and HeaderHandler - // in a generic way - - - // I have used destination to indicate my intent of receiving - // some form of correlation to know which consumer this data belongs to. - // It can be anything as long as I can make the right correlation - // ---------------------------------------------------------------- - public void data(Session context,String destination,byte[] src) throws QpidException - { - StreamingMessageListener l = context.messagListeners.get(destination); - l.data(src); - } - - public void endData(Session context,String destination) throws QpidException - { - StreamingMessageListener l = context.messagListeners.get(destination); - l.endData(); - } - - public void messageHeaders(Session context,String destination,Header... headers) throws QpidException - { - StreamingMessageListener l = context.messagListeners.get(destination); - l.endData(); - } + @Override public void messageTransfer(Session context, MessageTransfer struct) + { + StreamingMessageListener l = context.messagListeners.get(struct.getDestination()); + l.messageTransfer(struct.getDestination(),new Option[0]); + } + + // --------------------------------------------------------------- + // Non generated methods - but would like if they are also generated. + // These methods should be called from Body and Header Handlers. + // If these methods are generated as part of the delegate then + // I can call these methods from the BodyHandler and HeaderHandler + // in a generic way + + // I have used destination to indicate my intent of receiving + // some form of correlation to know which consumer this data belongs to. + // It can be anything as long as I can make the right correlation + // ---------------------------------------------------------------- + public void data(Session context,String destination,byte[] src) throws QpidException + { + StreamingMessageListener l = context.messagListeners.get(destination); + l.data(src); + } + + public void endData(Session context,String destination) throws QpidException + { + StreamingMessageListener l = context.messagListeners.get(destination); + l.endData(); + } + + public void messageHeaders(Session context,String destination,Header... headers) throws QpidException + { + StreamingMessageListener l = context.messagListeners.get(destination); + l.endData(); + } + } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Decoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/Decoder.java index 26191fa7ba..0a869baab7 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Decoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Decoder.java @@ -49,4 +49,6 @@ public interface Decoder String readContent(); + Struct readLongStruct(); + } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java index 954b690dc2..c25b96e462 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Encoder.java @@ -51,4 +51,6 @@ public interface Encoder void flush(); + void writeLongStruct(Struct s); + } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/FragmentDecoder.java b/qpid/java/common/src/main/java/org/apache/qpidity/FragmentDecoder.java index dcf1c19c38..64ee4ef6ce 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/FragmentDecoder.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/FragmentDecoder.java @@ -40,8 +40,9 @@ class FragmentDecoder extends AbstractDecoder private final Iterator fragments; private ByteBuffer current; - public FragmentDecoder(Iterator fragments) + public FragmentDecoder(StructFactory factory, Iterator fragments) { + super(factory); this.fragments = fragments; this.current = null; } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Method.java b/qpid/java/common/src/main/java/org/apache/qpidity/Method.java index a3926b572e..ab8825743c 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Method.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Method.java @@ -27,9 +27,8 @@ package org.apache.qpidity; * @author Rafael H. Schloming */ -interface Method extends Struct { - - int getEncodedType(); +interface Method extends Struct +{ byte getEncodedTrack(); diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/MethodDispatcher.java b/qpid/java/common/src/main/java/org/apache/qpidity/MethodDispatcher.java index 8fbc6f547d..b4545705ea 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/MethodDispatcher.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/MethodDispatcher.java @@ -47,7 +47,7 @@ class MethodDispatcher implements Handler> { System.out.println("got method segment:\n " + event.target); Iterator fragments = event.target.getFragments(); - Decoder dec = new FragmentDecoder(fragments); + Decoder dec = new FragmentDecoder(factory, fragments); int type = (int) dec.readLong(); Struct struct = factory.create(type, dec); Delegate delegate = resolver.resolve(struct); diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Struct.java b/qpid/java/common/src/main/java/org/apache/qpidity/Struct.java index 6d9913b042..63b0db2c12 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Struct.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Struct.java @@ -27,4 +27,9 @@ package org.apache.qpidity; * @author Rafael H. Schloming */ -interface Struct extends Delegator, Writable {} +interface Struct extends Delegator, Writable +{ + + int getEncodedType(); + +} -- cgit v1.2.1 From c23f0c0d9fa65434ff0dec11c8eb44ac0e274272 Mon Sep 17 00:00:00 2001 From: Arnaud Simon Date: Fri, 3 Aug 2007 11:32:28 +0000 Subject: Moved into client git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@562413 13f79535-47bb-0310-9956-ffa450edef68 --- .../qpidity/api/StreamingMessageListener.java | 60 ---------------------- 1 file changed, 60 deletions(-) delete mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/api/StreamingMessageListener.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/api/StreamingMessageListener.java b/qpid/java/common/src/main/java/org/apache/qpidity/api/StreamingMessageListener.java deleted file mode 100644 index b361e2ac82..0000000000 --- a/qpid/java/common/src/main/java/org/apache/qpidity/api/StreamingMessageListener.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.apache.qpidity.api; - -import org.apache.qpidity.Header; -import org.apache.qpidity.Option; - -/** - *

        This message listener is useful if u need to - * know when each message part becomes available - * as opposed to knowing when the whole message arrives.

        - * - */ -public interface StreamingMessageListener -{ - /** - * Transfer the given message. - *

        Following are the valid options for messageTransfer - *

          - *
        • CONFIRM - *
        • PRE_ACQUIRE - *
        - *

        - * - *

        In the absence of a particular option, the defaul value is: - *

          - *
        • CONFIRM = false - *
        • NO-ACCQUIRE - *
        - *

        - * - * @param destination The exchange the message being sent. - * @return options set of options - * @throws QpidException If the session fails to send the message due to some error - */ - public void messageTransfer(String destination,Option... options); - - /** - * Add the following headers to content bearing frame - * - * @param Header Either DeliveryProperties or ApplicationProperties - * @throws QpidException If the session fails to execute the method due to some error - */ - public void messageHeaders(Header ... headers); - - /** - * Add the following byte array to the content. - * This method is useful when streaming large messages - * - * @param src data to be added or streamed - * @throws QpidException If the session fails to execute the method due to some error - */ - public void data(byte[] src); - - /** - * Signals the end of data for the message. * - * This method is useful when streaming large messages - * - * @throws QpidException If the session fails to execute the method due to some error - */ - public void endData(); -} -- cgit v1.2.1 From 6df19b471e0f15e5aae31598b7816932990dc026 Mon Sep 17 00:00:00 2001 From: Rajith Muditha Attapattu Date: Fri, 3 Aug 2007 14:37:14 +0000 Subject: Fixed compilation errors git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@562479 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/qpidity/CommonSessionDelegate.java | 41 +--------------------- .../src/main/java/org/apache/qpidity/Session.java | 13 ++----- 2 files changed, 3 insertions(+), 51 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java b/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java index 7ae9a99fd2..cd9d31b1c2 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/CommonSessionDelegate.java @@ -20,9 +20,6 @@ */ package org.apache.qpidity; -import org.apache.qpidity.api.StreamingMessageListener; - - /** * CommonSessionDelegate */ @@ -44,41 +41,5 @@ public class CommonSessionDelegate extends Delegate @Override public void sessionSuspend(Session session, SessionSuspend struct) {} - @Override public void sessionDetached(Session session, SessionDetached struct) {} - - @Override public void messageTransfer(Session context, MessageTransfer struct) - { - StreamingMessageListener l = context.messagListeners.get(struct.getDestination()); - l.messageTransfer(struct.getDestination(),new Option[0]); - } - - // --------------------------------------------------------------- - // Non generated methods - but would like if they are also generated. - // These methods should be called from Body and Header Handlers. - // If these methods are generated as part of the delegate then - // I can call these methods from the BodyHandler and HeaderHandler - // in a generic way - - // I have used destination to indicate my intent of receiving - // some form of correlation to know which consumer this data belongs to. - // It can be anything as long as I can make the right correlation - // ---------------------------------------------------------------- - public void data(Session context,String destination,byte[] src) throws QpidException - { - StreamingMessageListener l = context.messagListeners.get(destination); - l.data(src); - } - - public void endData(Session context,String destination) throws QpidException - { - StreamingMessageListener l = context.messagListeners.get(destination); - l.endData(); - } - - public void messageHeaders(Session context,String destination,Header... headers) throws QpidException - { - StreamingMessageListener l = context.messagListeners.get(destination); - l.endData(); - } - + @Override public void sessionDetached(Session session, SessionDetached struct) {} } diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Session.java b/qpid/java/common/src/main/java/org/apache/qpidity/Session.java index 32fa5f55b3..666d6463c0 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Session.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Session.java @@ -24,8 +24,6 @@ import java.util.HashMap; import java.util.Map; import org.apache.qpidity.api.Message; -import org.apache.qpidity.api.StreamingMessageListener; - /** * Session * @@ -39,9 +37,7 @@ public class Session extends Invoker Channel channel; private int command_id = 0; // XXX - final Map> handlers = new HashMap>(); - - Map messagListeners = new HashMap(); + final Map> handlers = new HashMap>(); public void attach(Channel channel) { @@ -113,11 +109,6 @@ public class Session extends Invoker public void messageRelease() throws QpidException { // TODO Auto-generated method stub - } - - public void setMessageListener(String destination,StreamingMessageListener listener) - { - messagListeners.put(destination, listener); - } + } } -- cgit v1.2.1 From fb4a597fe874222728dbe27e899392285444d53c Mon Sep 17 00:00:00 2001 From: "Rafael H. Schloming" Date: Sat, 4 Aug 2007 22:52:50 +0000 Subject: added struct codegen and fixed naming bug in generated getters git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@562775 13f79535-47bb-0310-9956-ffa450edef68 --- qpid/java/common/src/main/java/org/apache/qpidity/Stub.java | 2 +- qpid/java/common/src/main/java/org/apache/qpidity/api/Message.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java index e27fc89a59..e4ac8358f3 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/Stub.java @@ -74,7 +74,7 @@ class ChannelDelegate extends Delegate { public @Override void sessionOpen(Channel channel, SessionOpen open) { Session ssn = new Session(); ssn.attach(channel); - long lifetime = open.getDetachedlifetime(); + long lifetime = open.getDetachedLifetime(); System.out.println("Session Opened lifetime = " + lifetime); try { diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/api/Message.java b/qpid/java/common/src/main/java/org/apache/qpidity/api/Message.java index 6086cc6a49..2305027556 100644 --- a/qpid/java/common/src/main/java/org/apache/qpidity/api/Message.java +++ b/qpid/java/common/src/main/java/org/apache/qpidity/api/Message.java @@ -1,6 +1,6 @@ package org.apache.qpidity.api; -import org.apache.qpidity.ApplicationProperties; +import org.apache.qpidity.MessageProperties; import org.apache.qpidity.DeliveryProperties; /* @@ -24,7 +24,7 @@ import org.apache.qpidity.DeliveryProperties; public interface Message { - public ApplicationProperties getApplicationProperties(); + public MessageProperties getMessageProperties(); public DeliveryProperties getDeliveryProperties(); -- cgit v1.2.1 From f14bda91cf8a8a40c0b895112f829574cff52664 Mon Sep 17 00:00:00 2001 From: Arnaud Simon Date: Sun, 5 Aug 2007 16:47:32 +0000 Subject: added default exchange git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@562904 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/qpidity/exchange/ExchangeDefaults.java | 51 ++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/exchange/ExchangeDefaults.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/exchange/ExchangeDefaults.java b/qpid/java/common/src/main/java/org/apache/qpidity/exchange/ExchangeDefaults.java new file mode 100644 index 0000000000..a99ea56d69 --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/exchange/ExchangeDefaults.java @@ -0,0 +1,51 @@ +/* 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.qpidity.exchange; + +/** + * Default exchange names + */ +public class ExchangeDefaults +{ + /** The default direct exchange, which is a special internal exchange that cannot be explicitly bound to. */ + public static final String DEFAULT_EXCHANGE_NAME = "<>"; + + /** The pre-defined topic exchange, the broker SHOULD provide this. */ + public static final String TOPIC_EXCHANGE_NAME = "amq.topic"; + + /** Defines the identifying type name of topic exchanges. */ + public static final String TOPIC_EXCHANGE_CLASS = "topic"; + + /** The pre-defined direct exchange, the broker MUST provide this. */ + public static final String DIRECT_EXCHANGE_NAME = "amq.direct"; + + /** Defines the identifying type name of direct exchanges. */ + public static final String DIRECT_EXCHANGE_CLASS = "direct"; + + /** The pre-defined headers exchange, the specification does not say this needs to be provided. */ + public static final String HEADERS_EXCHANGE_NAME = "amq.match"; + + /** Defines the identifying type name of headers exchanges. */ + public static final String HEADERS_EXCHANGE_CLASS = "headers"; + + /** The pre-defined fanout exchange, the boker MUST provide this. */ + public static final String FANOUT_EXCHANGE_NAME = "amq.fanout"; + + /** Defines the identifying type name of fanout exchanges. */ + public static final String FANOUT_EXCHANGE_CLASS = "fanout"; +} -- cgit v1.2.1 From 999b19703dca14e7209230e07ea145ee084e528f Mon Sep 17 00:00:00 2001 From: Arnaud Simon Date: Mon, 6 Aug 2007 10:32:50 +0000 Subject: git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/trunk@563097 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/qpidity/url/AMQBindingURL.java | 261 +++++++++++++++++++++ .../java/org/apache/qpidity/url/BindingURL.java | 53 +++++ .../java/org/apache/qpidity/url/URLHelper.java | 169 +++++++++++++ .../org/apache/qpidity/url/URLSyntaxException.java | 94 ++++++++ 4 files changed, 577 insertions(+) create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/url/AMQBindingURL.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/url/BindingURL.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/url/URLHelper.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpidity/url/URLSyntaxException.java (limited to 'qpid/java/common/src') diff --git a/qpid/java/common/src/main/java/org/apache/qpidity/url/AMQBindingURL.java b/qpid/java/common/src/main/java/org/apache/qpidity/url/AMQBindingURL.java new file mode 100644 index 0000000000..0edf9ac21b --- /dev/null +++ b/qpid/java/common/src/main/java/org/apache/qpidity/url/AMQBindingURL.java @@ -0,0 +1,261 @@ +/* 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.qpidity.url; + +import org.apache.qpidity.exchange.ExchangeDefaults; +import org.slf4j.LoggerFactory; +import org.slf4j.Logger; + +import java.util.HashMap; +import java.net.URI; +import java.net.URISyntaxException; + +public class AMQBindingURL implements BindingURL +{ + private static final Logger _logger = LoggerFactory.getLogger(AMQBindingURL.class); + + String _url; + String _exchangeClass; + String _exchangeName; + String _destinationName; + String _queueName; + private HashMap _options; + + public AMQBindingURL(String url) throws URLSyntaxException + { + // format: + // :///[]/[]?