You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tomcat.apache.org by fh...@apache.org on 2006/08/22 19:28:15 UTC
svn commit: r433703 [8/14] - in /tomcat/tc6.0.x/trunk: ./
java/org/apache/catalina/ha/ java/org/apache/catalina/ha/context/
java/org/apache/catalina/ha/deploy/ java/org/apache/catalina/ha/session/
java/org/apache/catalina/ha/tcp/ java/org/apache/catali...
Added: tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/ChannelInterceptorBase.java
URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/ChannelInterceptorBase.java?rev=433703&view=auto
==============================================================================
--- tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/ChannelInterceptorBase.java (added)
+++ tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/ChannelInterceptorBase.java Tue Aug 22 10:28:09 2006
@@ -0,0 +1,171 @@
+/*
+ * Copyright 1999,2004-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.catalina.tribes.group;
+
+import org.apache.catalina.tribes.ChannelException;
+import org.apache.catalina.tribes.ChannelInterceptor;
+import org.apache.catalina.tribes.ChannelMessage;
+import org.apache.catalina.tribes.Member;
+
+/**
+ * Abstract class for the interceptor base class.
+ * @author Filip Hanik
+ * @version $Revision: 304032 $, $Date: 2005-07-27 10:11:55 -0500 (Wed, 27 Jul 2005) $
+ */
+
+public abstract class ChannelInterceptorBase implements ChannelInterceptor {
+
+ protected static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(
+ ChannelInterceptorBase.class);
+
+ private ChannelInterceptor next;
+ private ChannelInterceptor previous;
+ //default value, always process
+ protected int optionFlag = 0;
+
+ public ChannelInterceptorBase() {
+
+ }
+
+ public boolean okToProcess(int messageFlags) {
+ if (this.optionFlag == 0 ) return true;
+ return ((optionFlag&messageFlags) == optionFlag);
+ }
+
+ public final void setNext(ChannelInterceptor next) {
+ this.next = next;
+ }
+
+ public final ChannelInterceptor getNext() {
+ return next;
+ }
+
+ public final void setPrevious(ChannelInterceptor previous) {
+ this.previous = previous;
+ }
+
+ public void setOptionFlag(int optionFlag) {
+ this.optionFlag = optionFlag;
+ }
+
+ public final ChannelInterceptor getPrevious() {
+ return previous;
+ }
+
+ public int getOptionFlag() {
+ return optionFlag;
+ }
+
+ public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws
+ ChannelException {
+ if (getNext() != null) getNext().sendMessage(destination, msg, payload);
+ }
+
+ public void messageReceived(ChannelMessage msg) {
+ if (getPrevious() != null) getPrevious().messageReceived(msg);
+ }
+
+ public boolean accept(ChannelMessage msg) {
+ return true;
+ }
+
+ public void memberAdded(Member member) {
+ //notify upwards
+ if (getPrevious() != null) getPrevious().memberAdded(member);
+ }
+
+ public void memberDisappeared(Member member) {
+ //notify upwards
+ if (getPrevious() != null) getPrevious().memberDisappeared(member);
+ }
+
+ public void heartbeat() {
+ if (getNext() != null) getNext().heartbeat();
+ }
+
+ /**
+ * has members
+ */
+ public boolean hasMembers() {
+ if ( getNext()!=null )return getNext().hasMembers();
+ else return false;
+ }
+
+ /**
+ * Get all current cluster members
+ * @return all members or empty array
+ */
+ public Member[] getMembers() {
+ if ( getNext()!=null ) return getNext().getMembers();
+ else return null;
+ }
+
+ /**
+ *
+ * @param mbr Member
+ * @return Member
+ */
+ public Member getMember(Member mbr) {
+ if ( getNext()!=null) return getNext().getMember(mbr);
+ else return null;
+ }
+
+ /**
+ * Return the member that represents this node.
+ *
+ * @return Member
+ */
+ public Member getLocalMember(boolean incAlive) {
+ if ( getNext()!=null ) return getNext().getLocalMember(incAlive);
+ else return null;
+ }
+
+ /**
+ * Starts up the channel. This can be called multiple times for individual services to start
+ * The svc parameter can be the logical or value of any constants
+ * @param svc int value of <BR>
+ * DEFAULT - will start all services <BR>
+ * MBR_RX_SEQ - starts the membership receiver <BR>
+ * MBR_TX_SEQ - starts the membership broadcaster <BR>
+ * SND_TX_SEQ - starts the replication transmitter<BR>
+ * SND_RX_SEQ - starts the replication receiver<BR>
+ * @throws ChannelException if a startup error occurs or the service is already started.
+ */
+ public void start(int svc) throws ChannelException {
+ if ( getNext()!=null ) getNext().start(svc);
+ }
+
+ /**
+ * Shuts down the channel. This can be called multiple times for individual services to shutdown
+ * The svc parameter can be the logical or value of any constants
+ * @param svc int value of <BR>
+ * DEFAULT - will shutdown all services <BR>
+ * MBR_RX_SEQ - stops the membership receiver <BR>
+ * MBR_TX_SEQ - stops the membership broadcaster <BR>
+ * SND_TX_SEQ - stops the replication transmitter<BR>
+ * SND_RX_SEQ - stops the replication receiver<BR>
+ * @throws ChannelException if a startup error occurs or the service is already started.
+ */
+ public void stop(int svc) throws ChannelException {
+ if (getNext() != null) getNext().stop(svc);
+ }
+
+ public void fireInterceptorEvent(InterceptorEvent event) {
+ //empty operation
+ }
+
+
+}
Added: tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/GroupChannel.java
URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/GroupChannel.java?rev=433703&view=auto
==============================================================================
--- tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/GroupChannel.java (added)
+++ tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/GroupChannel.java Tue Aug 22 10:28:09 2006
@@ -0,0 +1,666 @@
+/*
+ * Copyright 1999,2004-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.catalina.tribes.group;
+
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import org.apache.catalina.tribes.ByteMessage;
+import org.apache.catalina.tribes.Channel;
+import org.apache.catalina.tribes.ChannelException;
+import org.apache.catalina.tribes.ChannelInterceptor;
+import org.apache.catalina.tribes.ChannelListener;
+import org.apache.catalina.tribes.ChannelMessage;
+import org.apache.catalina.tribes.ChannelReceiver;
+import org.apache.catalina.tribes.ChannelSender;
+import org.apache.catalina.tribes.ErrorHandler;
+import org.apache.catalina.tribes.ManagedChannel;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.MembershipListener;
+import org.apache.catalina.tribes.MembershipService;
+import org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor;
+import org.apache.catalina.tribes.io.ChannelData;
+import org.apache.catalina.tribes.io.XByteBuffer;
+import org.apache.catalina.tribes.UniqueId;
+import org.apache.catalina.tribes.Heartbeat;
+import org.apache.catalina.tribes.io.BufferPool;
+import java.io.IOException;
+import org.apache.catalina.tribes.RemoteProcessException;
+import org.apache.catalina.tribes.util.Logs;
+import org.apache.catalina.tribes.util.Arrays;
+
+/**
+ * The default implementation of a Channel.<br>
+ * The GroupChannel manages the replication channel. It coordinates
+ * message being sent and received with membership announcements.
+ * The channel has an chain of interceptors that can modify the message or perform other logic.<br>
+ * It manages a complete group, both membership and replication.
+ * @author Filip Hanik
+ * @version $Revision: 304032 $, $Date: 2005-07-27 10:11:55 -0500 (Wed, 27 Jul 2005) $
+ */
+public class GroupChannel extends ChannelInterceptorBase implements ManagedChannel {
+ /**
+ * Flag to determine if the channel manages its own heartbeat
+ * If set to true, the channel will start a local thread for the heart beat.
+ */
+ protected boolean heartbeat = true;
+ /**
+ * If <code>heartbeat == true</code> then how often do we want this
+ * heartbeat to run. default is one minute
+ */
+ protected long heartbeatSleeptime = 5*1000;//every 5 seconds
+
+ /**
+ * Internal heartbeat thread
+ */
+ protected HeartbeatThread hbthread = null;
+
+ /**
+ * The <code>ChannelCoordinator</code> coordinates the bottom layer components:<br>
+ * - MembershipService<br>
+ * - ChannelSender <br>
+ * - ChannelReceiver<br>
+ */
+ protected ChannelCoordinator coordinator = new ChannelCoordinator();
+
+ /**
+ * The first interceptor in the inteceptor stack.
+ * The interceptors are chained in a linked list, so we only need a reference to the
+ * first one
+ */
+ protected ChannelInterceptor interceptors = null;
+
+ /**
+ * A list of membership listeners that subscribe to membership announcements
+ */
+ protected ArrayList membershipListeners = new ArrayList();
+
+ /**
+ * A list of channel listeners that subscribe to incoming messages
+ */
+ protected ArrayList channelListeners = new ArrayList();
+
+ /**
+ * If set to true, the GroupChannel will check to make sure that
+ */
+ protected boolean optionCheck = false;
+
+ /**
+ * Creates a GroupChannel. This constructor will also
+ * add the first interceptor in the GroupChannel.<br>
+ * The first interceptor is always the channel itself.
+ */
+ public GroupChannel() {
+ addInterceptor(this);
+ }
+
+
+ /**
+ * Adds an interceptor to the stack for message processing<br>
+ * Interceptors are ordered in the way they are added.<br>
+ * <code>channel.addInterceptor(A);</code><br>
+ * <code>channel.addInterceptor(C);</code><br>
+ * <code>channel.addInterceptor(B);</code><br>
+ * Will result in a interceptor stack like this:<br>
+ * <code>A -> C -> B</code><br>
+ * The complete stack will look like this:<br>
+ * <code>Channel -> A -> C -> B -> ChannelCoordinator</code><br>
+ * @param interceptor ChannelInterceptorBase
+ */
+ public void addInterceptor(ChannelInterceptor interceptor) {
+ if ( interceptors == null ) {
+ interceptors = interceptor;
+ interceptors.setNext(coordinator);
+ interceptors.setPrevious(null);
+ coordinator.setPrevious(interceptors);
+ } else {
+ ChannelInterceptor last = interceptors;
+ while ( last.getNext() != coordinator ) {
+ last = last.getNext();
+ }
+ last.setNext(interceptor);
+ interceptor.setNext(coordinator);
+ interceptor.setPrevious(last);
+ coordinator.setPrevious(interceptor);
+ }
+ }
+
+ /**
+ * Sends a heartbeat through the interceptor stack.<br>
+ * Invoke this method from the application on a periodic basis if
+ * you have turned off internal heartbeats <code>channel.setHeartbeat(false)</code>
+ */
+ public void heartbeat() {
+ super.heartbeat();
+ Iterator i = membershipListeners.iterator();
+ while ( i.hasNext() ) {
+ Object o = i.next();
+ if ( o instanceof Heartbeat ) ((Heartbeat)o).heartbeat();
+ }
+ i = channelListeners.iterator();
+ while ( i.hasNext() ) {
+ Object o = i.next();
+ if ( o instanceof Heartbeat ) ((Heartbeat)o).heartbeat();
+ }
+
+ }
+
+
+ /**
+ * Send a message to the destinations specified
+ * @param destination Member[] - destination.length > 1
+ * @param msg Serializable - the message to send
+ * @param options int - sender options, options can trigger guarantee levels and different interceptors to
+ * react to the message see class documentation for the <code>Channel</code> object.<br>
+ * @return UniqueId - the unique Id that was assigned to this message
+ * @throws ChannelException - if an error occurs processing the message
+ * @see org.apache.catalina.tribes.Channel
+ */
+ public UniqueId send(Member[] destination, Serializable msg, int options) throws ChannelException {
+ return send(destination,msg,options,null);
+ }
+
+ /**
+ *
+ * @param destination Member[] - destination.length > 1
+ * @param msg Serializable - the message to send
+ * @param options int - sender options, options can trigger guarantee levels and different interceptors to
+ * react to the message see class documentation for the <code>Channel</code> object.<br>
+ * @param handler - callback object for error handling and completion notification, used when a message is
+ * sent asynchronously using the <code>Channel.SEND_OPTIONS_ASYNCHRONOUS</code> flag enabled.
+ * @return UniqueId - the unique Id that was assigned to this message
+ * @throws ChannelException - if an error occurs processing the message
+ * @see org.apache.catalina.tribes.Channel
+ */
+ public UniqueId send(Member[] destination, Serializable msg, int options, ErrorHandler handler) throws ChannelException {
+ if ( msg == null ) throw new ChannelException("Cant send a NULL message");
+ XByteBuffer buffer = null;
+ try {
+ if ( destination == null || destination.length == 0) throw new ChannelException("No destination given");
+ ChannelData data = new ChannelData(true);//generates a unique Id
+ data.setAddress(getLocalMember(false));
+ data.setTimestamp(System.currentTimeMillis());
+ byte[] b = null;
+ if ( msg instanceof ByteMessage ){
+ b = ((ByteMessage)msg).getMessage();
+ options = options | SEND_OPTIONS_BYTE_MESSAGE;
+ } else {
+ b = XByteBuffer.serialize(msg);
+ options = options & (~SEND_OPTIONS_BYTE_MESSAGE);
+ }
+ data.setOptions(options);
+ //XByteBuffer buffer = new XByteBuffer(b.length+128,false);
+ buffer = BufferPool.getBufferPool().getBuffer(b.length+128, false);
+ buffer.append(b,0,b.length);
+ data.setMessage(buffer);
+ InterceptorPayload payload = null;
+ if ( handler != null ) {
+ payload = new InterceptorPayload();
+ payload.setErrorHandler(handler);
+ }
+ getFirstInterceptor().sendMessage(destination, data, payload);
+ if ( Logs.MESSAGES.isTraceEnabled() ) {
+ Logs.MESSAGES.trace("GroupChannel - Sent msg:" + new UniqueId(data.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " to "+Arrays.toNameString(destination));
+ Logs.MESSAGES.trace("GroupChannel - Send Message:" + new UniqueId(data.getUniqueId()) + " is " +msg);
+ }
+
+ return new UniqueId(data.getUniqueId());
+ }catch ( Exception x ) {
+ if ( x instanceof ChannelException ) throw (ChannelException)x;
+ throw new ChannelException(x);
+ } finally {
+ if ( buffer != null ) BufferPool.getBufferPool().returnBuffer(buffer);
+ }
+ }
+
+
+ /**
+ * Callback from the interceptor stack. <br>
+ * When a message is received from a remote node, this method will be invoked by
+ * the previous interceptor.<br>
+ * This method can also be used to send a message to other components within the same application,
+ * but its an extreme case, and you're probably better off doing that logic between the applications itself.
+ * @param msg ChannelMessage
+ */
+ public void messageReceived(ChannelMessage msg) {
+ if ( msg == null ) return;
+ try {
+ if ( Logs.MESSAGES.isTraceEnabled() ) {
+ Logs.MESSAGES.trace("GroupChannel - Received msg:" + new UniqueId(msg.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " from "+msg.getAddress().getName());
+ }
+
+ Serializable fwd = null;
+ if ( (msg.getOptions() & SEND_OPTIONS_BYTE_MESSAGE) == SEND_OPTIONS_BYTE_MESSAGE ) {
+ fwd = new ByteMessage(msg.getMessage().getBytes());
+ } else {
+ fwd = XByteBuffer.deserialize(msg.getMessage().getBytesDirect(),0,msg.getMessage().getLength());
+ }
+ if ( Logs.MESSAGES.isTraceEnabled() ) {
+ Logs.MESSAGES.trace("GroupChannel - Receive Message:" + new UniqueId(msg.getUniqueId()) + " is " +fwd);
+ }
+
+ //get the actual member with the correct alive time
+ Member source = msg.getAddress();
+ boolean rx = false;
+ boolean delivered = false;
+ for ( int i=0; i<channelListeners.size(); i++ ) {
+ ChannelListener channelListener = (ChannelListener)channelListeners.get(i);
+ if (channelListener != null && channelListener.accept(fwd, source)) {
+ channelListener.messageReceived(fwd, source);
+ delivered = true;
+ //if the message was accepted by an RPC channel, that channel
+ //is responsible for returning the reply, otherwise we send an absence reply
+ if ( channelListener instanceof RpcChannel ) rx = true;
+ }
+ }//for
+ if ((!rx) && (fwd instanceof RpcMessage)) {
+ //if we have a message that requires a response,
+ //but none was given, send back an immediate one
+ sendNoRpcChannelReply((RpcMessage)fwd,source);
+ }
+ if ( Logs.MESSAGES.isTraceEnabled() ) {
+ Logs.MESSAGES.trace("GroupChannel delivered["+delivered+"] id:"+new UniqueId(msg.getUniqueId()));
+ }
+
+ } catch ( Exception x ) {
+ if ( log.isDebugEnabled() ) log.error("Unable to process channel:IOException.",x);
+ throw new RemoteProcessException("IOException:"+x.getMessage(),x);
+ }
+ }
+
+ /**
+ * Sends a <code>NoRpcChannelReply</code> message to a member<br>
+ * This method gets invoked by the channel if a RPC message comes in
+ * and no channel listener accepts the message. This avoids timeout
+ * @param msg RpcMessage
+ * @param destination Member - the destination for the reply
+ */
+ protected void sendNoRpcChannelReply(RpcMessage msg, Member destination) {
+ try {
+ //avoid circular loop
+ if ( msg instanceof RpcMessage.NoRpcChannelReply) return;
+ RpcMessage.NoRpcChannelReply reply = new RpcMessage.NoRpcChannelReply(msg.rpcId,msg.uuid);
+ send(new Member[]{destination},reply,Channel.SEND_OPTIONS_ASYNCHRONOUS);
+ } catch ( Exception x ) {
+ log.error("Unable to find rpc channel, failed to send NoRpcChannelReply.",x);
+ }
+ }
+
+ /**
+ * memberAdded gets invoked by the interceptor below the channel
+ * and the channel will broadcast it to the membership listeners
+ * @param member Member - the new member
+ */
+ public void memberAdded(Member member) {
+ //notify upwards
+ for (int i=0; i<membershipListeners.size(); i++ ) {
+ MembershipListener membershipListener = (MembershipListener)membershipListeners.get(i);
+ if (membershipListener != null) membershipListener.memberAdded(member);
+ }
+ }
+
+ /**
+ * memberDisappeared gets invoked by the interceptor below the channel
+ * and the channel will broadcast it to the membership listeners
+ * @param member Member - the member that left or crashed
+ */
+ public void memberDisappeared(Member member) {
+ //notify upwards
+ for (int i=0; i<membershipListeners.size(); i++ ) {
+ MembershipListener membershipListener = (MembershipListener)membershipListeners.get(i);
+ if (membershipListener != null) membershipListener.memberDisappeared(member);
+ }
+ }
+
+ /**
+ * Sets up the default implementation interceptor stack
+ * if no interceptors have been added
+ * @throws ChannelException
+ */
+ protected synchronized void setupDefaultStack() throws ChannelException {
+
+ if ( getFirstInterceptor() != null &&
+ ((getFirstInterceptor().getNext() instanceof ChannelCoordinator))) {
+ ChannelInterceptor interceptor = null;
+ Class clazz = null;
+ try {
+ clazz = Class.forName("org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor",
+ true,GroupChannel.class.getClassLoader());
+ clazz.newInstance();
+ } catch ( Throwable x ) {
+ clazz = MessageDispatchInterceptor.class;
+ }//catch
+ try {
+ interceptor = (ChannelInterceptor) clazz.newInstance();
+ } catch (Exception x) {
+ throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x);
+ }
+ this.addInterceptor(interceptor);
+ }
+ }
+
+ /**
+ * Validates the option flags that each interceptor is using and reports
+ * an error if two interceptor share the same flag.
+ * @throws ChannelException
+ */
+ protected void checkOptionFlags() throws ChannelException {
+ StringBuffer conflicts = new StringBuffer();
+ ChannelInterceptor first = interceptors;
+ while ( first != null ) {
+ int flag = first.getOptionFlag();
+ if ( flag != 0 ) {
+ ChannelInterceptor next = first.getNext();
+ while ( next != null ) {
+ int nflag = next.getOptionFlag();
+ if (nflag!=0 && (((flag & nflag) == flag ) || ((flag & nflag) == nflag)) ) {
+ conflicts.append("[");
+ conflicts.append(first.getClass().getName());
+ conflicts.append(":");
+ conflicts.append(flag);
+ conflicts.append(" == ");
+ conflicts.append(next.getClass().getName());
+ conflicts.append(":");
+ conflicts.append(nflag);
+ conflicts.append("] ");
+ }//end if
+ next = next.getNext();
+ }//while
+ }//end if
+ first = first.getNext();
+ }//while
+ if ( conflicts.length() > 0 ) throw new ChannelException("Interceptor option flag conflict: "+conflicts.toString());
+
+ }
+
+ /**
+ * Starts the channel
+ * @param svc int - what service to start
+ * @throws ChannelException
+ * @see org.apache.catalina.tribes.Channel#start(int)
+ */
+ public synchronized void start(int svc) throws ChannelException {
+ setupDefaultStack();
+ if (optionCheck) checkOptionFlags();
+ super.start(svc);
+ if ( hbthread == null && heartbeat ) {
+ hbthread = new HeartbeatThread(this,heartbeatSleeptime);
+ hbthread.start();
+ }
+ }
+
+ /**
+ * Stops the channel
+ * @param svc int
+ * @throws ChannelException
+ * @see org.apache.catalina.tribes.Channel#stop(int)
+ */
+ public synchronized void stop(int svc) throws ChannelException {
+ if (hbthread != null) {
+ hbthread.stopHeartbeat();
+ hbthread = null;
+ }
+ super.stop(svc);
+ }
+
+ /**
+ * Returns the first interceptor of the stack. Useful for traversal.
+ * @return ChannelInterceptor
+ */
+ public ChannelInterceptor getFirstInterceptor() {
+ if (interceptors != null) return interceptors;
+ else return coordinator;
+ }
+
+ /**
+ * Returns the channel receiver component
+ * @return ChannelReceiver
+ */
+ public ChannelReceiver getChannelReceiver() {
+ return coordinator.getClusterReceiver();
+ }
+
+ /**
+ * Returns the channel sender component
+ * @return ChannelSender
+ */
+ public ChannelSender getChannelSender() {
+ return coordinator.getClusterSender();
+ }
+
+ /**
+ * Returns the membership service component
+ * @return MembershipService
+ */
+ public MembershipService getMembershipService() {
+ return coordinator.getMembershipService();
+ }
+
+ /**
+ * Sets the channel receiver component
+ * @param clusterReceiver ChannelReceiver
+ */
+ public void setChannelReceiver(ChannelReceiver clusterReceiver) {
+ coordinator.setClusterReceiver(clusterReceiver);
+ }
+
+ /**
+ * Sets the channel sender component
+ * @param clusterSender ChannelSender
+ */
+ public void setChannelSender(ChannelSender clusterSender) {
+ coordinator.setClusterSender(clusterSender);
+ }
+
+ /**
+ * Sets the membership component
+ * @param membershipService MembershipService
+ */
+ public void setMembershipService(MembershipService membershipService) {
+ coordinator.setMembershipService(membershipService);
+ }
+
+ /**
+ * Adds a membership listener to the channel.<br>
+ * Membership listeners are uniquely identified using the equals(Object) method
+ * @param membershipListener MembershipListener
+ */
+ public void addMembershipListener(MembershipListener membershipListener) {
+ if (!this.membershipListeners.contains(membershipListener) )
+ this.membershipListeners.add(membershipListener);
+ }
+
+ /**
+ * Removes a membership listener from the channel.<br>
+ * Membership listeners are uniquely identified using the equals(Object) method
+ * @param membershipListener MembershipListener
+ */
+
+ public void removeMembershipListener(MembershipListener membershipListener) {
+ membershipListeners.remove(membershipListener);
+ }
+
+ /**
+ * Adds a channel listener to the channel.<br>
+ * Channel listeners are uniquely identified using the equals(Object) method
+ * @param channelListener ChannelListener
+ */
+ public void addChannelListener(ChannelListener channelListener) {
+ if (!this.channelListeners.contains(channelListener) ) {
+ this.channelListeners.add(channelListener);
+ } else {
+ throw new IllegalArgumentException("Listener already exists:"+channelListener);
+ }
+ }
+
+ /**
+ *
+ * Removes a channel listener from the channel.<br>
+ * Channel listeners are uniquely identified using the equals(Object) method
+ * @param channelListener ChannelListener
+ */
+ public void removeChannelListener(ChannelListener channelListener) {
+ channelListeners.remove(channelListener);
+ }
+
+ /**
+ * Returns an iterator of all the interceptors in this stack
+ * @return Iterator
+ */
+ public Iterator getInterceptors() {
+ return new InterceptorIterator(this.getNext(),this.coordinator);
+ }
+
+ /**
+ * Enables/disables the option check<br>
+ * Setting this to true, will make the GroupChannel perform a conflict check
+ * on the interceptors. If two interceptors are using the same option flag
+ * and throw an error upon start.
+ * @param optionCheck boolean
+ */
+ public void setOptionCheck(boolean optionCheck) {
+ this.optionCheck = optionCheck;
+ }
+
+ /**
+ * Configure local heartbeat sleep time<br>
+ * Only used when <code>getHeartbeat()==true</code>
+ * @param heartbeatSleeptime long - time in milliseconds to sleep between heartbeats
+ */
+ public void setHeartbeatSleeptime(long heartbeatSleeptime) {
+ this.heartbeatSleeptime = heartbeatSleeptime;
+ }
+
+ /**
+ * Enables or disables local heartbeat.
+ * if <code>setHeartbeat(true)</code> is invoked then the channel will start an internal
+ * thread to invoke <code>Channel.heartbeat()</code> every <code>getHeartbeatSleeptime</code> milliseconds
+ * @param heartbeat boolean
+ */
+ public void setHeartbeat(boolean heartbeat) {
+ this.heartbeat = heartbeat;
+ }
+
+ /**
+ * @see #setOptionCheck(boolean)
+ * @return boolean
+ */
+ public boolean getOptionCheck() {
+ return optionCheck;
+ }
+
+ /**
+ * @see #setHeartbeat(boolean)
+ * @return boolean
+ */
+ public boolean getHeartbeat() {
+ return heartbeat;
+ }
+
+ /**
+ * Returns the sleep time in milliseconds that the internal heartbeat will
+ * sleep in between invokations of <code>Channel.heartbeat()</code>
+ * @return long
+ */
+ public long getHeartbeatSleeptime() {
+ return heartbeatSleeptime;
+ }
+
+ /**
+ *
+ * <p>Title: Interceptor Iterator</p>
+ *
+ * <p>Description: An iterator to loop through the interceptors in a channel</p>
+ *
+ * @version 1.0
+ */
+ public static class InterceptorIterator implements Iterator {
+ private ChannelInterceptor end;
+ private ChannelInterceptor start;
+ public InterceptorIterator(ChannelInterceptor start, ChannelInterceptor end) {
+ this.end = end;
+ this.start = start;
+ }
+
+ public boolean hasNext() {
+ return start!=null && start != end;
+ }
+
+ public Object next() {
+ Object result = null;
+ if ( hasNext() ) {
+ result = start;
+ start = start.getNext();
+ }
+ return result;
+ }
+
+ public void remove() {
+ //empty operation
+ }
+ }
+
+ /**
+ *
+ * <p>Title: Internal heartbeat thread</p>
+ *
+ * <p>Description: if <code>Channel.getHeartbeat()==true</code> then a thread of this class
+ * is created</p>
+ *
+ * @version 1.0
+ */
+ public static class HeartbeatThread extends Thread {
+ protected static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(HeartbeatThread.class);
+ protected static int counter = 1;
+ protected static synchronized int inc() {
+ return counter++;
+ }
+
+ protected boolean doRun = true;
+ protected GroupChannel channel;
+ protected long sleepTime;
+ public HeartbeatThread(GroupChannel channel, long sleepTime) {
+ super();
+ this.setPriority(MIN_PRIORITY);
+ setName("GroupChannel-Heartbeat-"+inc());
+ setDaemon(true);
+ this.channel = channel;
+ this.sleepTime = sleepTime;
+ }
+ public void stopHeartbeat() {
+ doRun = false;
+ interrupt();
+ }
+
+ public void run() {
+ while (doRun) {
+ try {
+ Thread.sleep(sleepTime);
+ channel.heartbeat();
+ } catch ( InterruptedException x ) {
+ interrupted();
+ } catch ( Exception x ) {
+ log.error("Unable to send heartbeat through Tribes interceptor stack. Will try to sleep again.",x);
+ }//catch
+ }//while
+ }//run
+ }//HeartbeatThread
+
+
+
+}
Added: tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/InterceptorPayload.java
URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/InterceptorPayload.java?rev=433703&view=auto
==============================================================================
--- tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/InterceptorPayload.java (added)
+++ tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/InterceptorPayload.java Tue Aug 22 10:28:09 2006
@@ -0,0 +1,34 @@
+/*
+ * Copyright 1999,2004-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.catalina.tribes.group;
+
+import org.apache.catalina.tribes.ErrorHandler;
+
+/**
+ * @author Filip Hanik
+ * @version 1.0
+ */
+public class InterceptorPayload {
+ private ErrorHandler errorHandler;
+
+ public ErrorHandler getErrorHandler() {
+ return errorHandler;
+ }
+
+ public void setErrorHandler(ErrorHandler errorHandler) {
+ this.errorHandler = errorHandler;
+ }
+}
\ No newline at end of file
Added: tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/Response.java
URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/Response.java?rev=433703&view=auto
==============================================================================
--- tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/Response.java (added)
+++ tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/Response.java Tue Aug 22 10:28:09 2006
@@ -0,0 +1,53 @@
+/*
+ * Copyright 1999,2004-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.catalina.tribes.group;
+
+import java.io.Serializable;
+
+import org.apache.catalina.tribes.Member;
+
+/**
+ * A response object holds a message from a responding partner.
+ * @author Filip Hanik
+ * @version 1.0
+ */
+public class Response {
+ private Member source;
+ private Serializable message;
+ public Response() {
+ }
+
+ public Response(Member source, Serializable message) {
+ this.source = source;
+ this.message = message;
+ }
+
+ public void setSource(Member source) {
+ this.source = source;
+ }
+
+ public void setMessage(Serializable message) {
+ this.message = message;
+ }
+
+ public Member getSource() {
+ return source;
+ }
+
+ public Serializable getMessage() {
+ return message;
+ }
+}
\ No newline at end of file
Added: tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/RpcCallback.java
URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/RpcCallback.java?rev=433703&view=auto
==============================================================================
--- tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/RpcCallback.java (added)
+++ tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/RpcCallback.java Tue Aug 22 10:28:09 2006
@@ -0,0 +1,45 @@
+/*
+ * Copyright 1999,2004-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.catalina.tribes.group;
+
+import java.io.Serializable;
+
+import org.apache.catalina.tribes.Member;
+
+/**
+ * The RpcCallback interface is an interface for the Tribes channel to request a
+ * response object to a request that came in.
+ * @author not attributable
+ * @version 1.0
+ */
+public interface RpcCallback {
+
+ /**
+ *
+ * @param msg Serializable
+ * @return Serializable - null if no reply should be sent
+ */
+ public Serializable replyRequest(Serializable msg, Member sender);
+
+ /**
+ * If the reply has already been sent to the requesting thread,
+ * the rpc callback can handle any data that comes in after the fact.
+ * @param msg Serializable
+ * @param sender Member
+ */
+ public void leftOver(Serializable msg, Member sender);
+
+}
\ No newline at end of file
Added: tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/RpcChannel.java
URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/RpcChannel.java?rev=433703&view=auto
==============================================================================
--- tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/RpcChannel.java (added)
+++ tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/RpcChannel.java Tue Aug 22 10:28:09 2006
@@ -0,0 +1,261 @@
+/*
+ * Copyright 1999,2004-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.catalina.tribes.group;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+
+import org.apache.catalina.tribes.Channel;
+import org.apache.catalina.tribes.ChannelException;
+import org.apache.catalina.tribes.ChannelListener;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.util.UUIDGenerator;
+
+/**
+ * A channel to handle RPC messaging
+ * @author Filip Hanik
+ */
+public class RpcChannel implements ChannelListener{
+ protected static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(RpcChannel.class);
+
+ public static final int FIRST_REPLY = 1;
+ public static final int MAJORITY_REPLY = 2;
+ public static final int ALL_REPLY = 3;
+ public static final int NO_REPLY = 4;
+
+ private Channel channel;
+ private RpcCallback callback;
+ private byte[] rpcId;
+
+ private HashMap responseMap = new HashMap();
+
+ /**
+ * Create an RPC channel. You can have several RPC channels attached to a group
+ * all separated out by the uniqueness
+ * @param rpcId - the unique Id for this RPC group
+ * @param channel Channel
+ * @param callback RpcCallback
+ */
+ public RpcChannel(byte[] rpcId, Channel channel, RpcCallback callback) {
+ this.channel = channel;
+ this.callback = callback;
+ this.rpcId = rpcId;
+ channel.addChannelListener(this);
+ }
+
+
+ /**
+ * Send a message and wait for the response.
+ * @param destination Member[] - the destination for the message, and the members you request a reply from
+ * @param message Serializable - the message you are sending out
+ * @param options int - FIRST_REPLY, MAJORITY_REPLY or ALL_REPLY
+ * @param timeout long - timeout in milliseconds, if no reply is received within this time null is returned
+ * @return Response[] - an array of response objects.
+ * @throws ChannelException
+ */
+ public Response[] send(Member[] destination,
+ Serializable message,
+ int rpcOptions,
+ int channelOptions,
+ long timeout) throws ChannelException {
+
+ if ( destination==null || destination.length == 0 ) return new Response[0];
+
+ //avoid dead lock
+ channelOptions = channelOptions & ~Channel.SEND_OPTIONS_SYNCHRONIZED_ACK;
+
+ RpcCollectorKey key = new RpcCollectorKey(UUIDGenerator.randomUUID(false));
+ RpcCollector collector = new RpcCollector(key,rpcOptions,destination.length,timeout);
+ try {
+ synchronized (collector) {
+ if ( rpcOptions != NO_REPLY ) responseMap.put(key, collector);
+ RpcMessage rmsg = new RpcMessage(rpcId, key.id, message);
+ channel.send(destination, rmsg, channelOptions);
+ if ( rpcOptions != NO_REPLY ) collector.wait(timeout);
+ }
+ } catch ( InterruptedException ix ) {
+ Thread.currentThread().interrupted();
+ //throw new ChannelException(ix);
+ }finally {
+ responseMap.remove(key);
+ }
+ return collector.getResponses();
+ }
+
+ public void messageReceived(Serializable msg, Member sender) {
+ RpcMessage rmsg = (RpcMessage)msg;
+ RpcCollectorKey key = new RpcCollectorKey(rmsg.uuid);
+ if ( rmsg.reply ) {
+ RpcCollector collector = (RpcCollector)responseMap.get(key);
+ if (collector == null) {
+ callback.leftOver(rmsg.message, sender);
+ } else {
+ synchronized (collector) {
+ //make sure it hasn't been removed
+ if ( responseMap.containsKey(key) ) {
+ if ( (rmsg instanceof RpcMessage.NoRpcChannelReply) )
+ collector.destcnt--;
+ else
+ collector.addResponse(rmsg.message, sender);
+ if (collector.isComplete()) collector.notifyAll();
+ } else {
+ if (! (rmsg instanceof RpcMessage.NoRpcChannelReply) )
+ callback.leftOver(rmsg.message, sender);
+ }
+ }//synchronized
+ }//end if
+ } else{
+ Serializable reply = callback.replyRequest(rmsg.message,sender);
+ rmsg.reply = true;
+ rmsg.message = reply;
+ try {
+ channel.send(new Member[] {sender}, rmsg,0);
+ }catch ( Exception x ) {
+ log.error("Unable to send back reply in RpcChannel.",x);
+ }
+ }//end if
+ }
+
+ public void breakdown() {
+ channel.removeChannelListener(this);
+ }
+
+ public void finalize() {
+ breakdown();
+ }
+
+ public boolean accept(Serializable msg, Member sender) {
+ if ( msg instanceof RpcMessage ) {
+ RpcMessage rmsg = (RpcMessage)msg;
+ return Arrays.equals(rmsg.rpcId,rpcId);
+ }else return false;
+ }
+
+ public Channel getChannel() {
+ return channel;
+ }
+
+ public RpcCallback getCallback() {
+ return callback;
+ }
+
+ public byte[] getRpcId() {
+ return rpcId;
+ }
+
+ public void setChannel(Channel channel) {
+ this.channel = channel;
+ }
+
+ public void setCallback(RpcCallback callback) {
+ this.callback = callback;
+ }
+
+ public void setRpcId(byte[] rpcId) {
+ this.rpcId = rpcId;
+ }
+
+
+
+ /**
+ *
+ * Class that holds all response.
+ * @author not attributable
+ * @version 1.0
+ */
+ public static class RpcCollector {
+ public ArrayList responses = new ArrayList();
+ public RpcCollectorKey key;
+ public int options;
+ public int destcnt;
+ public long timeout;
+
+ public RpcCollector(RpcCollectorKey key, int options, int destcnt, long timeout) {
+ this.key = key;
+ this.options = options;
+ this.destcnt = destcnt;
+ this.timeout = timeout;
+ }
+
+ public void addResponse(Serializable message, Member sender){
+ Response resp = new Response(sender,message);
+ responses.add(resp);
+ }
+
+ public boolean isComplete() {
+ if ( destcnt <= 0 ) return true;
+ switch (options) {
+ case ALL_REPLY:
+ return destcnt == responses.size();
+ case MAJORITY_REPLY:
+ {
+ float perc = ((float)responses.size()) / ((float)destcnt);
+ return perc >= 0.50f;
+ }
+ case FIRST_REPLY:
+ return responses.size()>0;
+ default:
+ return false;
+ }
+ }
+
+ public int hashCode() {
+ return key.hashCode();
+ }
+
+ public boolean equals(Object o) {
+ if ( o instanceof RpcCollector ) {
+ RpcCollector r = (RpcCollector)o;
+ return r.key.equals(this.key);
+ } else return false;
+ }
+
+ public Response[] getResponses() {
+ return (Response[])responses.toArray(new Response[responses.size()]);
+ }
+ }
+
+ public static class RpcCollectorKey {
+ byte[] id;
+ public RpcCollectorKey(byte[] id) {
+ this.id = id;
+ }
+
+ public int hashCode() {
+ return id[0]+id[1]+id[2]+id[3];
+ }
+
+ public boolean equals(Object o) {
+ if ( o instanceof RpcCollectorKey ) {
+ RpcCollectorKey r = (RpcCollectorKey)o;
+ return Arrays.equals(id,r.id);
+ } else return false;
+ }
+
+ }
+
+ protected static String bToS(byte[] data) {
+ StringBuffer buf = new StringBuffer(4*16);
+ buf.append("{");
+ for (int i=0; data!=null && i<data.length; i++ ) buf.append(String.valueOf(data[i])).append(" ");
+ buf.append("}");
+ return buf.toString();
+ }
+
+
+}
\ No newline at end of file
Added: tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/RpcMessage.java
URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/RpcMessage.java?rev=433703&view=auto
==============================================================================
--- tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/RpcMessage.java (added)
+++ tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/RpcMessage.java Tue Aug 22 10:28:09 2006
@@ -0,0 +1,103 @@
+/*
+ * Copyright 1999,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.catalina.tribes.group;
+
+import java.io.ObjectInput;
+import java.io.Serializable;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectOutput;
+
+/**
+ * <p>Title: </p>
+ *
+ * <p>Description: </p>
+ *
+ * <p>Copyright: Copyright (c) 2005</p>
+ *
+ * <p>Company: </p>
+ *
+ * @author not attributable
+ * @version 1.0
+ */
+public class RpcMessage implements Externalizable {
+
+ protected Serializable message;
+ protected byte[] uuid;
+ protected byte[] rpcId;
+ protected boolean reply = false;
+
+ public RpcMessage() {
+ //for serialization
+ }
+
+ public RpcMessage(byte[] rpcId, byte[] uuid, Serializable message) {
+ this.rpcId = rpcId;
+ this.uuid = uuid;
+ this.message = message;
+ }
+
+ public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
+ reply = in.readBoolean();
+ int length = in.readInt();
+ uuid = new byte[length];
+ in.read(uuid, 0, length);
+ length = in.readInt();
+ rpcId = new byte[length];
+ in.read(rpcId, 0, length);
+ message = (Serializable)in.readObject();
+ }
+
+ public void writeExternal(ObjectOutput out) throws IOException {
+ out.writeBoolean(reply);
+ out.writeInt(uuid.length);
+ out.write(uuid, 0, uuid.length);
+ out.writeInt(rpcId.length);
+ out.write(rpcId, 0, rpcId.length);
+ out.writeObject(message);
+ }
+
+ public static class NoRpcChannelReply extends RpcMessage {
+ public NoRpcChannelReply() {
+
+ }
+
+ public NoRpcChannelReply(byte[] rpcid, byte[] uuid) {
+ super(rpcid,uuid,null);
+ reply = true;
+ }
+
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ reply = true;
+ int length = in.readInt();
+ uuid = new byte[length];
+ in.read(uuid, 0, length);
+ length = in.readInt();
+ rpcId = new byte[length];
+ in.read(rpcId, 0, length);
+ }
+
+ public void writeExternal(ObjectOutput out) throws IOException {
+ out.writeInt(uuid.length);
+ out.write(uuid, 0, uuid.length);
+ out.writeInt(rpcId.length);
+ out.write(rpcId, 0, rpcId.length);
+ }
+ }
+
+
+}
Added: tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/DomainFilterInterceptor.java
URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/DomainFilterInterceptor.java?rev=433703&view=auto
==============================================================================
--- tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/DomainFilterInterceptor.java (added)
+++ tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/DomainFilterInterceptor.java Tue Aug 22 10:28:09 2006
@@ -0,0 +1,101 @@
+/*
+ * Copyright 1999,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
+ */
+package org.apache.catalina.tribes.group.interceptors;
+
+import org.apache.catalina.tribes.ChannelMessage;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.group.ChannelInterceptorBase;
+import org.apache.catalina.tribes.membership.MemberImpl;
+import org.apache.catalina.tribes.membership.Membership;
+import java.util.Arrays;
+
+/**
+ * <p>Title: Member domain filter interceptor </p>
+ *
+ * <p>Description: Filters membership based on domain.
+ * </p>
+ *
+ * @author Filip Hanik
+ * @version 1.0
+ */
+public class DomainFilterInterceptor extends ChannelInterceptorBase {
+
+ private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog( DomainFilterInterceptor.class );
+
+ protected Membership membership = null;
+
+ protected byte[] domain = new byte[0];
+
+ public void messageReceived(ChannelMessage msg) {
+ //should we filter incoming based on domain?
+ super.messageReceived(msg);
+ }//messageReceived
+
+
+ public void memberAdded(Member member) {
+ if ( membership == null ) setupMembership();
+ boolean notify = false;
+ synchronized (membership) {
+ notify = Arrays.equals(domain,member.getDomain());
+ if ( notify ) notify = membership.memberAlive((MemberImpl)member);
+ }
+ if ( notify ) super.memberAdded(member);
+ }
+
+ public void memberDisappeared(Member member) {
+ if ( membership == null ) setupMembership();
+ boolean notify = false;
+ synchronized (membership) {
+ notify = Arrays.equals(domain,member.getDomain());
+ membership.removeMember((MemberImpl)member);
+ }
+ if ( notify ) super.memberDisappeared(member);
+ }
+
+ public boolean hasMembers() {
+ if ( membership == null ) setupMembership();
+ return membership.hasMembers();
+ }
+
+ public Member[] getMembers() {
+ if ( membership == null ) setupMembership();
+ return membership.getMembers();
+ }
+
+ public Member getMember(Member mbr) {
+ if ( membership == null ) setupMembership();
+ return membership.getMember(mbr);
+ }
+
+ public Member getLocalMember(boolean incAlive) {
+ return super.getLocalMember(incAlive);
+ }
+
+
+ protected synchronized void setupMembership() {
+ if ( membership == null ) {
+ membership = new Membership((MemberImpl)super.getLocalMember(true));
+ }
+
+ }
+
+ public byte[] getDomain() {
+ return domain;
+ }
+
+ public void setDomain(byte[] domain) {
+ this.domain = domain;
+ }
+}
Added: tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java
URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java?rev=433703&view=auto
==============================================================================
--- tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java (added)
+++ tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/FragmentationInterceptor.java Tue Aug 22 10:28:09 2006
@@ -0,0 +1,241 @@
+/*
+ * Copyright 1999,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
+ */
+
+package org.apache.catalina.tribes.group.interceptors;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Set;
+
+import org.apache.catalina.tribes.ChannelException;
+import org.apache.catalina.tribes.ChannelMessage;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.group.ChannelInterceptorBase;
+import org.apache.catalina.tribes.group.InterceptorPayload;
+import org.apache.catalina.tribes.io.XByteBuffer;
+
+/**
+ *
+ * The fragmentation interceptor splits up large messages into smaller messages and assembles them on the other end.
+ * This is very useful when you don't want large messages hogging the sending sockets
+ * and smaller messages can make it through.
+ *
+ * <br><b>Configuration Options</b><br>
+ * OrderInteceptor.expire=<milliseconds> - how long do we keep the fragments in memory and wait for the rest to arrive<b>default=60,000ms -> 60seconds</b>
+ * This setting is useful to avoid OutOfMemoryErrors<br>
+ * OrderInteceptor.maxSize=<max message size> - message size in bytes <b>default=1024*100 (around a tenth of a MB)</b><br>
+ * @author Filip Hanik
+ * @version 1.0
+ */
+public class FragmentationInterceptor extends ChannelInterceptorBase {
+ private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog( FragmentationInterceptor.class );
+
+ protected HashMap fragpieces = new HashMap();
+ private int maxSize = 1024*100;
+ private long expire = 1000 * 60; //one minute expiration
+ protected boolean deepclone = true;
+
+
+ public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException {
+ int size = msg.getMessage().getLength();
+ boolean frag = (size>maxSize) && okToProcess(msg.getOptions());
+ if ( frag ) {
+ frag(destination, msg, payload);
+ } else {
+ msg.getMessage().append(frag);
+ super.sendMessage(destination, msg, payload);
+ }
+ }
+
+ public void messageReceived(ChannelMessage msg) {
+ boolean isFrag = XByteBuffer.toBoolean(msg.getMessage().getBytesDirect(),msg.getMessage().getLength()-1);
+ msg.getMessage().trim(1);
+ if ( isFrag ) {
+ defrag(msg);
+ } else {
+ super.messageReceived(msg);
+ }
+ }
+
+
+ public FragCollection getFragCollection(FragKey key, ChannelMessage msg) {
+ FragCollection coll = (FragCollection)fragpieces.get(key);
+ if ( coll == null ) {
+ synchronized (fragpieces) {
+ coll = (FragCollection)fragpieces.get(key);
+ if ( coll == null ) {
+ coll = new FragCollection(msg);
+ fragpieces.put(key, coll);
+ }
+ }
+ }
+ return coll;
+ }
+
+ public void removeFragCollection(FragKey key) {
+ fragpieces.remove(key);
+ }
+
+ public void defrag(ChannelMessage msg ) {
+ FragKey key = new FragKey(msg.getUniqueId());
+ FragCollection coll = getFragCollection(key,msg);
+ coll.addMessage((ChannelMessage)msg.deepclone());
+
+ if ( coll.complete() ) {
+ removeFragCollection(key);
+ ChannelMessage complete = coll.assemble();
+ super.messageReceived(complete);
+
+ }
+ }
+
+ public void frag(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException {
+ int size = msg.getMessage().getLength();
+
+ int count = ((size / maxSize )+(size%maxSize==0?0:1));
+ ChannelMessage[] messages = new ChannelMessage[count];
+ int remaining = size;
+ for ( int i=0; i<count; i++ ) {
+ ChannelMessage tmp = (ChannelMessage)msg.clone();
+ int offset = (i*maxSize);
+ int length = Math.min(remaining,maxSize);
+ tmp.getMessage().clear();
+ tmp.getMessage().append(msg.getMessage().getBytesDirect(),offset,length);
+ //add the msg nr
+ //tmp.getMessage().append(XByteBuffer.toBytes(i),0,4);
+ tmp.getMessage().append(i);
+ //add the total nr of messages
+ //tmp.getMessage().append(XByteBuffer.toBytes(count),0,4);
+ tmp.getMessage().append(count);
+ //add true as the frag flag
+ //byte[] flag = XByteBuffer.toBytes(true);
+ //tmp.getMessage().append(flag,0,flag.length);
+ tmp.getMessage().append(true);
+ messages[i] = tmp;
+ remaining -= length;
+
+ }
+ for ( int i=0; i<messages.length; i++ ) {
+ super.sendMessage(destination,messages[i],payload);
+ }
+ }
+
+ public void heartbeat() {
+ try {
+ Set set = fragpieces.keySet();
+ Object[] keys = set.toArray();
+ for ( int i=0; i<keys.length; i++ ) {
+ FragKey key = (FragKey)keys[i];
+ if ( key != null && key.expired(getExpire()) )
+ removeFragCollection(key);
+ }
+ }catch ( Exception x ) {
+ if ( log.isErrorEnabled() ) {
+ log.error("Unable to perform heartbeat clean up in the frag interceptor",x);
+ }
+ }
+ super.heartbeat();
+ }
+
+
+
+ public int getMaxSize() {
+ return maxSize;
+ }
+
+ public long getExpire() {
+ return expire;
+ }
+
+ public void setMaxSize(int maxSize) {
+ this.maxSize = maxSize;
+ }
+
+ public void setExpire(long expire) {
+ this.expire = expire;
+ }
+
+ public static class FragCollection {
+ private long received = System.currentTimeMillis();
+ private ChannelMessage msg;
+ private XByteBuffer[] frags;
+ public FragCollection(ChannelMessage msg) {
+ //get the total messages
+ int count = XByteBuffer.toInt(msg.getMessage().getBytesDirect(),msg.getMessage().getLength()-4);
+ frags = new XByteBuffer[count];
+ this.msg = msg;
+ }
+
+ public void addMessage(ChannelMessage msg) {
+ //remove the total messages
+ msg.getMessage().trim(4);
+ //get the msg nr
+ int nr = XByteBuffer.toInt(msg.getMessage().getBytesDirect(),msg.getMessage().getLength()-4);
+ //remove the msg nr
+ msg.getMessage().trim(4);
+ frags[nr] = msg.getMessage();
+
+ }
+
+ public boolean complete() {
+ boolean result = true;
+ for ( int i=0; (i<frags.length) && (result); i++ ) result = (frags[i] != null);
+ return result;
+ }
+
+ public ChannelMessage assemble() {
+ if ( !complete() ) throw new IllegalStateException("Fragments are missing.");
+ int buffersize = 0;
+ for (int i=0; i<frags.length; i++ ) buffersize += frags[i].getLength();
+ XByteBuffer buf = new XByteBuffer(buffersize,false);
+ msg.setMessage(buf);
+ for ( int i=0; i<frags.length; i++ ) {
+ msg.getMessage().append(frags[i].getBytesDirect(),0,frags[i].getLength());
+ }
+ return msg;
+ }
+
+ public boolean expired(long expire) {
+ return (System.currentTimeMillis()-received)>expire;
+ }
+
+
+
+ }
+
+ public static class FragKey {
+ private byte[] uniqueId;
+ private long received = System.currentTimeMillis();
+ public FragKey(byte[] id ) {
+ this.uniqueId = id;
+ }
+ public int hashCode() {
+ return XByteBuffer.toInt(uniqueId,0);
+ }
+
+ public boolean equals(Object o ) {
+ if ( o instanceof FragKey ) {
+ return Arrays.equals(uniqueId,((FragKey)o).uniqueId);
+ } else return false;
+
+ }
+
+ public boolean expired(long expire) {
+ return (System.currentTimeMillis()-received)>expire;
+ }
+
+ }
+
+}
\ No newline at end of file
Added: tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java
URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java?rev=433703&view=auto
==============================================================================
--- tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java (added)
+++ tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/GzipInterceptor.java Tue Aug 22 10:28:09 2006
@@ -0,0 +1,99 @@
+/*
+ * Copyright 1999,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
+ */
+
+package org.apache.catalina.tribes.group.interceptors;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
+import org.apache.catalina.tribes.ChannelException;
+import org.apache.catalina.tribes.ChannelMessage;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.group.ChannelInterceptorBase;
+import org.apache.catalina.tribes.group.InterceptorPayload;
+
+
+
+/**
+ *
+ *
+ * @author Filip Hanik
+ * @version 1.0
+ */
+public class GzipInterceptor extends ChannelInterceptorBase {
+ public static final int DEFAULT_BUFFER_SIZE = 2048;
+
+ public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException {
+ try {
+ byte[] data = compress(msg.getMessage().getBytes());
+ msg.getMessage().trim(msg.getMessage().getLength());
+ msg.getMessage().append(data,0,data.length);
+ getNext().sendMessage(destination, msg, payload);
+ } catch ( IOException x ) {
+ log.error("Unable to compress byte contents");
+ throw new ChannelException(x);
+ }
+ }
+
+ public void messageReceived(ChannelMessage msg) {
+ try {
+ byte[] data = decompress(msg.getMessage().getBytes());
+ msg.getMessage().trim(msg.getMessage().getLength());
+ msg.getMessage().append(data,0,data.length);
+ getPrevious().messageReceived(msg);
+ } catch ( IOException x ) {
+ log.error("Unable to decompress byte contents",x);
+ }
+ }
+
+ public static byte[] compress(byte[] data) throws IOException {
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ GZIPOutputStream gout = new GZIPOutputStream(bout);
+ gout.write(data);
+ gout.flush();
+ gout.close();
+ return bout.toByteArray();
+ }
+
+ /**
+ * @todo Fix to create an automatically growing buffer.
+ * @param data byte[]
+ * @return byte[]
+ * @throws IOException
+ */
+ public static byte[] decompress(byte[] data) throws IOException {
+ ByteArrayInputStream bin = new ByteArrayInputStream(data);
+ GZIPInputStream gin = new GZIPInputStream(bin);
+ byte[] tmp = new byte[DEFAULT_BUFFER_SIZE];
+ int length = gin.read(tmp);
+ byte[] result = new byte[length];
+ System.arraycopy(tmp,0,result,0,length);
+ return result;
+ }
+
+ public static void main(String[] arg) throws Exception {
+ byte[] data = new byte[1024];
+ Arrays.fill(data,(byte)1);
+ byte[] compress = compress(data);
+ byte[] decompress = decompress(compress);
+ System.out.println("Debug test");
+
+ }
+
+}
Added: tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/MessageDispatch15Interceptor.java
URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/MessageDispatch15Interceptor.java?rev=433703&view=auto
==============================================================================
--- tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/MessageDispatch15Interceptor.java (added)
+++ tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/MessageDispatch15Interceptor.java Tue Aug 22 10:28:09 2006
@@ -0,0 +1,111 @@
+/*
+ * Copyright 1999,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
+ */
+package org.apache.catalina.tribes.group.interceptors;
+
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.catalina.tribes.ChannelMessage;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.group.InterceptorPayload;
+import org.apache.catalina.tribes.transport.bio.util.LinkObject;
+import java.util.concurrent.TimeUnit;
+
+/**
+ *
+ * Same implementation as the MessageDispatchInterceptor
+ * except is ues an atomic long for the currentSize calculation
+ * and uses a thread pool for message sending.
+ *
+ * @author Filip Hanik
+ * @version 1.0
+ */
+
+public class MessageDispatch15Interceptor extends MessageDispatchInterceptor {
+
+ protected AtomicLong currentSize = new AtomicLong(0);
+ protected ThreadPoolExecutor executor = null;
+ protected int maxThreads = 10;
+ protected int maxSpareThreads = 2;
+ protected long keepAliveTime = 5000;
+ protected LinkedBlockingQueue<Runnable> runnablequeue = new LinkedBlockingQueue<Runnable>();
+
+ public long getCurrentSize() {
+ return currentSize.get();
+ }
+
+ public long addAndGetCurrentSize(long inc) {
+ return currentSize.addAndGet(inc);
+ }
+
+ public long setAndGetCurrentSize(long value) {
+ currentSize.set(value);
+ return value;
+ }
+
+ public boolean addToQueue(ChannelMessage msg, Member[] destination, InterceptorPayload payload) {
+ final LinkObject obj = new LinkObject(msg,destination,payload);
+ Runnable r = new Runnable() {
+ public void run() {
+ sendAsyncData(obj);
+ }
+ };
+ executor.execute(r);
+ return true;
+ }
+
+ public LinkObject removeFromQueue() {
+ return null; //not used, thread pool contains its own queue.
+ }
+
+ public void startQueue() {
+ if ( run ) return;
+ executor = new ThreadPoolExecutor(maxSpareThreads,maxThreads,keepAliveTime,TimeUnit.MILLISECONDS,runnablequeue);
+ run = true;
+ }
+
+ public void stopQueue() {
+ run = false;
+ executor.shutdownNow();
+ setAndGetCurrentSize(0);
+ runnablequeue.clear();
+ }
+
+ public long getKeepAliveTime() {
+ return keepAliveTime;
+ }
+
+ public int getMaxSpareThreads() {
+ return maxSpareThreads;
+ }
+
+ public int getMaxThreads() {
+ return maxThreads;
+ }
+
+ public void setKeepAliveTime(long keepAliveTime) {
+ this.keepAliveTime = keepAliveTime;
+ }
+
+ public void setMaxSpareThreads(int maxSpareThreads) {
+ this.maxSpareThreads = maxSpareThreads;
+ }
+
+ public void setMaxThreads(int maxThreads) {
+ this.maxThreads = maxThreads;
+ }
+
+}
\ No newline at end of file
Added: tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java
URL: http://svn.apache.org/viewvc/tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java?rev=433703&view=auto
==============================================================================
--- tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java (added)
+++ tomcat/tc6.0.x/trunk/java/org/apache/catalina/tribes/group/interceptors/MessageDispatchInterceptor.java Tue Aug 22 10:28:09 2006
@@ -0,0 +1,201 @@
+/*
+ * Copyright 1999,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
+ */
+
+package org.apache.catalina.tribes.group.interceptors;
+
+import org.apache.catalina.tribes.Channel;
+import org.apache.catalina.tribes.ChannelException;
+import org.apache.catalina.tribes.ChannelMessage;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.group.ChannelInterceptorBase;
+import org.apache.catalina.tribes.group.InterceptorPayload;
+import org.apache.catalina.tribes.transport.bio.util.FastQueue;
+import org.apache.catalina.tribes.transport.bio.util.LinkObject;
+import org.apache.catalina.tribes.UniqueId;
+
+/**
+ *
+ * The message dispatcher is a way to enable asynchronous communication
+ * through a channel. The dispatcher will look for the <code>Channel.SEND_OPTIONS_ASYNCHRONOUS</code>
+ * flag to be set, if it is, it will queue the message for delivery and immediately return to the sender.
+ *
+ *
+ *
+ * @author Filip Hanik
+ * @version 1.0
+ */
+public class MessageDispatchInterceptor extends ChannelInterceptorBase implements Runnable {
+ protected static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(MessageDispatchInterceptor.class);
+
+ protected long maxQueueSize = 1024*1024*64; //64MB
+ protected FastQueue queue = new FastQueue();
+ protected boolean run = false;
+ protected Thread msgDispatchThread = null;
+ protected long currentSize = 0;
+ protected boolean useDeepClone = true;
+ protected boolean alwaysSend = true;
+
+ public MessageDispatchInterceptor() {
+ setOptionFlag(Channel.SEND_OPTIONS_ASYNCHRONOUS);
+ }
+
+ public void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException {
+ boolean async = (msg.getOptions() & Channel.SEND_OPTIONS_ASYNCHRONOUS) == Channel.SEND_OPTIONS_ASYNCHRONOUS;
+ if ( async && run ) {
+ if ( (getCurrentSize()+msg.getMessage().getLength()) > maxQueueSize ) {
+ if ( alwaysSend ) {
+ super.sendMessage(destination,msg,payload);
+ return;
+ } else {
+ throw new ChannelException("Asynchronous queue is full, reached its limit of " + maxQueueSize +" bytes, current:" + getCurrentSize() + " bytes.");
+ }//end if
+ }//end if
+ //add to queue
+ if ( useDeepClone ) msg = (ChannelMessage)msg.deepclone();
+ if (!addToQueue(msg, destination, payload) ) {
+ throw new ChannelException("Unable to add the message to the async queue, queue bug?");
+ }
+ addAndGetCurrentSize(msg.getMessage().getLength());
+ } else {
+ super.sendMessage(destination, msg, payload);
+ }
+ }
+
+ public boolean addToQueue(ChannelMessage msg, Member[] destination, InterceptorPayload payload) {
+ return queue.add(msg,destination,payload);
+ }
+
+ public LinkObject removeFromQueue() {
+ return queue.remove();
+ }
+
+ public void startQueue() {
+ msgDispatchThread = new Thread(this);
+ msgDispatchThread.setName("MessageDispatchInterceptor.MessageDispatchThread");
+ msgDispatchThread.setDaemon(true);
+ msgDispatchThread.setPriority(Thread.MAX_PRIORITY);
+ queue.setEnabled(true);
+ run = true;
+ msgDispatchThread.start();
+ }
+
+ public void stopQueue() {
+ run = false;
+ msgDispatchThread.interrupt();
+ queue.setEnabled(false);
+ setAndGetCurrentSize(0);
+ }
+
+
+ public void setOptionFlag(int flag) {
+ if ( flag != Channel.SEND_OPTIONS_ASYNCHRONOUS ) log.warn("Warning, you are overriding the asynchronous option flag, this will disable the Channel.SEND_OPTIONS_ASYNCHRONOUS that other apps might use.");
+ super.setOptionFlag(flag);
+ }
+
+ public void setMaxQueueSize(long maxQueueSize) {
+ this.maxQueueSize = maxQueueSize;
+ }
+
+ public void setUseDeepClone(boolean useDeepClone) {
+ this.useDeepClone = useDeepClone;
+ }
+
+ public long getMaxQueueSize() {
+ return maxQueueSize;
+ }
+
+ public boolean getUseDeepClone() {
+ return useDeepClone;
+ }
+
+ public long getCurrentSize() {
+ return currentSize;
+ }
+
+ public synchronized long addAndGetCurrentSize(long inc) {
+ currentSize += inc;
+ return currentSize;
+ }
+
+ public synchronized long setAndGetCurrentSize(long value) {
+ currentSize = value;
+ return value;
+ }
+
+ public void start(int svc) throws ChannelException {
+ //start the thread
+ if (!run ) {
+ synchronized (this) {
+ if ( !run && ((svc & Channel.SND_TX_SEQ)==Channel.SND_TX_SEQ) ) {//only start with the sender
+ startQueue();
+ }//end if
+ }//sync
+ }//end if
+ super.start(svc);
+ }
+
+
+ public void stop(int svc) throws ChannelException {
+ //stop the thread
+ if ( run ) {
+ synchronized (this) {
+ if ( run && ((svc & Channel.SND_TX_SEQ)==Channel.SND_TX_SEQ)) {
+ stopQueue();
+ }//end if
+ }//sync
+ }//end if
+
+ super.stop(svc);
+ }
+
+ public void run() {
+ while ( run ) {
+ LinkObject link = removeFromQueue();
+ if ( link == null ) continue; //should not happen unless we exceed wait time
+ while ( link != null && run ) {
+ link = sendAsyncData(link);
+ }//while
+ }//while
+ }//run
+
+ protected LinkObject sendAsyncData(LinkObject link) {
+ ChannelMessage msg = link.data();
+ Member[] destination = link.getDestination();
+ try {
+ super.sendMessage(destination,msg,null);
+ try {
+ if ( link.getHandler() != null ) link.getHandler().handleCompletion(new UniqueId(msg.getUniqueId()));
+ } catch ( Exception ex ) {
+ log.error("Unable to report back completed message.",ex);
+ }
+ } catch ( Exception x ) {
+ ChannelException cx = null;
+ if ( x instanceof ChannelException ) cx = (ChannelException)x;
+ else cx = new ChannelException(x);
+ if ( log.isDebugEnabled() ) log.debug("Error while processing async message.",x);
+ try {
+ if (link.getHandler() != null) link.getHandler().handleError(cx, new UniqueId(msg.getUniqueId()));
+ } catch ( Exception ex ) {
+ log.error("Unable to report back error message.",ex);
+ }
+ } finally {
+ addAndGetCurrentSize(-msg.getMessage().getLength());
+ link = link.next();
+ }//try
+ return link;
+ }
+
+
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org