-/*\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- * \r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * \r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-\r
-package org.apache.catalina.core;\r
-\r
-import java.util.Collection;\r
-import java.util.concurrent.LinkedBlockingQueue;\r
-import java.util.concurrent.ThreadFactory;\r
-import java.util.concurrent.ThreadPoolExecutor;\r
-import java.util.concurrent.TimeUnit;\r
-import java.util.concurrent.atomic.AtomicInteger;\r
-\r
-import org.apache.catalina.Executor;\r
-import org.apache.catalina.LifecycleException;\r
-import org.apache.catalina.LifecycleListener;\r
-import org.apache.catalina.util.LifecycleSupport;\r
-import java.util.concurrent.RejectedExecutionException;\r
-\r
-public class StandardThreadExecutor implements Executor {\r
- \r
- // ---------------------------------------------- Properties\r
- protected int threadPriority = Thread.NORM_PRIORITY;\r
-\r
- protected boolean daemon = true;\r
- \r
- protected String namePrefix = "tomcat-exec-";\r
- \r
- protected int maxThreads = 200;\r
- \r
- protected int minSpareThreads = 25;\r
- \r
- protected int maxIdleTime = 60000;\r
- \r
- protected ThreadPoolExecutor executor = null;\r
- \r
- protected String name;\r
- \r
- private LifecycleSupport lifecycle = new LifecycleSupport(this);\r
- // ---------------------------------------------- Constructors\r
- public StandardThreadExecutor() {\r
- //empty constructor for the digester\r
- }\r
- \r
-\r
- \r
- // ---------------------------------------------- Public Methods\r
- public void start() throws LifecycleException {\r
- lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);\r
- TaskQueue taskqueue = new TaskQueue();\r
- TaskThreadFactory tf = new TaskThreadFactory(namePrefix);\r
- lifecycle.fireLifecycleEvent(START_EVENT, null);\r
- executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), maxIdleTime, TimeUnit.MILLISECONDS,taskqueue, tf);\r
- taskqueue.setParent( (ThreadPoolExecutor) executor);\r
- lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);\r
- }\r
- \r
- public void stop() throws LifecycleException{\r
- lifecycle.fireLifecycleEvent(BEFORE_STOP_EVENT, null);\r
- lifecycle.fireLifecycleEvent(STOP_EVENT, null);\r
- if ( executor != null ) executor.shutdown();\r
- executor = null;\r
- lifecycle.fireLifecycleEvent(AFTER_STOP_EVENT, null);\r
- }\r
- \r
- public void execute(Runnable command) {\r
- if ( executor != null ) {\r
- try {\r
- executor.execute(command);\r
- } catch (RejectedExecutionException rx) {\r
- //there could have been contention around the queue\r
- if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException();\r
- }\r
- } else throw new IllegalStateException("StandardThreadPool not started.");\r
- }\r
-\r
- public int getThreadPriority() {\r
- return threadPriority;\r
- }\r
-\r
- public boolean isDaemon() {\r
-\r
- return daemon;\r
- }\r
-\r
- public String getNamePrefix() {\r
- return namePrefix;\r
- }\r
-\r
- public int getMaxIdleTime() {\r
- return maxIdleTime;\r
- }\r
-\r
- public int getMaxThreads() {\r
- return maxThreads;\r
- }\r
-\r
- public int getMinSpareThreads() {\r
- return minSpareThreads;\r
- }\r
-\r
- public String getName() {\r
- return name;\r
- }\r
-\r
- public void setThreadPriority(int threadPriority) {\r
- this.threadPriority = threadPriority;\r
- }\r
-\r
- public void setDaemon(boolean daemon) {\r
- this.daemon = daemon;\r
- }\r
-\r
- public void setNamePrefix(String namePrefix) {\r
- this.namePrefix = namePrefix;\r
- }\r
-\r
- public void setMaxIdleTime(int maxIdleTime) {\r
- this.maxIdleTime = maxIdleTime;\r
- }\r
-\r
- public void setMaxThreads(int maxThreads) {\r
- this.maxThreads = maxThreads;\r
- }\r
-\r
- public void setMinSpareThreads(int minSpareThreads) {\r
- this.minSpareThreads = minSpareThreads;\r
- }\r
-\r
- public void setName(String name) {\r
- this.name = name;\r
- }\r
- \r
- /**\r
- * Add a LifecycleEvent listener to this component.\r
- *\r
- * @param listener The listener to add\r
- */\r
- public void addLifecycleListener(LifecycleListener listener) {\r
- lifecycle.addLifecycleListener(listener);\r
- }\r
-\r
-\r
- /**\r
- * Get the lifecycle listeners associated with this lifecycle. If this \r
- * Lifecycle has no listeners registered, a zero-length array is returned.\r
- */\r
- public LifecycleListener[] findLifecycleListeners() {\r
- return lifecycle.findLifecycleListeners();\r
- }\r
-\r
-\r
- /**\r
- * Remove a LifecycleEvent listener from this component.\r
- *\r
- * @param listener The listener to remove\r
- */\r
- public void removeLifecycleListener(LifecycleListener listener) {\r
- lifecycle.removeLifecycleListener(listener);\r
- }\r
-\r
- // Statistics from the thread pool\r
- public int getActiveCount() {\r
- return (executor != null) ? executor.getActiveCount() : 0;\r
- }\r
-\r
- public long getCompletedTaskCount() {\r
- return (executor != null) ? executor.getCompletedTaskCount() : 0;\r
- }\r
-\r
- public int getCorePoolSize() {\r
- return (executor != null) ? executor.getCorePoolSize() : 0;\r
- }\r
-\r
- public int getLargestPoolSize() {\r
- return (executor != null) ? executor.getLargestPoolSize() : 0;\r
- }\r
-\r
- public int getPoolSize() {\r
- return (executor != null) ? executor.getPoolSize() : 0;\r
- }\r
-\r
- // ---------------------------------------------- TaskQueue Inner Class\r
- class TaskQueue extends LinkedBlockingQueue<Runnable> {\r
- ThreadPoolExecutor parent = null;\r
-\r
- public TaskQueue() {\r
- super();\r
- }\r
-\r
- public TaskQueue(int initialCapacity) {\r
- super(initialCapacity);\r
- }\r
-\r
- public TaskQueue(Collection<? extends Runnable> c) {\r
- super(c);\r
- }\r
-\r
- public void setParent(ThreadPoolExecutor tp) {\r
- parent = tp;\r
- }\r
- \r
- public boolean force(Runnable o) {\r
- if ( parent.isShutdown() ) throw new RejectedExecutionException("Executor not running, can't force a command into the queue");\r
- return super.offer(o); //forces the item onto the queue, to be used if the task is rejected\r
- }\r
-\r
- public boolean offer(Runnable o) {\r
- //we can't do any checks\r
- if (parent==null) return super.offer(o);\r
- //we are maxed out on threads, simply queue the object\r
- if (parent.getPoolSize() == parent.getMaximumPoolSize()) return super.offer(o);\r
- //we have idle threads, just add it to the queue\r
- //this is an approximation, so it could use some tuning\r
- if (parent.getActiveCount()<(parent.getPoolSize())) return super.offer(o);\r
- //if we have less threads than maximum force creation of a new thread\r
- if (parent.getPoolSize()<parent.getMaximumPoolSize()) return false;\r
- //if we reached here, we need to add it to the queue\r
- return super.offer(o);\r
- }\r
- }\r
-\r
- // ---------------------------------------------- ThreadFactory Inner Class\r
- class TaskThreadFactory implements ThreadFactory {\r
- final ThreadGroup group;\r
- final AtomicInteger threadNumber = new AtomicInteger(1);\r
- final String namePrefix;\r
-\r
- TaskThreadFactory(String namePrefix) {\r
- SecurityManager s = System.getSecurityManager();\r
- group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();\r
- this.namePrefix = namePrefix;\r
- }\r
-\r
- public Thread newThread(Runnable r) {\r
- Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement());\r
- t.setDaemon(daemon);\r
- t.setPriority(getThreadPriority());\r
- return t;\r
- }\r
- }\r
-\r
-\r
+/*
+ * 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.catalina.core;
+
+import java.util.Collection;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.catalina.Executor;
+import org.apache.catalina.LifecycleException;
+import org.apache.catalina.LifecycleListener;
+import org.apache.catalina.util.LifecycleSupport;
+import java.util.concurrent.RejectedExecutionException;
+
+public class StandardThreadExecutor implements Executor {
+
+ // ---------------------------------------------- Properties
+ protected int threadPriority = Thread.NORM_PRIORITY;
+
+ protected boolean daemon = true;
+
+ protected String namePrefix = "tomcat-exec-";
+
+ protected int maxThreads = 200;
+
+ protected int minSpareThreads = 25;
+
+ protected int maxIdleTime = 60000;
+
+ protected ThreadPoolExecutor executor = null;
+
+ protected String name;
+
+ private LifecycleSupport lifecycle = new LifecycleSupport(this);
+ // ---------------------------------------------- Constructors
+ public StandardThreadExecutor() {
+ //empty constructor for the digester
+ }
+
+
+
+ // ---------------------------------------------- Public Methods
+ public void start() throws LifecycleException {
+ lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
+ TaskQueue taskqueue = new TaskQueue();
+ TaskThreadFactory tf = new TaskThreadFactory(namePrefix);
+ lifecycle.fireLifecycleEvent(START_EVENT, null);
+ executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), maxIdleTime, TimeUnit.MILLISECONDS,taskqueue, tf);
+ taskqueue.setParent( (ThreadPoolExecutor) executor);
+ lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
+ }
+
+ public void stop() throws LifecycleException{
+ lifecycle.fireLifecycleEvent(BEFORE_STOP_EVENT, null);
+ lifecycle.fireLifecycleEvent(STOP_EVENT, null);
+ if ( executor != null ) executor.shutdown();
+ executor = null;
+ lifecycle.fireLifecycleEvent(AFTER_STOP_EVENT, null);
+ }
+
+ public void execute(Runnable command) {
+ if ( executor != null ) {
+ try {
+ executor.execute(command);
+ } catch (RejectedExecutionException rx) {
+ //there could have been contention around the queue
+ if ( !( (TaskQueue) executor.getQueue()).force(command) ) throw new RejectedExecutionException();
+ }
+ } else throw new IllegalStateException("StandardThreadPool not started.");
+ }
+
+ public int getThreadPriority() {
+ return threadPriority;
+ }
+
+ public boolean isDaemon() {
+
+ return daemon;
+ }
+
+ public String getNamePrefix() {
+ return namePrefix;
+ }
+
+ public int getMaxIdleTime() {
+ return maxIdleTime;
+ }
+
+ public int getMaxThreads() {
+ return maxThreads;
+ }
+
+ public int getMinSpareThreads() {
+ return minSpareThreads;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setThreadPriority(int threadPriority) {
+ this.threadPriority = threadPriority;
+ }
+
+ public void setDaemon(boolean daemon) {
+ this.daemon = daemon;
+ }
+
+ public void setNamePrefix(String namePrefix) {
+ this.namePrefix = namePrefix;
+ }
+
+ public void setMaxIdleTime(int maxIdleTime) {
+ this.maxIdleTime = maxIdleTime;
+ }
+
+ public void setMaxThreads(int maxThreads) {
+ this.maxThreads = maxThreads;
+ }
+
+ public void setMinSpareThreads(int minSpareThreads) {
+ this.minSpareThreads = minSpareThreads;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Add a LifecycleEvent listener to this component.
+ *
+ * @param listener The listener to add
+ */
+ public void addLifecycleListener(LifecycleListener listener) {
+ lifecycle.addLifecycleListener(listener);
+ }
+
+
+ /**
+ * Get the lifecycle listeners associated with this lifecycle. If this
+ * Lifecycle has no listeners registered, a zero-length array is returned.
+ */
+ public LifecycleListener[] findLifecycleListeners() {
+ return lifecycle.findLifecycleListeners();
+ }
+
+
+ /**
+ * Remove a LifecycleEvent listener from this component.
+ *
+ * @param listener The listener to remove
+ */
+ public void removeLifecycleListener(LifecycleListener listener) {
+ lifecycle.removeLifecycleListener(listener);
+ }
+
+ // Statistics from the thread pool
+ public int getActiveCount() {
+ return (executor != null) ? executor.getActiveCount() : 0;
+ }
+
+ public long getCompletedTaskCount() {
+ return (executor != null) ? executor.getCompletedTaskCount() : 0;
+ }
+
+ public int getCorePoolSize() {
+ return (executor != null) ? executor.getCorePoolSize() : 0;
+ }
+
+ public int getLargestPoolSize() {
+ return (executor != null) ? executor.getLargestPoolSize() : 0;
+ }
+
+ public int getPoolSize() {
+ return (executor != null) ? executor.getPoolSize() : 0;
+ }
+
+ // ---------------------------------------------- TaskQueue Inner Class
+ class TaskQueue extends LinkedBlockingQueue<Runnable> {
+ ThreadPoolExecutor parent = null;
+
+ public TaskQueue() {
+ super();
+ }
+
+ public TaskQueue(int initialCapacity) {
+ super(initialCapacity);
+ }
+
+ public TaskQueue(Collection<? extends Runnable> c) {
+ super(c);
+ }
+
+ public void setParent(ThreadPoolExecutor tp) {
+ parent = tp;
+ }
+
+ public boolean force(Runnable o) {
+ if ( parent.isShutdown() ) throw new RejectedExecutionException("Executor not running, can't force a command into the queue");
+ return super.offer(o); //forces the item onto the queue, to be used if the task is rejected
+ }
+
+ public boolean offer(Runnable o) {
+ //we can't do any checks
+ if (parent==null) return super.offer(o);
+ //we are maxed out on threads, simply queue the object
+ if (parent.getPoolSize() == parent.getMaximumPoolSize()) return super.offer(o);
+ //we have idle threads, just add it to the queue
+ //this is an approximation, so it could use some tuning
+ if (parent.getActiveCount()<(parent.getPoolSize())) return super.offer(o);
+ //if we have less threads than maximum force creation of a new thread
+ if (parent.getPoolSize()<parent.getMaximumPoolSize()) return false;
+ //if we reached here, we need to add it to the queue
+ return super.offer(o);
+ }
+ }
+
+ // ---------------------------------------------- ThreadFactory Inner Class
+ class TaskThreadFactory implements ThreadFactory {
+ final ThreadGroup group;
+ final AtomicInteger threadNumber = new AtomicInteger(1);
+ final String namePrefix;
+
+ TaskThreadFactory(String namePrefix) {
+ SecurityManager s = System.getSecurityManager();
+ group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
+ this.namePrefix = namePrefix;
+ }
+
+ public Thread newThread(Runnable r) {
+ Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement());
+ t.setDaemon(daemon);
+ t.setPriority(getThreadPriority());
+ return t;
+ }
+ }
+
+
}
\ No newline at end of file
-<?xml version="1.0"?>\r
-<!--\r
- Licensed to the Apache Software Foundation (ASF) under one or more\r
- contributor license agreements. See the NOTICE file distributed with\r
- this work for additional information regarding copyright ownership.\r
- The ASF licenses this file to You under the Apache License, Version 2.0\r
- (the "License"); you may not use this file except in compliance with\r
- the License. You may obtain a copy of the License at\r
- http://www.apache.org/licenses/LICENSE-2.0\r
- Unless required by applicable law or agreed to in writing, software\r
- distributed under the License is distributed on an "AS IS" BASIS,\r
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- See the License for the specific language governing permissions and\r
- limitations under the License.\r
--->\r
-<mbeans-descriptors>\r
- <mbean\r
- name="FarmWarDeployer"\r
- className="org.apache.catalina.mbeans.ClassNameMBean"\r
- description="Farm Deployer - Broken"\r
- domain="Catalina"\r
- group="Cluster"\r
- type="org.apache.catalina.ha.deploy.FarmWarDeployer"/>\r
-</mbeans-descriptors>\r
+<?xml version="1.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.
+-->
+<mbeans-descriptors>
+ <mbean
+ name="FarmWarDeployer"
+ className="org.apache.catalina.mbeans.ClassNameMBean"
+ description="Farm Deployer - Broken"
+ domain="Catalina"
+ group="Cluster"
+ type="org.apache.catalina.ha.deploy.FarmWarDeployer"/>
+</mbeans-descriptors>
-/*\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- * \r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * \r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.apache.catalina.ha.jmx;\r
-\r
-import javax.management.DynamicMBean;\r
-import javax.management.MBeanServer;\r
-import javax.management.MBeanServerFactory;\r
-import javax.management.ObjectName;\r
-\r
-import org.apache.catalina.core.StandardEngine;\r
-import org.apache.catalina.core.StandardHost;\r
-import org.apache.catalina.ha.authenticator.ClusterSingleSignOn;\r
-import org.apache.catalina.ha.deploy.FarmWarDeployer;\r
-import org.apache.catalina.ha.session.DeltaManager;\r
-import org.apache.catalina.ha.tcp.SimpleTcpCluster;\r
-import org.apache.juli.logging.Log;\r
-import org.apache.juli.logging.LogFactory;\r
-import org.apache.tomcat.util.modeler.ManagedBean;\r
-import org.apache.tomcat.util.modeler.Registry;\r
-/**\r
- * \r
- * @author Filip Hanik\r
- */\r
-public class ClusterJmxHelper {\r
- \r
- protected static Registry registry = Registry.getRegistry(null,null);\r
- \r
- protected static Log log = LogFactory.getLog(ClusterJmxHelper.class);\r
- \r
- protected static boolean jmxEnabled = true;\r
- \r
- protected static MBeanServer mbeanServer = null;\r
- \r
- public static Registry getRegistry() {\r
- return registry;\r
- }\r
-\r
- public static MBeanServer getMBeanServer() throws Exception {\r
- if (mbeanServer == null) {\r
- if (MBeanServerFactory.findMBeanServer(null).size() > 0) {\r
- mbeanServer = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);\r
- } else {\r
- mbeanServer = MBeanServerFactory.createMBeanServer();\r
- }\r
- }\r
- return mbeanServer;\r
- }\r
- \r
- protected static boolean initMetaData(Class clazz) {\r
- try {\r
- if (clazz==null) return false;\r
- getRegistry().loadMetadata(clazz.getResourceAsStream("mbeans-descriptors.xml"));\r
- }catch (Exception x) {\r
- log.warn("Unable to load meta data for class:"+clazz.getName());\r
- return false;\r
- }\r
- return true;\r
- }\r
- \r
- public static DynamicMBean getManagedBean(Object object) throws Exception {\r
- DynamicMBean mbean = null;\r
- if (getRegistry() != null) {\r
- ManagedBean managedBean = registry.findManagedBean(object.getClass().getName());\r
- mbean = managedBean.createMBean(object);\r
- }\r
- return mbean;\r
- }\r
-\r
- \r
- protected static void initDefaultCluster() {\r
- initMetaData(SimpleTcpCluster.class);\r
- initMetaData(DeltaManager.class);\r
- initMetaData(FarmWarDeployer.class); //not functional yet\r
- initMetaData(ClusterSingleSignOn.class); //not functional yet\r
- }\r
- \r
- public static boolean registerDefaultCluster(SimpleTcpCluster cluster) {\r
- try {\r
- initDefaultCluster();\r
- ObjectName clusterName = getDefaultClusterName(cluster);\r
- if (!getMBeanServer().isRegistered(clusterName)) {\r
- getMBeanServer().registerMBean(getManagedBean(cluster), clusterName);\r
- }\r
- return true;\r
- }catch ( Exception x ) {\r
- log.warn("Unable to register default cluster implementation with JMX",x);\r
- return false;\r
- }\r
- }\r
-\r
- public static boolean unregisterDefaultCluster(SimpleTcpCluster cluster) {\r
- try {\r
- ObjectName clusterName = getDefaultClusterName(cluster);\r
- if (getMBeanServer().isRegistered(clusterName)) {\r
- getMBeanServer().unregisterMBean(clusterName);\r
- }\r
- return true;\r
- }catch ( Exception x ) {\r
- log.warn("Unable to unregister default cluster implementation with JMX",x);\r
- return false;\r
- }\r
- }\r
-\r
- private static ObjectName getDefaultClusterName(SimpleTcpCluster cluster) throws Exception {\r
- String domain = getMBeanServer().getDefaultDomain();\r
- String type = ":type=";\r
- String clusterType= type+"Cluster";\r
- if (cluster.getContainer() instanceof StandardHost) {\r
- domain = ((StandardHost) cluster.getContainer()).getDomain();\r
- clusterType += ",host=" + cluster.getContainer().getName();\r
- } else {\r
- if (cluster.getContainer() instanceof StandardEngine) {\r
- domain = ((StandardEngine) cluster.getContainer()).getDomain();\r
- }\r
- }\r
- ObjectName clusterName = new ObjectName(domain + clusterType);\r
- return clusterName;\r
- }\r
- \r
+/*
+ * 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.catalina.ha.jmx;
+
+import javax.management.DynamicMBean;
+import javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.ObjectName;
+
+import org.apache.catalina.core.StandardEngine;
+import org.apache.catalina.core.StandardHost;
+import org.apache.catalina.ha.authenticator.ClusterSingleSignOn;
+import org.apache.catalina.ha.deploy.FarmWarDeployer;
+import org.apache.catalina.ha.session.DeltaManager;
+import org.apache.catalina.ha.tcp.SimpleTcpCluster;
+import org.apache.juli.logging.Log;
+import org.apache.juli.logging.LogFactory;
+import org.apache.tomcat.util.modeler.ManagedBean;
+import org.apache.tomcat.util.modeler.Registry;
+/**
+ *
+ * @author Filip Hanik
+ */
+public class ClusterJmxHelper {
+
+ protected static Registry registry = Registry.getRegistry(null,null);
+
+ protected static Log log = LogFactory.getLog(ClusterJmxHelper.class);
+
+ protected static boolean jmxEnabled = true;
+
+ protected static MBeanServer mbeanServer = null;
+
+ public static Registry getRegistry() {
+ return registry;
+ }
+
+ public static MBeanServer getMBeanServer() throws Exception {
+ if (mbeanServer == null) {
+ if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
+ mbeanServer = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
+ } else {
+ mbeanServer = MBeanServerFactory.createMBeanServer();
+ }
+ }
+ return mbeanServer;
+ }
+
+ protected static boolean initMetaData(Class clazz) {
+ try {
+ if (clazz==null) return false;
+ getRegistry().loadMetadata(clazz.getResourceAsStream("mbeans-descriptors.xml"));
+ }catch (Exception x) {
+ log.warn("Unable to load meta data for class:"+clazz.getName());
+ return false;
+ }
+ return true;
+ }
+
+ public static DynamicMBean getManagedBean(Object object) throws Exception {
+ DynamicMBean mbean = null;
+ if (getRegistry() != null) {
+ ManagedBean managedBean = registry.findManagedBean(object.getClass().getName());
+ mbean = managedBean.createMBean(object);
+ }
+ return mbean;
+ }
+
+
+ protected static void initDefaultCluster() {
+ initMetaData(SimpleTcpCluster.class);
+ initMetaData(DeltaManager.class);
+ initMetaData(FarmWarDeployer.class); //not functional yet
+ initMetaData(ClusterSingleSignOn.class); //not functional yet
+ }
+
+ public static boolean registerDefaultCluster(SimpleTcpCluster cluster) {
+ try {
+ initDefaultCluster();
+ ObjectName clusterName = getDefaultClusterName(cluster);
+ if (!getMBeanServer().isRegistered(clusterName)) {
+ getMBeanServer().registerMBean(getManagedBean(cluster), clusterName);
+ }
+ return true;
+ }catch ( Exception x ) {
+ log.warn("Unable to register default cluster implementation with JMX",x);
+ return false;
+ }
+ }
+
+ public static boolean unregisterDefaultCluster(SimpleTcpCluster cluster) {
+ try {
+ ObjectName clusterName = getDefaultClusterName(cluster);
+ if (getMBeanServer().isRegistered(clusterName)) {
+ getMBeanServer().unregisterMBean(clusterName);
+ }
+ return true;
+ }catch ( Exception x ) {
+ log.warn("Unable to unregister default cluster implementation with JMX",x);
+ return false;
+ }
+ }
+
+ private static ObjectName getDefaultClusterName(SimpleTcpCluster cluster) throws Exception {
+ String domain = getMBeanServer().getDefaultDomain();
+ String type = ":type=";
+ String clusterType= type+"Cluster";
+ if (cluster.getContainer() instanceof StandardHost) {
+ domain = ((StandardHost) cluster.getContainer()).getDomain();
+ clusterType += ",host=" + cluster.getContainer().getName();
+ } else {
+ if (cluster.getContainer() instanceof StandardEngine) {
+ domain = ((StandardEngine) cluster.getContainer()).getDomain();
+ }
+ }
+ ObjectName clusterName = new ObjectName(domain + clusterType);
+ return clusterName;
+ }
+
}
\ No newline at end of file
-/*\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- * \r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * \r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-\r
-package org.apache.catalina.tribes.group.interceptors;\r
-\r
-import java.lang.ref.WeakReference;\r
-import java.util.Arrays;\r
-import java.util.concurrent.atomic.AtomicInteger;\r
-\r
-import org.apache.catalina.tribes.ChannelException;\r
-import org.apache.catalina.tribes.ChannelInterceptor;\r
-import org.apache.catalina.tribes.ChannelMessage;\r
-import org.apache.catalina.tribes.Member;\r
-import org.apache.catalina.tribes.group.ChannelInterceptorBase;\r
-import org.apache.catalina.tribes.io.ChannelData;\r
-\r
-/**\r
- * \r
- * Sends a ping to all members.\r
- * Configure this interceptor with the TcpFailureDetector below it,\r
- * and the TcpFailureDetector will act as the membership guide.\r
- * @author Filip Hanik\r
- * @version 1.0\r
- */\r
-\r
-public class TcpPingInterceptor extends ChannelInterceptorBase {\r
- \r
- protected static org.apache.juli.logging.Log log = \r
- org.apache.juli.logging.LogFactory.getLog(TcpPingInterceptor.class);\r
- \r
- protected static byte[] TCP_PING_DATA = new byte[] {\r
- 79, -89, 115, 72, 121, -33, 67, -55, -97, 111, -119, -128, -95, 91, 7, 20,\r
- 125, -39, 82, 91, -21, -33, 67, -102, -73, 126, -66, -113, -127, 103, 30, -74,\r
- 55, 21, -66, -121, 69, 33, 76, -88, -65, 10, 77, 19, 83, 56, 21, 50,\r
- 85, -10, -108, -73, 58, -33, 33, 120, -111, 4, 125, -41, 114, -124, -64, -43}; \r
-\r
- protected long interval = 1000; //1 second\r
-\r
- protected boolean useThread = false;\r
- protected boolean staticOnly = false;\r
- protected boolean running = true;\r
- protected PingThread thread = null;\r
- protected static AtomicInteger cnt = new AtomicInteger(0);\r
- \r
- WeakReference<TcpFailureDetector> failureDetector = null;\r
- WeakReference<StaticMembershipInterceptor> staticMembers = null;\r
- \r
- public synchronized void start(int svc) throws ChannelException {\r
- super.start(svc);\r
- running = true;\r
- if ( thread == null ) {\r
- thread = new PingThread();\r
- thread.setDaemon(true);\r
- thread.setName("TcpPingInterceptor.PingThread-"+cnt.addAndGet(1));\r
- thread.start();\r
- }\r
- \r
- //acquire the interceptors to invoke on send ping events\r
- ChannelInterceptor next = getNext();\r
- while ( next != null ) {\r
- if ( next instanceof TcpFailureDetector ) \r
- failureDetector = new WeakReference<TcpFailureDetector>((TcpFailureDetector)next);\r
- if ( next instanceof StaticMembershipInterceptor ) \r
- staticMembers = new WeakReference<StaticMembershipInterceptor>((StaticMembershipInterceptor)next);\r
- next = next.getNext();\r
- }\r
- \r
- }\r
- \r
- public void stop(int svc) throws ChannelException {\r
- running = false;\r
- if ( thread != null ) thread.interrupt();\r
- thread = null;\r
- super.stop(svc);\r
- }\r
- \r
- public void heartbeat() {\r
- super.heartbeat();\r
- if (!getUseThread()) sendPing();\r
- }\r
-\r
- public long getInterval() {\r
- return interval;\r
- }\r
-\r
- public void setInterval(long interval) {\r
- this.interval = interval;\r
- }\r
-\r
- public void setUseThread(boolean useThread) {\r
- this.useThread = useThread;\r
- }\r
-\r
- public void setStaticOnly(boolean staticOnly) {\r
- this.staticOnly = staticOnly;\r
- }\r
-\r
- public boolean getUseThread() {\r
- return useThread;\r
- }\r
-\r
- public boolean getStaticOnly() {\r
- return staticOnly;\r
- }\r
-\r
- protected void sendPing() {\r
- if (failureDetector.get()!=null) {\r
- //we have a reference to the failure detector\r
- //piggy back on that dude\r
- failureDetector.get().checkMembers(true);\r
- }else {\r
- if (staticOnly && staticMembers.get()!=null) {\r
- sendPingMessage(staticMembers.get().getMembers());\r
- } else {\r
- sendPingMessage(getMembers());\r
- }\r
- }\r
- }\r
-\r
- protected void sendPingMessage(Member[] members) {\r
- if ( members == null || members.length == 0 ) return;\r
- ChannelData data = new ChannelData(true);//generates a unique Id\r
- data.setAddress(getLocalMember(false));\r
- data.setTimestamp(System.currentTimeMillis());\r
- data.setOptions(getOptionFlag());\r
- try {\r
- super.sendMessage(members, data, null);\r
- }catch (ChannelException x) {\r
- log.warn("Unable to send TCP ping.",x);\r
- }\r
- }\r
- \r
- public void messageReceived(ChannelMessage msg) {\r
- //catch incoming \r
- boolean process = true;\r
- if ( okToProcess(msg.getOptions()) ) {\r
- //check to see if it is a ping message, if so, process = false\r
- process = ( (msg.getMessage().getLength() != TCP_PING_DATA.length) ||\r
- (!Arrays.equals(TCP_PING_DATA,msg.getMessage().getBytes()) ) );\r
- }//end if\r
-\r
- //ignore the message, it doesnt have the flag set\r
- if ( process ) super.messageReceived(msg);\r
- else if ( log.isDebugEnabled() ) log.debug("Received a TCP ping packet:"+msg);\r
- }//messageReceived\r
- \r
- protected class PingThread extends Thread {\r
- public void run() {\r
- while (running) {\r
- try {\r
- sleep(interval);\r
- sendPing();\r
- }catch ( InterruptedException ix ) {\r
- interrupted();\r
- }catch ( Exception x ) {\r
- log.warn("Unable to send ping from TCP ping thread.",x);\r
- }\r
- }\r
- }\r
- }\r
-\r
- \r
- \r
-\r
-}\r
+/*
+ * 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.catalina.tribes.group.interceptors;
+
+import java.lang.ref.WeakReference;
+import java.util.Arrays;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.catalina.tribes.ChannelException;
+import org.apache.catalina.tribes.ChannelInterceptor;
+import org.apache.catalina.tribes.ChannelMessage;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.group.ChannelInterceptorBase;
+import org.apache.catalina.tribes.io.ChannelData;
+
+/**
+ *
+ * Sends a ping to all members.
+ * Configure this interceptor with the TcpFailureDetector below it,
+ * and the TcpFailureDetector will act as the membership guide.
+ * @author Filip Hanik
+ * @version 1.0
+ */
+
+public class TcpPingInterceptor extends ChannelInterceptorBase {
+
+ protected static org.apache.juli.logging.Log log =
+ org.apache.juli.logging.LogFactory.getLog(TcpPingInterceptor.class);
+
+ protected static byte[] TCP_PING_DATA = new byte[] {
+ 79, -89, 115, 72, 121, -33, 67, -55, -97, 111, -119, -128, -95, 91, 7, 20,
+ 125, -39, 82, 91, -21, -33, 67, -102, -73, 126, -66, -113, -127, 103, 30, -74,
+ 55, 21, -66, -121, 69, 33, 76, -88, -65, 10, 77, 19, 83, 56, 21, 50,
+ 85, -10, -108, -73, 58, -33, 33, 120, -111, 4, 125, -41, 114, -124, -64, -43};
+
+ protected long interval = 1000; //1 second
+
+ protected boolean useThread = false;
+ protected boolean staticOnly = false;
+ protected boolean running = true;
+ protected PingThread thread = null;
+ protected static AtomicInteger cnt = new AtomicInteger(0);
+
+ WeakReference<TcpFailureDetector> failureDetector = null;
+ WeakReference<StaticMembershipInterceptor> staticMembers = null;
+
+ public synchronized void start(int svc) throws ChannelException {
+ super.start(svc);
+ running = true;
+ if ( thread == null ) {
+ thread = new PingThread();
+ thread.setDaemon(true);
+ thread.setName("TcpPingInterceptor.PingThread-"+cnt.addAndGet(1));
+ thread.start();
+ }
+
+ //acquire the interceptors to invoke on send ping events
+ ChannelInterceptor next = getNext();
+ while ( next != null ) {
+ if ( next instanceof TcpFailureDetector )
+ failureDetector = new WeakReference<TcpFailureDetector>((TcpFailureDetector)next);
+ if ( next instanceof StaticMembershipInterceptor )
+ staticMembers = new WeakReference<StaticMembershipInterceptor>((StaticMembershipInterceptor)next);
+ next = next.getNext();
+ }
+
+ }
+
+ public void stop(int svc) throws ChannelException {
+ running = false;
+ if ( thread != null ) thread.interrupt();
+ thread = null;
+ super.stop(svc);
+ }
+
+ public void heartbeat() {
+ super.heartbeat();
+ if (!getUseThread()) sendPing();
+ }
+
+ public long getInterval() {
+ return interval;
+ }
+
+ public void setInterval(long interval) {
+ this.interval = interval;
+ }
+
+ public void setUseThread(boolean useThread) {
+ this.useThread = useThread;
+ }
+
+ public void setStaticOnly(boolean staticOnly) {
+ this.staticOnly = staticOnly;
+ }
+
+ public boolean getUseThread() {
+ return useThread;
+ }
+
+ public boolean getStaticOnly() {
+ return staticOnly;
+ }
+
+ protected void sendPing() {
+ if (failureDetector.get()!=null) {
+ //we have a reference to the failure detector
+ //piggy back on that dude
+ failureDetector.get().checkMembers(true);
+ }else {
+ if (staticOnly && staticMembers.get()!=null) {
+ sendPingMessage(staticMembers.get().getMembers());
+ } else {
+ sendPingMessage(getMembers());
+ }
+ }
+ }
+
+ protected void sendPingMessage(Member[] members) {
+ if ( members == null || members.length == 0 ) return;
+ ChannelData data = new ChannelData(true);//generates a unique Id
+ data.setAddress(getLocalMember(false));
+ data.setTimestamp(System.currentTimeMillis());
+ data.setOptions(getOptionFlag());
+ try {
+ super.sendMessage(members, data, null);
+ }catch (ChannelException x) {
+ log.warn("Unable to send TCP ping.",x);
+ }
+ }
+
+ public void messageReceived(ChannelMessage msg) {
+ //catch incoming
+ boolean process = true;
+ if ( okToProcess(msg.getOptions()) ) {
+ //check to see if it is a ping message, if so, process = false
+ process = ( (msg.getMessage().getLength() != TCP_PING_DATA.length) ||
+ (!Arrays.equals(TCP_PING_DATA,msg.getMessage().getBytes()) ) );
+ }//end if
+
+ //ignore the message, it doesnt have the flag set
+ if ( process ) super.messageReceived(msg);
+ else if ( log.isDebugEnabled() ) log.debug("Received a TCP ping packet:"+msg);
+ }//messageReceived
+
+ protected class PingThread extends Thread {
+ public void run() {
+ while (running) {
+ try {
+ sleep(interval);
+ sendPing();
+ }catch ( InterruptedException ix ) {
+ interrupted();
+ }catch ( Exception x ) {
+ log.warn("Unable to send ping from TCP ping thread.",x);
+ }
+ }
+ }
+ }
+
+
+
+
+}
-/*\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.apache.tomcat.util.net;\r
-\r
-import java.net.Socket;\r
-import java.net.SocketException;\r
-/**\r
- * Properties that can be set in the <Connector> element\r
- * in server.xml. All properties are prefixed with "socket."\r
- * and are currently only working for the Nio connector\r
- *\r
- * @author Filip Hanik\r
- */\r
-public class SocketProperties {\r
- /**\r
- * Enable/disable key cache, this bounded cache stores\r
- * KeyAttachment objects to reduce GC\r
- * Default is 500\r
- * -1 is unlimited\r
- * 0 is disabled\r
- */\r
- protected int keyCache = 500;\r
- \r
- /**\r
- * Enable/disable socket processor cache, this bounded cache stores\r
- * SocketProcessor objects to reduce GC\r
- * Default is 500\r
- * -1 is unlimited\r
- * 0 is disabled\r
- */\r
- protected int processorCache = 500;\r
-\r
-\r
-\r
- /**\r
- * Enable/disable poller event cache, this bounded cache stores\r
- * PollerEvent objects to reduce GC for the poller\r
- * Default is 500 \r
- * -1 is unlimited\r
- * 0 is disabled\r
- * >0 the max number of objects to keep in cache.\r
- */\r
- protected int eventCache = 500;\r
-\r
-\r
- /**\r
- * Enable/disable direct buffers for the network buffers\r
- * Default value is enabled\r
- */\r
- protected boolean directBuffer = false;\r
- /**\r
- * Socket receive buffer size in bytes (SO_RCVBUF)\r
- * Default value is 25188\r
- */\r
- protected int rxBufSize = 25188;\r
- /**\r
- * Socket send buffer size in bytes (SO_SNDBUF)\r
- * Default value is 43800\r
- */\r
- protected int txBufSize = 43800;\r
-\r
- /**\r
- * The application read buffer size in bytes.\r
- * Default value is rxBufSize\r
- */\r
- protected int appReadBufSize = 8192;\r
-\r
- /**\r
- * The application write buffer size in bytes\r
- * Default value is txBufSize\r
- */\r
- protected int appWriteBufSize = 8192;\r
-\r
- /**\r
- * NioChannel pool size for the endpoint,\r
- * this value is how many channels\r
- * -1 means unlimited cached, 0 means no cache\r
- * Default value is 500\r
- */\r
- protected int bufferPool = 500;\r
-\r
-\r
- /**\r
- * Buffer pool size in bytes to be cached\r
- * -1 means unlimited, 0 means no cache\r
- * Default value is 100MB (1024*1024*100 bytes)\r
- */\r
- protected int bufferPoolSize = 1024*1024*100;\r
-\r
- /**\r
- * TCP_NO_DELAY option, default is true\r
- */\r
- protected boolean tcpNoDelay = true;\r
- /**\r
- * SO_KEEPALIVE option, default is false\r
- */\r
- protected boolean soKeepAlive = false;\r
- /**\r
- * OOBINLINE option, default is true\r
- */\r
- protected boolean ooBInline = true;\r
- /**\r
- * SO_REUSEADDR option, default is true\r
- */\r
- protected boolean soReuseAddress = true;\r
- /**\r
- * SO_LINGER option, default is true, paired with the <code>soLingerTime</code> value\r
- */\r
- protected boolean soLingerOn = true;\r
- /**\r
- * SO_LINGER option, default is 25 seconds.\r
- */\r
- protected int soLingerTime = 25;\r
- /**\r
- * SO_TIMEOUT option, default is 5000 milliseconds\r
- */\r
- protected int soTimeout = 5000;\r
- /**\r
- * Traffic class option, value between 0 and 255\r
- * IPTOS_LOWCOST (0x02)\r
- * IPTOS_RELIABILITY (0x04)\r
- * IPTOS_THROUGHPUT (0x08)\r
- * IPTOS_LOWDELAY (0x10)\r
- * Default value is 0x04 | 0x08 | 0x010\r
- */\r
- protected int soTrafficClass = 0x04 | 0x08 | 0x010;\r
- /**\r
- * Performance preferences according to\r
- * http://java.sun.com/j2se/1.5.0/docs/api/java/net/Socket.html#setPerformancePreferences(int,%20int,%20int)\r
- * Default value is 1\r
- */\r
- protected int performanceConnectionTime = 1;\r
- /**\r
- * Performance preferences according to\r
- * http://java.sun.com/j2se/1.5.0/docs/api/java/net/Socket.html#setPerformancePreferences(int,%20int,%20int)\r
- * Default value is 0\r
- */\r
- protected int performanceLatency = 0;\r
- /**\r
- * Performance preferences according to\r
- * http://java.sun.com/j2se/1.5.0/docs/api/java/net/Socket.html#setPerformancePreferences(int,%20int,%20int)\r
- * Default value is 1\r
- */\r
- protected int performanceBandwidth = 1;\r
- \r
- /**\r
- * The minimum frequency of the timeout interval to avoid the \r
- * poller going boinkers during high traffic\r
- */\r
- protected long timeoutInterval = 1000;\r
-\r
-\r
- private Socket properties;\r
-\r
- public void setProperties(Socket socket) throws SocketException{\r
- socket.setReceiveBufferSize(rxBufSize);\r
- socket.setSendBufferSize(txBufSize);\r
- socket.setOOBInline(ooBInline);\r
- socket.setKeepAlive(soKeepAlive);\r
- socket.setPerformancePreferences(performanceConnectionTime,performanceLatency,performanceBandwidth);\r
- socket.setReuseAddress(soReuseAddress);\r
- socket.setSoLinger(soLingerOn,soLingerTime);\r
- socket.setSoTimeout(soTimeout);\r
- socket.setTcpNoDelay(tcpNoDelay);\r
- socket.setTrafficClass(soTrafficClass);\r
- }\r
-\r
- public boolean getDirectBuffer() {\r
- return directBuffer;\r
- }\r
-\r
- public boolean getOoBInline() {\r
- return ooBInline;\r
- }\r
-\r
- public int getPerformanceBandwidth() {\r
- return performanceBandwidth;\r
- }\r
-\r
- public int getPerformanceConnectionTime() {\r
- return performanceConnectionTime;\r
- }\r
-\r
- public int getPerformanceLatency() {\r
- return performanceLatency;\r
- }\r
-\r
- public int getRxBufSize() {\r
- return rxBufSize;\r
- }\r
-\r
- public boolean getSoKeepAlive() {\r
- return soKeepAlive;\r
- }\r
-\r
- public boolean getSoLingerOn() {\r
- return soLingerOn;\r
- }\r
-\r
- public int getSoLingerTime() {\r
- return soLingerTime;\r
- }\r
-\r
- public boolean getSoReuseAddress() {\r
- return soReuseAddress;\r
- }\r
-\r
- public int getSoTimeout() {\r
- return soTimeout;\r
- }\r
-\r
- public int getSoTrafficClass() {\r
- return soTrafficClass;\r
- }\r
-\r
- public boolean getTcpNoDelay() {\r
- return tcpNoDelay;\r
- }\r
-\r
- public int getTxBufSize() {\r
- return txBufSize;\r
- }\r
-\r
- public int getBufferPool() {\r
- return bufferPool;\r
- }\r
-\r
- public int getBufferPoolSize() {\r
- return bufferPoolSize;\r
- }\r
-\r
- public int getEventCache() {\r
- return eventCache;\r
- }\r
-\r
- public int getKeyCache() {\r
- return keyCache;\r
- }\r
-\r
- public Socket getProperties() {\r
- return properties;\r
- }\r
-\r
- public int getAppReadBufSize() {\r
- return appReadBufSize;\r
- }\r
-\r
- public int getAppWriteBufSize() {\r
- return appWriteBufSize;\r
- }\r
-\r
- public int getProcessorCache() {\r
- return processorCache;\r
- }\r
-\r
- public long getTimeoutInterval() {\r
- return timeoutInterval;\r
- }\r
-\r
- public int getDirectBufferPool() {\r
- return bufferPool;\r
- }\r
-\r
- public void setPerformanceConnectionTime(int performanceConnectionTime) {\r
- this.performanceConnectionTime = performanceConnectionTime;\r
- }\r
-\r
- public void setTxBufSize(int txBufSize) {\r
- this.txBufSize = txBufSize;\r
- }\r
-\r
- public void setTcpNoDelay(boolean tcpNoDelay) {\r
- this.tcpNoDelay = tcpNoDelay;\r
- }\r
-\r
- public void setSoTrafficClass(int soTrafficClass) {\r
- this.soTrafficClass = soTrafficClass;\r
- }\r
-\r
- public void setSoTimeout(int soTimeout) {\r
- this.soTimeout = soTimeout;\r
- }\r
-\r
- public void setSoReuseAddress(boolean soReuseAddress) {\r
- this.soReuseAddress = soReuseAddress;\r
- }\r
-\r
- public void setSoLingerTime(int soLingerTime) {\r
- this.soLingerTime = soLingerTime;\r
- }\r
-\r
- public void setSoKeepAlive(boolean soKeepAlive) {\r
- this.soKeepAlive = soKeepAlive;\r
- }\r
-\r
- public void setRxBufSize(int rxBufSize) {\r
- this.rxBufSize = rxBufSize;\r
- }\r
-\r
- public void setPerformanceLatency(int performanceLatency) {\r
- this.performanceLatency = performanceLatency;\r
- }\r
-\r
- public void setPerformanceBandwidth(int performanceBandwidth) {\r
- this.performanceBandwidth = performanceBandwidth;\r
- }\r
-\r
- public void setOoBInline(boolean ooBInline) {\r
- this.ooBInline = ooBInline;\r
- }\r
-\r
- public void setDirectBuffer(boolean directBuffer) {\r
- this.directBuffer = directBuffer;\r
- }\r
-\r
- public void setSoLingerOn(boolean soLingerOn) {\r
- this.soLingerOn = soLingerOn;\r
- }\r
-\r
- public void setBufferPool(int bufferPool) {\r
- this.bufferPool = bufferPool;\r
- }\r
-\r
- public void setBufferPoolSize(int bufferPoolSize) {\r
- this.bufferPoolSize = bufferPoolSize;\r
- }\r
-\r
- public void setEventCache(int eventCache) {\r
- this.eventCache = eventCache;\r
- }\r
-\r
- public void setKeyCache(int keyCache) {\r
- this.keyCache = keyCache;\r
- }\r
-\r
- public void setAppReadBufSize(int appReadBufSize) {\r
- this.appReadBufSize = appReadBufSize;\r
- }\r
-\r
- public void setAppWriteBufSize(int appWriteBufSize) {\r
- this.appWriteBufSize = appWriteBufSize;\r
- }\r
-\r
- public void setProcessorCache(int processorCache) {\r
- this.processorCache = processorCache;\r
- }\r
-\r
- public void setTimeoutInterval(long timeoutInterval) {\r
- this.timeoutInterval = timeoutInterval;\r
- }\r
-\r
- public void setDirectBufferPool(int directBufferPool) {\r
- this.bufferPool = directBufferPool;\r
- }\r
-\r
+/*
+ * 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.tomcat.util.net;
+
+import java.net.Socket;
+import java.net.SocketException;
+/**
+ * Properties that can be set in the <Connector> element
+ * in server.xml. All properties are prefixed with "socket."
+ * and are currently only working for the Nio connector
+ *
+ * @author Filip Hanik
+ */
+public class SocketProperties {
+ /**
+ * Enable/disable key cache, this bounded cache stores
+ * KeyAttachment objects to reduce GC
+ * Default is 500
+ * -1 is unlimited
+ * 0 is disabled
+ */
+ protected int keyCache = 500;
+
+ /**
+ * Enable/disable socket processor cache, this bounded cache stores
+ * SocketProcessor objects to reduce GC
+ * Default is 500
+ * -1 is unlimited
+ * 0 is disabled
+ */
+ protected int processorCache = 500;
+
+
+
+ /**
+ * Enable/disable poller event cache, this bounded cache stores
+ * PollerEvent objects to reduce GC for the poller
+ * Default is 500
+ * -1 is unlimited
+ * 0 is disabled
+ * >0 the max number of objects to keep in cache.
+ */
+ protected int eventCache = 500;
+
+
+ /**
+ * Enable/disable direct buffers for the network buffers
+ * Default value is enabled
+ */
+ protected boolean directBuffer = false;
+ /**
+ * Socket receive buffer size in bytes (SO_RCVBUF)
+ * Default value is 25188
+ */
+ protected int rxBufSize = 25188;
+ /**
+ * Socket send buffer size in bytes (SO_SNDBUF)
+ * Default value is 43800
+ */
+ protected int txBufSize = 43800;
+
+ /**
+ * The application read buffer size in bytes.
+ * Default value is rxBufSize
+ */
+ protected int appReadBufSize = 8192;
+
+ /**
+ * The application write buffer size in bytes
+ * Default value is txBufSize
+ */
+ protected int appWriteBufSize = 8192;
+
+ /**
+ * NioChannel pool size for the endpoint,
+ * this value is how many channels
+ * -1 means unlimited cached, 0 means no cache
+ * Default value is 500
+ */
+ protected int bufferPool = 500;
+
+
+ /**
+ * Buffer pool size in bytes to be cached
+ * -1 means unlimited, 0 means no cache
+ * Default value is 100MB (1024*1024*100 bytes)
+ */
+ protected int bufferPoolSize = 1024*1024*100;
+
+ /**
+ * TCP_NO_DELAY option, default is true
+ */
+ protected boolean tcpNoDelay = true;
+ /**
+ * SO_KEEPALIVE option, default is false
+ */
+ protected boolean soKeepAlive = false;
+ /**
+ * OOBINLINE option, default is true
+ */
+ protected boolean ooBInline = true;
+ /**
+ * SO_REUSEADDR option, default is true
+ */
+ protected boolean soReuseAddress = true;
+ /**
+ * SO_LINGER option, default is true, paired with the <code>soLingerTime</code> value
+ */
+ protected boolean soLingerOn = true;
+ /**
+ * SO_LINGER option, default is 25 seconds.
+ */
+ protected int soLingerTime = 25;
+ /**
+ * SO_TIMEOUT option, default is 5000 milliseconds
+ */
+ protected int soTimeout = 5000;
+ /**
+ * Traffic class option, value between 0 and 255
+ * IPTOS_LOWCOST (0x02)
+ * IPTOS_RELIABILITY (0x04)
+ * IPTOS_THROUGHPUT (0x08)
+ * IPTOS_LOWDELAY (0x10)
+ * Default value is 0x04 | 0x08 | 0x010
+ */
+ protected int soTrafficClass = 0x04 | 0x08 | 0x010;
+ /**
+ * Performance preferences according to
+ * http://java.sun.com/j2se/1.5.0/docs/api/java/net/Socket.html#setPerformancePreferences(int,%20int,%20int)
+ * Default value is 1
+ */
+ protected int performanceConnectionTime = 1;
+ /**
+ * Performance preferences according to
+ * http://java.sun.com/j2se/1.5.0/docs/api/java/net/Socket.html#setPerformancePreferences(int,%20int,%20int)
+ * Default value is 0
+ */
+ protected int performanceLatency = 0;
+ /**
+ * Performance preferences according to
+ * http://java.sun.com/j2se/1.5.0/docs/api/java/net/Socket.html#setPerformancePreferences(int,%20int,%20int)
+ * Default value is 1
+ */
+ protected int performanceBandwidth = 1;
+
+ /**
+ * The minimum frequency of the timeout interval to avoid the
+ * poller going boinkers during high traffic
+ */
+ protected long timeoutInterval = 1000;
+
+
+ private Socket properties;
+
+ public void setProperties(Socket socket) throws SocketException{
+ socket.setReceiveBufferSize(rxBufSize);
+ socket.setSendBufferSize(txBufSize);
+ socket.setOOBInline(ooBInline);
+ socket.setKeepAlive(soKeepAlive);
+ socket.setPerformancePreferences(performanceConnectionTime,performanceLatency,performanceBandwidth);
+ socket.setReuseAddress(soReuseAddress);
+ socket.setSoLinger(soLingerOn,soLingerTime);
+ socket.setSoTimeout(soTimeout);
+ socket.setTcpNoDelay(tcpNoDelay);
+ socket.setTrafficClass(soTrafficClass);
+ }
+
+ public boolean getDirectBuffer() {
+ return directBuffer;
+ }
+
+ public boolean getOoBInline() {
+ return ooBInline;
+ }
+
+ public int getPerformanceBandwidth() {
+ return performanceBandwidth;
+ }
+
+ public int getPerformanceConnectionTime() {
+ return performanceConnectionTime;
+ }
+
+ public int getPerformanceLatency() {
+ return performanceLatency;
+ }
+
+ public int getRxBufSize() {
+ return rxBufSize;
+ }
+
+ public boolean getSoKeepAlive() {
+ return soKeepAlive;
+ }
+
+ public boolean getSoLingerOn() {
+ return soLingerOn;
+ }
+
+ public int getSoLingerTime() {
+ return soLingerTime;
+ }
+
+ public boolean getSoReuseAddress() {
+ return soReuseAddress;
+ }
+
+ public int getSoTimeout() {
+ return soTimeout;
+ }
+
+ public int getSoTrafficClass() {
+ return soTrafficClass;
+ }
+
+ public boolean getTcpNoDelay() {
+ return tcpNoDelay;
+ }
+
+ public int getTxBufSize() {
+ return txBufSize;
+ }
+
+ public int getBufferPool() {
+ return bufferPool;
+ }
+
+ public int getBufferPoolSize() {
+ return bufferPoolSize;
+ }
+
+ public int getEventCache() {
+ return eventCache;
+ }
+
+ public int getKeyCache() {
+ return keyCache;
+ }
+
+ public Socket getProperties() {
+ return properties;
+ }
+
+ public int getAppReadBufSize() {
+ return appReadBufSize;
+ }
+
+ public int getAppWriteBufSize() {
+ return appWriteBufSize;
+ }
+
+ public int getProcessorCache() {
+ return processorCache;
+ }
+
+ public long getTimeoutInterval() {
+ return timeoutInterval;
+ }
+
+ public int getDirectBufferPool() {
+ return bufferPool;
+ }
+
+ public void setPerformanceConnectionTime(int performanceConnectionTime) {
+ this.performanceConnectionTime = performanceConnectionTime;
+ }
+
+ public void setTxBufSize(int txBufSize) {
+ this.txBufSize = txBufSize;
+ }
+
+ public void setTcpNoDelay(boolean tcpNoDelay) {
+ this.tcpNoDelay = tcpNoDelay;
+ }
+
+ public void setSoTrafficClass(int soTrafficClass) {
+ this.soTrafficClass = soTrafficClass;
+ }
+
+ public void setSoTimeout(int soTimeout) {
+ this.soTimeout = soTimeout;
+ }
+
+ public void setSoReuseAddress(boolean soReuseAddress) {
+ this.soReuseAddress = soReuseAddress;
+ }
+
+ public void setSoLingerTime(int soLingerTime) {
+ this.soLingerTime = soLingerTime;
+ }
+
+ public void setSoKeepAlive(boolean soKeepAlive) {
+ this.soKeepAlive = soKeepAlive;
+ }
+
+ public void setRxBufSize(int rxBufSize) {
+ this.rxBufSize = rxBufSize;
+ }
+
+ public void setPerformanceLatency(int performanceLatency) {
+ this.performanceLatency = performanceLatency;
+ }
+
+ public void setPerformanceBandwidth(int performanceBandwidth) {
+ this.performanceBandwidth = performanceBandwidth;
+ }
+
+ public void setOoBInline(boolean ooBInline) {
+ this.ooBInline = ooBInline;
+ }
+
+ public void setDirectBuffer(boolean directBuffer) {
+ this.directBuffer = directBuffer;
+ }
+
+ public void setSoLingerOn(boolean soLingerOn) {
+ this.soLingerOn = soLingerOn;
+ }
+
+ public void setBufferPool(int bufferPool) {
+ this.bufferPool = bufferPool;
+ }
+
+ public void setBufferPoolSize(int bufferPoolSize) {
+ this.bufferPoolSize = bufferPoolSize;
+ }
+
+ public void setEventCache(int eventCache) {
+ this.eventCache = eventCache;
+ }
+
+ public void setKeyCache(int keyCache) {
+ this.keyCache = keyCache;
+ }
+
+ public void setAppReadBufSize(int appReadBufSize) {
+ this.appReadBufSize = appReadBufSize;
+ }
+
+ public void setAppWriteBufSize(int appWriteBufSize) {
+ this.appWriteBufSize = appWriteBufSize;
+ }
+
+ public void setProcessorCache(int processorCache) {
+ this.processorCache = processorCache;
+ }
+
+ public void setTimeoutInterval(long timeoutInterval) {
+ this.timeoutInterval = timeoutInterval;
+ }
+
+ public void setDirectBufferPool(int directBufferPool) {
+ this.bufferPool = directBufferPool;
+ }
+
}
\ No newline at end of file
-/*\r
- * Licensed to the Apache Software Foundation (ASF) under one or more\r
- * contributor license agreements. See the NOTICE file distributed with\r
- * this work for additional information regarding copyright ownership.\r
- * The ASF licenses this file to You under the Apache License, Version 2.0\r
- * (the "License"); you may not use this file except in compliance with\r
- * the License. You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- */\r
-package org.apache.catalina.tribes.test.interceptors;\r
-\r
-import org.apache.catalina.tribes.Channel;\r
-import org.apache.catalina.tribes.Member;\r
-import org.apache.catalina.tribes.group.GroupChannel;\r
-import org.apache.catalina.tribes.group.interceptors.NonBlockingCoordinator;\r
-import org.apache.catalina.tribes.group.interceptors.TcpFailureDetector;\r
-import junit.framework.TestCase;\r
-import junit.framework.TestResult;\r
-import junit.framework.TestSuite;\r
-import org.apache.catalina.tribes.ChannelListener;\r
-import java.io.Serializable;\r
-import org.apache.catalina.tribes.group.interceptors.OrderInterceptor;\r
-import org.apache.catalina.tribes.group.ChannelInterceptorBase;\r
-import org.apache.catalina.tribes.ChannelMessage;\r
-import org.apache.catalina.tribes.group.InterceptorPayload;\r
-import org.apache.catalina.tribes.ChannelException;\r
-import java.util.concurrent.atomic.AtomicInteger;\r
-\r
-public class TestOrderInterceptor extends TestCase {\r
-\r
- GroupChannel[] channels = null;\r
- OrderInterceptor[] orderitcs = null;\r
- MangleOrderInterceptor[] mangleitcs = null;\r
- TestListener[] test = null;\r
- int channelCount = 2;\r
- Thread[] threads = null;\r
- protected void setUp() throws Exception {\r
- System.out.println("Setup");\r
- super.setUp();\r
- channels = new GroupChannel[channelCount];\r
- orderitcs = new OrderInterceptor[channelCount];\r
- mangleitcs = new MangleOrderInterceptor[channelCount];\r
- test = new TestListener[channelCount];\r
- threads = new Thread[channelCount];\r
- for ( int i=0; i<channelCount; i++ ) {\r
- channels[i] = new GroupChannel();\r
- \r
- orderitcs[i] = new OrderInterceptor();\r
- mangleitcs[i] = new MangleOrderInterceptor();\r
- orderitcs[i].setExpire(Long.MAX_VALUE);\r
- channels[i].addInterceptor(orderitcs[i]);\r
- channels[i].addInterceptor(mangleitcs[i]);\r
- test[i] = new TestListener(i);\r
- channels[i].addChannelListener(test[i]);\r
- final int j = i;\r
- threads[i] = new Thread() {\r
- public void run() {\r
- try {\r
- channels[j].start(Channel.DEFAULT);\r
- Thread.sleep(50);\r
- } catch (Exception x) {\r
- x.printStackTrace();\r
- }\r
- }\r
- };\r
- }\r
- for ( int i=0; i<channelCount; i++ ) threads[i].start();\r
- for ( int i=0; i<channelCount; i++ ) threads[i].join();\r
- Thread.sleep(1000);\r
- }\r
- \r
- public void testOrder1() throws Exception {\r
- Member[] dest = channels[0].getMembers();\r
- final AtomicInteger value = new AtomicInteger(0);\r
- for ( int i=0; i<100; i++ ) {\r
- channels[0].send(dest,new Integer(value.getAndAdd(1)),0);\r
- }\r
- Thread.sleep(5000);\r
- for ( int i=0; i<test.length; i++ ) {\r
- super.assertEquals(false,test[i].fail);\r
- }\r
- }\r
- \r
- public void testOrder2() throws Exception {\r
- final Member[] dest = channels[0].getMembers();\r
- final AtomicInteger value = new AtomicInteger(0);\r
- Runnable run = new Runnable() {\r
- public void run() {\r
- for (int i = 0; i < 100; i++) {\r
- try {\r
- synchronized (channels[0]) {\r
- channels[0].send(dest, new Integer(value.getAndAdd(1)), 0);\r
- }\r
- }catch ( Exception x ) {\r
- x.printStackTrace();\r
- assertEquals(true,false);\r
- }\r
- }\r
- }\r
- };\r
- Thread[] threads = new Thread[5];\r
- for (int i=0;i<threads.length;i++) {\r
- threads[i] = new Thread(run);\r
- }\r
- for (int i=0;i<threads.length;i++) {\r
- threads[i].start();\r
- }\r
- for (int i=0;i<threads.length;i++) {\r
- threads[i].join();\r
- }\r
- Thread.sleep(5000);\r
- for ( int i=0; i<test.length; i++ ) {\r
- super.assertEquals(false,test[i].fail);\r
- }\r
- }\r
-\r
-\r
- protected void tearDown() throws Exception {\r
- System.out.println("tearDown");\r
- super.tearDown();\r
- for ( int i=0; i<channelCount; i++ ) {\r
- channels[i].stop(Channel.DEFAULT);\r
- }\r
- }\r
- \r
- public static void main(String[] args) throws Exception {\r
- TestSuite suite = new TestSuite();\r
- suite.addTestSuite(TestOrderInterceptor.class);\r
- suite.run(new TestResult());\r
- }\r
- \r
- public static class TestListener implements ChannelListener {\r
- int id = -1;\r
- public TestListener(int id) {\r
- this.id = id;\r
- }\r
- int cnt = 0;\r
- int total = 0;\r
- boolean fail = false;\r
- public synchronized void messageReceived(Serializable msg, Member sender) {\r
- total++;\r
- Integer i = (Integer)msg;\r
- if ( i.intValue() != cnt ) fail = true;\r
- else cnt++;\r
- System.out.println("Listener["+id+"] Message received:"+i+" Count:"+total+" Fail:"+fail);\r
-\r
- }\r
-\r
- public boolean accept(Serializable msg, Member sender) {\r
- return (msg instanceof Integer);\r
- }\r
- }\r
- \r
- public static class MangleOrderInterceptor extends ChannelInterceptorBase {\r
- int cnt = 1;\r
- ChannelMessage hold = null;\r
- Member[] dest = null;\r
- public synchronized void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException {\r
- if ( hold == null ) {\r
- //System.out.println("Skipping message:"+msg);\r
- hold = (ChannelMessage)msg.deepclone();\r
- dest = new Member[destination.length];\r
- System.arraycopy(destination,0,dest,0,dest.length);\r
- } else {\r
- //System.out.println("Sending message:"+msg);\r
- super.sendMessage(destination,msg,payload);\r
- //System.out.println("Sending message:"+hold);\r
- super.sendMessage(dest,hold,null);\r
- hold = null;\r
- dest = null;\r
- }\r
- }\r
- }\r
- \r
- \r
- \r
- \r
-\r
-}\r
+/*
+ * 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.catalina.tribes.test.interceptors;
+
+import org.apache.catalina.tribes.Channel;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.group.GroupChannel;
+import org.apache.catalina.tribes.group.interceptors.NonBlockingCoordinator;
+import org.apache.catalina.tribes.group.interceptors.TcpFailureDetector;
+import junit.framework.TestCase;
+import junit.framework.TestResult;
+import junit.framework.TestSuite;
+import org.apache.catalina.tribes.ChannelListener;
+import java.io.Serializable;
+import org.apache.catalina.tribes.group.interceptors.OrderInterceptor;
+import org.apache.catalina.tribes.group.ChannelInterceptorBase;
+import org.apache.catalina.tribes.ChannelMessage;
+import org.apache.catalina.tribes.group.InterceptorPayload;
+import org.apache.catalina.tribes.ChannelException;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class TestOrderInterceptor extends TestCase {
+
+ GroupChannel[] channels = null;
+ OrderInterceptor[] orderitcs = null;
+ MangleOrderInterceptor[] mangleitcs = null;
+ TestListener[] test = null;
+ int channelCount = 2;
+ Thread[] threads = null;
+ protected void setUp() throws Exception {
+ System.out.println("Setup");
+ super.setUp();
+ channels = new GroupChannel[channelCount];
+ orderitcs = new OrderInterceptor[channelCount];
+ mangleitcs = new MangleOrderInterceptor[channelCount];
+ test = new TestListener[channelCount];
+ threads = new Thread[channelCount];
+ for ( int i=0; i<channelCount; i++ ) {
+ channels[i] = new GroupChannel();
+
+ orderitcs[i] = new OrderInterceptor();
+ mangleitcs[i] = new MangleOrderInterceptor();
+ orderitcs[i].setExpire(Long.MAX_VALUE);
+ channels[i].addInterceptor(orderitcs[i]);
+ channels[i].addInterceptor(mangleitcs[i]);
+ test[i] = new TestListener(i);
+ channels[i].addChannelListener(test[i]);
+ final int j = i;
+ threads[i] = new Thread() {
+ public void run() {
+ try {
+ channels[j].start(Channel.DEFAULT);
+ Thread.sleep(50);
+ } catch (Exception x) {
+ x.printStackTrace();
+ }
+ }
+ };
+ }
+ for ( int i=0; i<channelCount; i++ ) threads[i].start();
+ for ( int i=0; i<channelCount; i++ ) threads[i].join();
+ Thread.sleep(1000);
+ }
+
+ public void testOrder1() throws Exception {
+ Member[] dest = channels[0].getMembers();
+ final AtomicInteger value = new AtomicInteger(0);
+ for ( int i=0; i<100; i++ ) {
+ channels[0].send(dest,new Integer(value.getAndAdd(1)),0);
+ }
+ Thread.sleep(5000);
+ for ( int i=0; i<test.length; i++ ) {
+ super.assertEquals(false,test[i].fail);
+ }
+ }
+
+ public void testOrder2() throws Exception {
+ final Member[] dest = channels[0].getMembers();
+ final AtomicInteger value = new AtomicInteger(0);
+ Runnable run = new Runnable() {
+ public void run() {
+ for (int i = 0; i < 100; i++) {
+ try {
+ synchronized (channels[0]) {
+ channels[0].send(dest, new Integer(value.getAndAdd(1)), 0);
+ }
+ }catch ( Exception x ) {
+ x.printStackTrace();
+ assertEquals(true,false);
+ }
+ }
+ }
+ };
+ Thread[] threads = new Thread[5];
+ for (int i=0;i<threads.length;i++) {
+ threads[i] = new Thread(run);
+ }
+ for (int i=0;i<threads.length;i++) {
+ threads[i].start();
+ }
+ for (int i=0;i<threads.length;i++) {
+ threads[i].join();
+ }
+ Thread.sleep(5000);
+ for ( int i=0; i<test.length; i++ ) {
+ super.assertEquals(false,test[i].fail);
+ }
+ }
+
+
+ protected void tearDown() throws Exception {
+ System.out.println("tearDown");
+ super.tearDown();
+ for ( int i=0; i<channelCount; i++ ) {
+ channels[i].stop(Channel.DEFAULT);
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+ TestSuite suite = new TestSuite();
+ suite.addTestSuite(TestOrderInterceptor.class);
+ suite.run(new TestResult());
+ }
+
+ public static class TestListener implements ChannelListener {
+ int id = -1;
+ public TestListener(int id) {
+ this.id = id;
+ }
+ int cnt = 0;
+ int total = 0;
+ boolean fail = false;
+ public synchronized void messageReceived(Serializable msg, Member sender) {
+ total++;
+ Integer i = (Integer)msg;
+ if ( i.intValue() != cnt ) fail = true;
+ else cnt++;
+ System.out.println("Listener["+id+"] Message received:"+i+" Count:"+total+" Fail:"+fail);
+
+ }
+
+ public boolean accept(Serializable msg, Member sender) {
+ return (msg instanceof Integer);
+ }
+ }
+
+ public static class MangleOrderInterceptor extends ChannelInterceptorBase {
+ int cnt = 1;
+ ChannelMessage hold = null;
+ Member[] dest = null;
+ public synchronized void sendMessage(Member[] destination, ChannelMessage msg, InterceptorPayload payload) throws ChannelException {
+ if ( hold == null ) {
+ //System.out.println("Skipping message:"+msg);
+ hold = (ChannelMessage)msg.deepclone();
+ dest = new Member[destination.length];
+ System.arraycopy(destination,0,dest,0,dest.length);
+ } else {
+ //System.out.println("Sending message:"+msg);
+ super.sendMessage(destination,msg,payload);
+ //System.out.println("Sending message:"+hold);
+ super.sendMessage(dest,hold,null);
+ hold = null;
+ dest = null;
+ }
+ }
+ }
+
+
+
+
+
+}