-/*\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.demos;\r
-\r
-import java.util.Iterator;\r
-import java.util.Properties;\r
-\r
-import org.apache.catalina.tribes.Channel;\r
-import org.apache.catalina.tribes.ManagedChannel;\r
-import org.apache.catalina.tribes.group.GroupChannel;\r
-import org.apache.catalina.tribes.group.interceptors.FragmentationInterceptor;\r
-import org.apache.catalina.tribes.group.interceptors.GzipInterceptor;\r
-import org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor;\r
-import org.apache.catalina.tribes.group.interceptors.OrderInterceptor;\r
-import org.apache.catalina.tribes.membership.McastService;\r
-import org.apache.catalina.tribes.transport.MultiPointSender;\r
-import org.apache.catalina.tribes.transport.ReceiverBase;\r
-import org.apache.catalina.tribes.transport.ReplicationTransmitter;\r
-import org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor;\r
-import org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor;\r
-import org.apache.catalina.tribes.group.interceptors.TcpFailureDetector;\r
-import org.apache.catalina.tribes.group.interceptors.DomainFilterInterceptor;\r
-import java.util.ArrayList;\r
-import org.apache.catalina.tribes.membership.MemberImpl;\r
-import org.apache.catalina.tribes.group.interceptors.StaticMembershipInterceptor;\r
-import org.apache.catalina.tribes.Member;\r
-\r
-/**\r
- * <p>Title: </p>\r
- *\r
- * <p>Description: </p>\r
- *\r
- *\r
- * <p>Company: </p>\r
- *\r
- * @author fhanik\r
- * @version 1.0\r
- */\r
-public class ChannelCreator {\r
- \r
- org.apache.commons.logging.impl.LogFactoryImpl impl=null;\r
- public static StringBuffer usage() {\r
- StringBuffer buf = new StringBuffer();\r
- buf.append("\n\t\t[-bind tcpbindaddress]")\r
- .append("\n\t\t[-tcpselto tcpselectortimeout]") \r
- .append("\n\t\t[-tcpthreads tcpthreadcount]") \r
- .append("\n\t\t[-port tcplistenport]")\r
- .append("\n\t\t[-autobind tcpbindtryrange]")\r
- .append("\n\t\t[-ackto acktimeout]") \r
- .append("\n\t\t[-receiver org.apache.catalina.tribes.transport.nio.NioReceiver|org.apache.catalina.tribes.transport.bio.BioReceiver|]")\r
- .append("\n\t\t[-transport org.apache.catalina.tribes.transport.nio.PooledParallelSender|org.apache.catalina.tribes.transport.bio.PooledMultiSender]")\r
- .append("\n\t\t[-transport.xxx transport specific property]")\r
- .append("\n\t\t[-maddr multicastaddr]")\r
- .append("\n\t\t[-mport multicastport]")\r
- .append("\n\t\t[-mbind multicastbindaddr]")\r
- .append("\n\t\t[-mfreq multicastfrequency]")\r
- .append("\n\t\t[-mdrop multicastdroptime]")\r
- .append("\n\t\t[-gzip]")\r
- .append("\n\t\t[-static hostname:port (-static localhost:9999 -static 127.0.0.1:8888 can be repeated)]")\r
- .append("\n\t\t[-order]")\r
- .append("\n\t\t[-ordersize maxorderqueuesize]")\r
- .append("\n\t\t[-frag]")\r
- .append("\n\t\t[-fragsize maxmsgsize]")\r
- .append("\n\t\t[-throughput]")\r
- .append("\n\t\t[-failuredetect]")\r
- .append("\n\t\t[-async]")\r
- .append("\n\t\t[-asyncsize maxqueuesizeinkilobytes]");\r
- return buf;\r
-\r
- }\r
-\r
- public static Channel createChannel(String[] args) throws Exception {\r
- String bind = "auto";\r
- int port = 4001;\r
- String mbind = null;\r
- boolean gzip = false;\r
- int tcpseltimeout = 5000;\r
- int tcpthreadcount = 4;\r
- int acktimeout = 15000;\r
- String mcastaddr = "228.0.0.5";\r
- int mcastport = 45565;\r
- long mcastfreq = 500;\r
- long mcastdrop = 2000;\r
- boolean order = false;\r
- int ordersize = Integer.MAX_VALUE;\r
- boolean frag = false;\r
- int fragsize = 1024;\r
- int autoBind = 10;\r
- ArrayList staticMembers = new ArrayList();\r
- Properties transportProperties = new Properties();\r
- String transport = "org.apache.catalina.tribes.transport.nio.PooledParallelSender";\r
- String receiver = "org.apache.catalina.tribes.transport.nio.NioReceiver";\r
- boolean async = false;\r
- int asyncsize = 1024*1024*50; //50MB\r
- boolean throughput = false;\r
- boolean failuredetect = false;\r
- \r
- for (int i = 0; i < args.length; i++) {\r
- if ("-bind".equals(args[i])) {\r
- bind = args[++i];\r
- } else if ("-port".equals(args[i])) {\r
- port = Integer.parseInt(args[++i]);\r
- } else if ("-autobind".equals(args[i])) {\r
- autoBind = Integer.parseInt(args[++i]);\r
- } else if ("-tcpselto".equals(args[i])) {\r
- tcpseltimeout = Integer.parseInt(args[++i]);\r
- } else if ("-tcpthreads".equals(args[i])) {\r
- tcpthreadcount = Integer.parseInt(args[++i]);\r
- } else if ("-gzip".equals(args[i])) {\r
- gzip = true;\r
- } else if ("-async".equals(args[i])) {\r
- async = true;\r
- } else if ("-failuredetect".equals(args[i])) {\r
- failuredetect = true;\r
- } else if ("-asyncsize".equals(args[i])) {\r
- asyncsize = Integer.parseInt(args[++i]);\r
- System.out.println("Setting MessageDispatchInterceptor.maxQueueSize="+asyncsize);\r
- } else if ("-static".equals(args[i])) {\r
- String d = args[++i];\r
- String h = d.substring(0,d.indexOf(":"));\r
- String p = d.substring(h.length()+1);\r
- MemberImpl m = new MemberImpl(h,Integer.parseInt(p),2000);\r
- staticMembers.add(m);\r
- } else if ("-throughput".equals(args[i])) {\r
- throughput = true;\r
- } else if ("-order".equals(args[i])) {\r
- order = true;\r
- } else if ("-ordersize".equals(args[i])) {\r
- ordersize = Integer.parseInt(args[++i]);\r
- System.out.println("Setting OrderInterceptor.maxQueue="+ordersize);\r
- } else if ("-frag".equals(args[i])) {\r
- frag = true;\r
- } else if ("-fragsize".equals(args[i])) {\r
- fragsize = Integer.parseInt(args[++i]);\r
- System.out.println("Setting FragmentationInterceptor.maxSize="+fragsize);\r
- } else if ("-ackto".equals(args[i])) {\r
- acktimeout = Integer.parseInt(args[++i]);\r
- } else if ("-transport".equals(args[i])) {\r
- transport = args[++i];\r
- } else if (args[i]!=null && args[i].startsWith("transport.")) {\r
- String key = args[i];\r
- String val = args[++i];\r
- transportProperties.setProperty(key,val);\r
- } else if ("-receiver".equals(args[i])) {\r
- receiver = args[++i];\r
- } else if ("-maddr".equals(args[i])) {\r
- mcastaddr = args[++i];\r
- } else if ("-mport".equals(args[i])) {\r
- mcastport = Integer.parseInt(args[++i]);\r
- } else if ("-mfreq".equals(args[i])) {\r
- mcastfreq = Long.parseLong(args[++i]);\r
- } else if ("-mdrop".equals(args[i])) {\r
- mcastdrop = Long.parseLong(args[++i]);\r
- } else if ("-mbind".equals(args[i])) {\r
- mbind = args[++i];\r
- }\r
- }\r
- \r
- System.out.println("Creating receiver class="+receiver);\r
- Class cl = Class.forName(receiver,true,ChannelCreator.class.getClassLoader());\r
- ReceiverBase rx = (ReceiverBase)cl.newInstance();\r
- rx.setTcpListenAddress(bind);\r
- rx.setTcpListenPort(port);\r
- rx.setTcpSelectorTimeout(tcpseltimeout);\r
- rx.setTcpThreadCount(tcpthreadcount);\r
- rx.getBind();\r
- rx.setRxBufSize(43800);\r
- rx.setTxBufSize(25188);\r
- rx.setAutoBind(autoBind);\r
-\r
- \r
- ReplicationTransmitter ps = new ReplicationTransmitter();\r
- System.out.println("Creating transport class="+transport);\r
- MultiPointSender sender = (MultiPointSender)Class.forName(transport,true,ChannelCreator.class.getClassLoader()).newInstance();\r
- sender.setTimeout(acktimeout);\r
- sender.setMaxRetryAttempts(2);\r
- sender.setRxBufSize(43800);\r
- sender.setTxBufSize(25188);\r
-\r
- Iterator i = transportProperties.keySet().iterator();\r
- while ( i.hasNext() ) {\r
- String key = (String)i.next();\r
- IntrospectionUtils.setProperty(sender,key,transportProperties.getProperty(key));\r
- }\r
- ps.setTransport(sender);\r
-\r
- McastService service = new McastService();\r
- service.setMcastAddr(mcastaddr);\r
- if (mbind != null) service.setMcastBindAddress(mbind);\r
- service.setMcastFrequency(mcastfreq);\r
- service.setMcastDropTime(mcastdrop);\r
- service.setMcastPort(mcastport);\r
-\r
- ManagedChannel channel = new GroupChannel();\r
- channel.setChannelReceiver(rx);\r
- channel.setChannelSender(ps);\r
- channel.setMembershipService(service);\r
- \r
- if ( throughput ) channel.addInterceptor(new ThroughputInterceptor());\r
- if (gzip) channel.addInterceptor(new GzipInterceptor());\r
- if ( frag ) {\r
- FragmentationInterceptor fi = new FragmentationInterceptor();\r
- fi.setMaxSize(fragsize);\r
- channel.addInterceptor(fi);\r
- }\r
- if (order) {\r
- OrderInterceptor oi = new OrderInterceptor();\r
- oi.setMaxQueue(ordersize);\r
- channel.addInterceptor(oi);\r
- }\r
- \r
- if ( async ) {\r
- MessageDispatchInterceptor mi = new MessageDispatch15Interceptor();\r
- mi.setMaxQueueSize(asyncsize);\r
- channel.addInterceptor(mi);\r
- System.out.println("Added MessageDispatchInterceptor");\r
- }\r
- \r
- if ( failuredetect ) {\r
- TcpFailureDetector tcpfi = new TcpFailureDetector();\r
- channel.addInterceptor(tcpfi);\r
- }\r
- if ( staticMembers.size() > 0 ) {\r
- StaticMembershipInterceptor smi = new StaticMembershipInterceptor();\r
- for (int x=0; x<staticMembers.size(); x++ ) {\r
- smi.addStaticMember((Member)staticMembers.get(x));\r
- }\r
- channel.addInterceptor(smi);\r
- }\r
-\r
-\r
- byte[] domain = new byte[] {1,2,3,4,5,6,7,8,9,0};\r
- ((McastService)channel.getMembershipService()).setDomain(domain);\r
- DomainFilterInterceptor filter = new DomainFilterInterceptor();\r
- filter.setDomain(domain);\r
- channel.addInterceptor(filter);\r
- return channel;\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.demos;
+
+import java.util.Iterator;
+import java.util.Properties;
+
+import org.apache.catalina.tribes.Channel;
+import org.apache.catalina.tribes.ManagedChannel;
+import org.apache.catalina.tribes.group.GroupChannel;
+import org.apache.catalina.tribes.group.interceptors.FragmentationInterceptor;
+import org.apache.catalina.tribes.group.interceptors.GzipInterceptor;
+import org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor;
+import org.apache.catalina.tribes.group.interceptors.OrderInterceptor;
+import org.apache.catalina.tribes.membership.McastService;
+import org.apache.catalina.tribes.transport.MultiPointSender;
+import org.apache.catalina.tribes.transport.ReceiverBase;
+import org.apache.catalina.tribes.transport.ReplicationTransmitter;
+import org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor;
+import org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor;
+import org.apache.catalina.tribes.group.interceptors.TcpFailureDetector;
+import org.apache.catalina.tribes.group.interceptors.DomainFilterInterceptor;
+import java.util.ArrayList;
+import org.apache.catalina.tribes.membership.MemberImpl;
+import org.apache.catalina.tribes.group.interceptors.StaticMembershipInterceptor;
+import org.apache.catalina.tribes.Member;
+
+/**
+ * <p>Title: </p>
+ *
+ * <p>Description: </p>
+ *
+ *
+ * <p>Company: </p>
+ *
+ * @author fhanik
+ * @version 1.0
+ */
+public class ChannelCreator {
+
+ org.apache.commons.logging.impl.LogFactoryImpl impl=null;
+ public static StringBuffer usage() {
+ StringBuffer buf = new StringBuffer();
+ buf.append("\n\t\t[-bind tcpbindaddress]")
+ .append("\n\t\t[-tcpselto tcpselectortimeout]")
+ .append("\n\t\t[-tcpthreads tcpthreadcount]")
+ .append("\n\t\t[-port tcplistenport]")
+ .append("\n\t\t[-autobind tcpbindtryrange]")
+ .append("\n\t\t[-ackto acktimeout]")
+ .append("\n\t\t[-receiver org.apache.catalina.tribes.transport.nio.NioReceiver|org.apache.catalina.tribes.transport.bio.BioReceiver|]")
+ .append("\n\t\t[-transport org.apache.catalina.tribes.transport.nio.PooledParallelSender|org.apache.catalina.tribes.transport.bio.PooledMultiSender]")
+ .append("\n\t\t[-transport.xxx transport specific property]")
+ .append("\n\t\t[-maddr multicastaddr]")
+ .append("\n\t\t[-mport multicastport]")
+ .append("\n\t\t[-mbind multicastbindaddr]")
+ .append("\n\t\t[-mfreq multicastfrequency]")
+ .append("\n\t\t[-mdrop multicastdroptime]")
+ .append("\n\t\t[-gzip]")
+ .append("\n\t\t[-static hostname:port (-static localhost:9999 -static 127.0.0.1:8888 can be repeated)]")
+ .append("\n\t\t[-order]")
+ .append("\n\t\t[-ordersize maxorderqueuesize]")
+ .append("\n\t\t[-frag]")
+ .append("\n\t\t[-fragsize maxmsgsize]")
+ .append("\n\t\t[-throughput]")
+ .append("\n\t\t[-failuredetect]")
+ .append("\n\t\t[-async]")
+ .append("\n\t\t[-asyncsize maxqueuesizeinkilobytes]");
+ return buf;
+
+ }
+
+ public static Channel createChannel(String[] args) throws Exception {
+ String bind = "auto";
+ int port = 4001;
+ String mbind = null;
+ boolean gzip = false;
+ int tcpseltimeout = 5000;
+ int tcpthreadcount = 4;
+ int acktimeout = 15000;
+ String mcastaddr = "228.0.0.5";
+ int mcastport = 45565;
+ long mcastfreq = 500;
+ long mcastdrop = 2000;
+ boolean order = false;
+ int ordersize = Integer.MAX_VALUE;
+ boolean frag = false;
+ int fragsize = 1024;
+ int autoBind = 10;
+ ArrayList staticMembers = new ArrayList();
+ Properties transportProperties = new Properties();
+ String transport = "org.apache.catalina.tribes.transport.nio.PooledParallelSender";
+ String receiver = "org.apache.catalina.tribes.transport.nio.NioReceiver";
+ boolean async = false;
+ int asyncsize = 1024*1024*50; //50MB
+ boolean throughput = false;
+ boolean failuredetect = false;
+
+ for (int i = 0; i < args.length; i++) {
+ if ("-bind".equals(args[i])) {
+ bind = args[++i];
+ } else if ("-port".equals(args[i])) {
+ port = Integer.parseInt(args[++i]);
+ } else if ("-autobind".equals(args[i])) {
+ autoBind = Integer.parseInt(args[++i]);
+ } else if ("-tcpselto".equals(args[i])) {
+ tcpseltimeout = Integer.parseInt(args[++i]);
+ } else if ("-tcpthreads".equals(args[i])) {
+ tcpthreadcount = Integer.parseInt(args[++i]);
+ } else if ("-gzip".equals(args[i])) {
+ gzip = true;
+ } else if ("-async".equals(args[i])) {
+ async = true;
+ } else if ("-failuredetect".equals(args[i])) {
+ failuredetect = true;
+ } else if ("-asyncsize".equals(args[i])) {
+ asyncsize = Integer.parseInt(args[++i]);
+ System.out.println("Setting MessageDispatchInterceptor.maxQueueSize="+asyncsize);
+ } else if ("-static".equals(args[i])) {
+ String d = args[++i];
+ String h = d.substring(0,d.indexOf(":"));
+ String p = d.substring(h.length()+1);
+ MemberImpl m = new MemberImpl(h,Integer.parseInt(p),2000);
+ staticMembers.add(m);
+ } else if ("-throughput".equals(args[i])) {
+ throughput = true;
+ } else if ("-order".equals(args[i])) {
+ order = true;
+ } else if ("-ordersize".equals(args[i])) {
+ ordersize = Integer.parseInt(args[++i]);
+ System.out.println("Setting OrderInterceptor.maxQueue="+ordersize);
+ } else if ("-frag".equals(args[i])) {
+ frag = true;
+ } else if ("-fragsize".equals(args[i])) {
+ fragsize = Integer.parseInt(args[++i]);
+ System.out.println("Setting FragmentationInterceptor.maxSize="+fragsize);
+ } else if ("-ackto".equals(args[i])) {
+ acktimeout = Integer.parseInt(args[++i]);
+ } else if ("-transport".equals(args[i])) {
+ transport = args[++i];
+ } else if (args[i]!=null && args[i].startsWith("transport.")) {
+ String key = args[i];
+ String val = args[++i];
+ transportProperties.setProperty(key,val);
+ } else if ("-receiver".equals(args[i])) {
+ receiver = args[++i];
+ } else if ("-maddr".equals(args[i])) {
+ mcastaddr = args[++i];
+ } else if ("-mport".equals(args[i])) {
+ mcastport = Integer.parseInt(args[++i]);
+ } else if ("-mfreq".equals(args[i])) {
+ mcastfreq = Long.parseLong(args[++i]);
+ } else if ("-mdrop".equals(args[i])) {
+ mcastdrop = Long.parseLong(args[++i]);
+ } else if ("-mbind".equals(args[i])) {
+ mbind = args[++i];
+ }
+ }
+
+ System.out.println("Creating receiver class="+receiver);
+ Class cl = Class.forName(receiver,true,ChannelCreator.class.getClassLoader());
+ ReceiverBase rx = (ReceiverBase)cl.newInstance();
+ rx.setTcpListenAddress(bind);
+ rx.setTcpListenPort(port);
+ rx.setTcpSelectorTimeout(tcpseltimeout);
+ rx.setTcpThreadCount(tcpthreadcount);
+ rx.getBind();
+ rx.setRxBufSize(43800);
+ rx.setTxBufSize(25188);
+ rx.setAutoBind(autoBind);
+
+
+ ReplicationTransmitter ps = new ReplicationTransmitter();
+ System.out.println("Creating transport class="+transport);
+ MultiPointSender sender = (MultiPointSender)Class.forName(transport,true,ChannelCreator.class.getClassLoader()).newInstance();
+ sender.setTimeout(acktimeout);
+ sender.setMaxRetryAttempts(2);
+ sender.setRxBufSize(43800);
+ sender.setTxBufSize(25188);
+
+ Iterator i = transportProperties.keySet().iterator();
+ while ( i.hasNext() ) {
+ String key = (String)i.next();
+ IntrospectionUtils.setProperty(sender,key,transportProperties.getProperty(key));
+ }
+ ps.setTransport(sender);
+
+ McastService service = new McastService();
+ service.setMcastAddr(mcastaddr);
+ if (mbind != null) service.setMcastBindAddress(mbind);
+ service.setMcastFrequency(mcastfreq);
+ service.setMcastDropTime(mcastdrop);
+ service.setMcastPort(mcastport);
+
+ ManagedChannel channel = new GroupChannel();
+ channel.setChannelReceiver(rx);
+ channel.setChannelSender(ps);
+ channel.setMembershipService(service);
+
+ if ( throughput ) channel.addInterceptor(new ThroughputInterceptor());
+ if (gzip) channel.addInterceptor(new GzipInterceptor());
+ if ( frag ) {
+ FragmentationInterceptor fi = new FragmentationInterceptor();
+ fi.setMaxSize(fragsize);
+ channel.addInterceptor(fi);
+ }
+ if (order) {
+ OrderInterceptor oi = new OrderInterceptor();
+ oi.setMaxQueue(ordersize);
+ channel.addInterceptor(oi);
+ }
+
+ if ( async ) {
+ MessageDispatchInterceptor mi = new MessageDispatch15Interceptor();
+ mi.setMaxQueueSize(asyncsize);
+ channel.addInterceptor(mi);
+ System.out.println("Added MessageDispatchInterceptor");
+ }
+
+ if ( failuredetect ) {
+ TcpFailureDetector tcpfi = new TcpFailureDetector();
+ channel.addInterceptor(tcpfi);
+ }
+ if ( staticMembers.size() > 0 ) {
+ StaticMembershipInterceptor smi = new StaticMembershipInterceptor();
+ for (int x=0; x<staticMembers.size(); x++ ) {
+ smi.addStaticMember((Member)staticMembers.get(x));
+ }
+ channel.addInterceptor(smi);
+ }
+
+
+ byte[] domain = new byte[] {1,2,3,4,5,6,7,8,9,0};
+ ((McastService)channel.getMembershipService()).setDomain(domain);
+ DomainFilterInterceptor filter = new DomainFilterInterceptor();
+ filter.setDomain(domain);
+ channel.addInterceptor(filter);
+ return channel;
+ }
+
}
\ 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.demos;\r
-\r
-import java.io.File;\r
-import java.io.FilenameFilter;\r
-import java.io.IOException;\r
-import java.lang.reflect.InvocationTargetException;\r
-import java.lang.reflect.Method;\r
-import java.net.InetAddress;\r
-import java.net.MalformedURLException;\r
-import java.net.URL;\r
-import java.net.UnknownHostException;\r
-import java.util.Hashtable;\r
-import java.util.StringTokenizer;\r
-import java.util.Vector;\r
-\r
-// Depends: JDK1.1\r
-\r
-/**\r
- * Utils for introspection and reflection\r
- */\r
-public final class IntrospectionUtils {\r
-\r
-\r
- private static org.apache.commons.logging.Log log=\r
- org.apache.commons.logging.LogFactory.getLog( IntrospectionUtils.class );\r
-\r
- /**\r
- * Call execute() - any ant-like task should work\r
- */\r
- public static void execute(Object proxy, String method) throws Exception {\r
- Method executeM = null;\r
- Class c = proxy.getClass();\r
- Class params[] = new Class[0];\r
- // params[0]=args.getClass();\r
- executeM = findMethod(c, method, params);\r
- if (executeM == null) {\r
- throw new RuntimeException("No execute in " + proxy.getClass());\r
- }\r
- executeM.invoke(proxy, (Object[]) null);//new Object[] { args });\r
- }\r
-\r
- /**\r
- * Call void setAttribute( String ,Object )\r
- */\r
- public static void setAttribute(Object proxy, String n, Object v)\r
- throws Exception {\r
- if (proxy instanceof AttributeHolder) {\r
- ((AttributeHolder) proxy).setAttribute(n, v);\r
- return;\r
- }\r
-\r
- Method executeM = null;\r
- Class c = proxy.getClass();\r
- Class params[] = new Class[2];\r
- params[0] = String.class;\r
- params[1] = Object.class;\r
- executeM = findMethod(c, "setAttribute", params);\r
- if (executeM == null) {\r
- if (log.isDebugEnabled())\r
- log.debug("No setAttribute in " + proxy.getClass());\r
- return;\r
- }\r
- if (false)\r
- if (log.isDebugEnabled())\r
- log.debug("Setting " + n + "=" + v + " in " + proxy);\r
- executeM.invoke(proxy, new Object[] { n, v });\r
- return;\r
- }\r
-\r
- /**\r
- * Call void getAttribute( String )\r
- */\r
- public static Object getAttribute(Object proxy, String n) throws Exception {\r
- Method executeM = null;\r
- Class c = proxy.getClass();\r
- Class params[] = new Class[1];\r
- params[0] = String.class;\r
- executeM = findMethod(c, "getAttribute", params);\r
- if (executeM == null) {\r
- if (log.isDebugEnabled())\r
- log.debug("No getAttribute in " + proxy.getClass());\r
- return null;\r
- }\r
- return executeM.invoke(proxy, new Object[] { n });\r
- }\r
-\r
- /**\r
- * Construct a URLClassLoader. Will compile and work in JDK1.1 too.\r
- */\r
- public static ClassLoader getURLClassLoader(URL urls[], ClassLoader parent) {\r
- try {\r
- Class urlCL = Class.forName("java.net.URLClassLoader");\r
- Class paramT[] = new Class[2];\r
- paramT[0] = urls.getClass();\r
- paramT[1] = ClassLoader.class;\r
- Method m = findMethod(urlCL, "newInstance", paramT);\r
- if (m == null)\r
- return null;\r
-\r
- ClassLoader cl = (ClassLoader) m.invoke(urlCL, new Object[] { urls,\r
- parent });\r
- return cl;\r
- } catch (ClassNotFoundException ex) {\r
- // jdk1.1\r
- return null;\r
- } catch (Exception ex) {\r
- ex.printStackTrace();\r
- return null;\r
- }\r
- }\r
-\r
- public static String guessInstall(String installSysProp,\r
- String homeSysProp, String jarName) {\r
- return guessInstall(installSysProp, homeSysProp, jarName, null);\r
- }\r
-\r
- /**\r
- * Guess a product install/home by analyzing the class path. It works for\r
- * product using the pattern: lib/executable.jar or if executable.jar is\r
- * included in classpath by a shell script. ( java -jar also works )\r
- *\r
- * Insures both "install" and "home" System properties are set. If either or\r
- * both System properties are unset, "install" and "home" will be set to the\r
- * same value. This value will be the other System property that is set, or\r
- * the guessed value if neither is set.\r
- */\r
- public static String guessInstall(String installSysProp,\r
- String homeSysProp, String jarName, String classFile) {\r
- String install = null;\r
- String home = null;\r
-\r
- if (installSysProp != null)\r
- install = System.getProperty(installSysProp);\r
-\r
- if (homeSysProp != null)\r
- home = System.getProperty(homeSysProp);\r
-\r
- if (install != null) {\r
- if (home == null)\r
- System.getProperties().put(homeSysProp, install);\r
- return install;\r
- }\r
-\r
- // Find the directory where jarName.jar is located\r
-\r
- String cpath = System.getProperty("java.class.path");\r
- String pathSep = System.getProperty("path.separator");\r
- StringTokenizer st = new StringTokenizer(cpath, pathSep);\r
- while (st.hasMoreTokens()) {\r
- String path = st.nextToken();\r
- // log( "path " + path );\r
- if (path.endsWith(jarName)) {\r
- home = path.substring(0, path.length() - jarName.length());\r
- try {\r
- if ("".equals(home)) {\r
- home = new File("./").getCanonicalPath();\r
- } else if (home.endsWith(File.separator)) {\r
- home = home.substring(0, home.length() - 1);\r
- }\r
- File f = new File(home);\r
- String parentDir = f.getParent();\r
- if (parentDir == null)\r
- parentDir = home; // unix style\r
- File f1 = new File(parentDir);\r
- install = f1.getCanonicalPath();\r
- if (installSysProp != null)\r
- System.getProperties().put(installSysProp, install);\r
- if (home == null && homeSysProp != null)\r
- System.getProperties().put(homeSysProp, install);\r
- return install;\r
- } catch (Exception ex) {\r
- ex.printStackTrace();\r
- }\r
- } else {\r
- String fname = path + (path.endsWith("/") ? "" : "/")\r
- + classFile;\r
- if (new File(fname).exists()) {\r
- try {\r
- File f = new File(path);\r
- String parentDir = f.getParent();\r
- if (parentDir == null)\r
- parentDir = path; // unix style\r
- File f1 = new File(parentDir);\r
- install = f1.getCanonicalPath();\r
- if (installSysProp != null)\r
- System.getProperties().put(installSysProp, install);\r
- if (home == null && homeSysProp != null)\r
- System.getProperties().put(homeSysProp, install);\r
- return install;\r
- } catch (Exception ex) {\r
- ex.printStackTrace();\r
- }\r
- }\r
- }\r
- }\r
-\r
- // if install directory can't be found, use home as the default\r
- if (home != null) {\r
- System.getProperties().put(installSysProp, home);\r
- return home;\r
- }\r
-\r
- return null;\r
- }\r
-\r
- /**\r
- * Debug method, display the classpath\r
- */\r
- public static void displayClassPath(String msg, URL[] cp) {\r
- if (log.isDebugEnabled()) {\r
- log.debug(msg);\r
- for (int i = 0; i < cp.length; i++) {\r
- log.debug(cp[i].getFile());\r
- }\r
- }\r
- }\r
-\r
- public static String PATH_SEPARATOR = System.getProperty("path.separator");\r
-\r
- /**\r
- * Adds classpath entries from a vector of URL's to the "tc_path_add" System\r
- * property. This System property lists the classpath entries common to web\r
- * applications. This System property is currently used by Jasper when its\r
- * JSP servlet compiles the Java file for a JSP.\r
- */\r
- public static String classPathAdd(URL urls[], String cp) {\r
- if (urls == null)\r
- return cp;\r
-\r
- for (int i = 0; i < urls.length; i++) {\r
- if (cp != null)\r
- cp += PATH_SEPARATOR + urls[i].getFile();\r
- else\r
- cp = urls[i].getFile();\r
- }\r
- return cp;\r
- }\r
-\r
- /**\r
- * Find a method with the right name If found, call the method ( if param is\r
- * int or boolean we'll convert value to the right type before) - that means\r
- * you can have setDebug(1).\r
- */\r
- public static void setProperty(Object o, String name, String value) {\r
- if (dbg > 1)\r
- d("setProperty(" + o.getClass() + " " + name + "=" + value + ")");\r
-\r
- String setter = "set" + capitalize(name);\r
-\r
- try {\r
- Method methods[] = findMethods(o.getClass());\r
- Method setPropertyMethod = null;\r
-\r
- // First, the ideal case - a setFoo( String ) method\r
- for (int i = 0; i < methods.length; i++) {\r
- Class paramT[] = methods[i].getParameterTypes();\r
- if (setter.equals(methods[i].getName()) && paramT.length == 1\r
- && "java.lang.String".equals(paramT[0].getName())) {\r
-\r
- methods[i].invoke(o, new Object[] { value });\r
- return;\r
- }\r
- }\r
-\r
- // Try a setFoo ( int ) or ( boolean )\r
- for (int i = 0; i < methods.length; i++) {\r
- boolean ok = true;\r
- if (setter.equals(methods[i].getName())\r
- && methods[i].getParameterTypes().length == 1) {\r
-\r
- // match - find the type and invoke it\r
- Class paramType = methods[i].getParameterTypes()[0];\r
- Object params[] = new Object[1];\r
-\r
- // Try a setFoo ( int )\r
- if ("java.lang.Integer".equals(paramType.getName())\r
- || "int".equals(paramType.getName())) {\r
- try {\r
- params[0] = new Integer(value);\r
- } catch (NumberFormatException ex) {\r
- ok = false;\r
- }\r
- // Try a setFoo ( long )\r
- }else if ("java.lang.Long".equals(paramType.getName())\r
- || "long".equals(paramType.getName())) {\r
- try {\r
- params[0] = new Long(value);\r
- } catch (NumberFormatException ex) {\r
- ok = false;\r
- }\r
-\r
- // Try a setFoo ( boolean )\r
- } else if ("java.lang.Boolean".equals(paramType.getName())\r
- || "boolean".equals(paramType.getName())) {\r
- params[0] = new Boolean(value);\r
-\r
- // Try a setFoo ( InetAddress )\r
- } else if ("java.net.InetAddress".equals(paramType\r
- .getName())) {\r
- try {\r
- params[0] = InetAddress.getByName(value);\r
- } catch (UnknownHostException exc) {\r
- d("Unable to resolve host name:" + value);\r
- ok = false;\r
- }\r
-\r
- // Unknown type\r
- } else {\r
- d("Unknown type " + paramType.getName());\r
- }\r
-\r
- if (ok) {\r
- methods[i].invoke(o, params);\r
- return;\r
- }\r
- }\r
-\r
- // save "setProperty" for later\r
- if ("setProperty".equals(methods[i].getName())) {\r
- setPropertyMethod = methods[i];\r
- }\r
- }\r
-\r
- // Ok, no setXXX found, try a setProperty("name", "value")\r
- if (setPropertyMethod != null) {\r
- Object params[] = new Object[2];\r
- params[0] = name;\r
- params[1] = value;\r
- setPropertyMethod.invoke(o, params);\r
- }\r
-\r
- } catch (IllegalArgumentException ex2) {\r
- log.warn("IAE " + o + " " + name + " " + value, ex2);\r
- } catch (SecurityException ex1) {\r
- if (dbg > 0)\r
- d("SecurityException for " + o.getClass() + " " + name + "="\r
- + value + ")");\r
- if (dbg > 1)\r
- ex1.printStackTrace();\r
- } catch (IllegalAccessException iae) {\r
- if (dbg > 0)\r
- d("IllegalAccessException for " + o.getClass() + " " + name\r
- + "=" + value + ")");\r
- if (dbg > 1)\r
- iae.printStackTrace();\r
- } catch (InvocationTargetException ie) {\r
- if (dbg > 0)\r
- d("InvocationTargetException for " + o.getClass() + " " + name\r
- + "=" + value + ")");\r
- if (dbg > 1)\r
- ie.printStackTrace();\r
- }\r
- }\r
-\r
- public static Object getProperty(Object o, String name) {\r
- String getter = "get" + capitalize(name);\r
- String isGetter = "is" + capitalize(name);\r
-\r
- try {\r
- Method methods[] = findMethods(o.getClass());\r
- Method getPropertyMethod = null;\r
-\r
- // First, the ideal case - a getFoo() method\r
- for (int i = 0; i < methods.length; i++) {\r
- Class paramT[] = methods[i].getParameterTypes();\r
- if (getter.equals(methods[i].getName()) && paramT.length == 0) {\r
- return methods[i].invoke(o, (Object[]) null);\r
- }\r
- if (isGetter.equals(methods[i].getName()) && paramT.length == 0) {\r
- return methods[i].invoke(o, (Object[]) null);\r
- }\r
-\r
- if ("getProperty".equals(methods[i].getName())) {\r
- getPropertyMethod = methods[i];\r
- }\r
- }\r
-\r
- // Ok, no setXXX found, try a getProperty("name")\r
- if (getPropertyMethod != null) {\r
- Object params[] = new Object[1];\r
- params[0] = name;\r
- return getPropertyMethod.invoke(o, params);\r
- }\r
-\r
- } catch (IllegalArgumentException ex2) {\r
- log.warn("IAE " + o + " " + name, ex2);\r
- } catch (SecurityException ex1) {\r
- if (dbg > 0)\r
- d("SecurityException for " + o.getClass() + " " + name + ")");\r
- if (dbg > 1)\r
- ex1.printStackTrace();\r
- } catch (IllegalAccessException iae) {\r
- if (dbg > 0)\r
- d("IllegalAccessException for " + o.getClass() + " " + name\r
- + ")");\r
- if (dbg > 1)\r
- iae.printStackTrace();\r
- } catch (InvocationTargetException ie) {\r
- if (dbg > 0)\r
- d("InvocationTargetException for " + o.getClass() + " " + name\r
- + ")");\r
- if (dbg > 1)\r
- ie.printStackTrace();\r
- }\r
- return null;\r
- }\r
-\r
- /**\r
- */\r
- public static void setProperty(Object o, String name) {\r
- String setter = "set" + capitalize(name);\r
- try {\r
- Method methods[] = findMethods(o.getClass());\r
- Method setPropertyMethod = null;\r
- // find setFoo() method\r
- for (int i = 0; i < methods.length; i++) {\r
- Class paramT[] = methods[i].getParameterTypes();\r
- if (setter.equals(methods[i].getName()) && paramT.length == 0) {\r
- methods[i].invoke(o, new Object[] {});\r
- return;\r
- }\r
- }\r
- } catch (Exception ex1) {\r
- if (dbg > 0)\r
- d("Exception for " + o.getClass() + " " + name);\r
- if (dbg > 1)\r
- ex1.printStackTrace();\r
- }\r
- }\r
-\r
- /**\r
- * Replace ${NAME} with the property value\r
- *\r
- * @deprecated Use the explicit method\r
- */\r
- public static String replaceProperties(String value, Object getter) {\r
- if (getter instanceof Hashtable)\r
- return replaceProperties(value, (Hashtable) getter, null);\r
-\r
- if (getter instanceof PropertySource) {\r
- PropertySource src[] = new PropertySource[] { (PropertySource) getter };\r
- return replaceProperties(value, null, src);\r
- }\r
- return value;\r
- }\r
-\r
- /**\r
- * Replace ${NAME} with the property value\r
- */\r
- public static String replaceProperties(String value, Hashtable staticProp,\r
- PropertySource dynamicProp[]) {\r
- StringBuffer sb = new StringBuffer();\r
- int prev = 0;\r
- // assert value!=nil\r
- int pos;\r
- while ((pos = value.indexOf("$", prev)) >= 0) {\r
- if (pos > 0) {\r
- sb.append(value.substring(prev, pos));\r
- }\r
- if (pos == (value.length() - 1)) {\r
- sb.append('$');\r
- prev = pos + 1;\r
- } else if (value.charAt(pos + 1) != '{') {\r
- sb.append('$');\r
- prev = pos + 1; // XXX\r
- } else {\r
- int endName = value.indexOf('}', pos);\r
- if (endName < 0) {\r
- sb.append(value.substring(pos));\r
- prev = value.length();\r
- continue;\r
- }\r
- String n = value.substring(pos + 2, endName);\r
- String v = null;\r
- if (staticProp != null) {\r
- v = (String) ((Hashtable) staticProp).get(n);\r
- }\r
- if (v == null && dynamicProp != null) {\r
- for (int i = 0; i < dynamicProp.length; i++) {\r
- v = dynamicProp[i].getProperty(n);\r
- if (v != null) {\r
- break;\r
- }\r
- }\r
- }\r
- if (v == null)\r
- v = "${" + n + "}";\r
-\r
- sb.append(v);\r
- prev = endName + 1;\r
- }\r
- }\r
- if (prev < value.length())\r
- sb.append(value.substring(prev));\r
- return sb.toString();\r
- }\r
-\r
- /**\r
- * Reverse of Introspector.decapitalize\r
- */\r
- public static String capitalize(String name) {\r
- if (name == null || name.length() == 0) {\r
- return name;\r
- }\r
- char chars[] = name.toCharArray();\r
- chars[0] = Character.toUpperCase(chars[0]);\r
- return new String(chars);\r
- }\r
-\r
- public static String unCapitalize(String name) {\r
- if (name == null || name.length() == 0) {\r
- return name;\r
- }\r
- char chars[] = name.toCharArray();\r
- chars[0] = Character.toLowerCase(chars[0]);\r
- return new String(chars);\r
- }\r
-\r
- // -------------------- Class path tools --------------------\r
-\r
- /**\r
- * Add all the jar files in a dir to the classpath, represented as a Vector\r
- * of URLs.\r
- */\r
- public static void addToClassPath(Vector cpV, String dir) {\r
- try {\r
- String cpComp[] = getFilesByExt(dir, ".jar");\r
- if (cpComp != null) {\r
- int jarCount = cpComp.length;\r
- for (int i = 0; i < jarCount; i++) {\r
- URL url = getURL(dir, cpComp[i]);\r
- if (url != null)\r
- cpV.addElement(url);\r
- }\r
- }\r
- } catch (Exception ex) {\r
- ex.printStackTrace();\r
- }\r
- }\r
-\r
- public static void addToolsJar(Vector v) {\r
- try {\r
- // Add tools.jar in any case\r
- File f = new File(System.getProperty("java.home")\r
- + "/../lib/tools.jar");\r
-\r
- if (!f.exists()) {\r
- // On some systems java.home gets set to the root of jdk.\r
- // That's a bug, but we can work around and be nice.\r
- f = new File(System.getProperty("java.home") + "/lib/tools.jar");\r
- if (f.exists()) {\r
- if (log.isDebugEnabled())\r
- log.debug("Detected strange java.home value "\r
- + System.getProperty("java.home")\r
- + ", it should point to jre");\r
- }\r
- }\r
- URL url = new URL("file", "", f.getAbsolutePath());\r
-\r
- v.addElement(url);\r
- } catch (MalformedURLException ex) {\r
- ex.printStackTrace();\r
- }\r
- }\r
-\r
- /**\r
- * Return all files with a given extension in a dir\r
- */\r
- public static String[] getFilesByExt(String ld, String ext) {\r
- File dir = new File(ld);\r
- String[] names = null;\r
- final String lext = ext;\r
- if (dir.isDirectory()) {\r
- names = dir.list(new FilenameFilter() {\r
- public boolean accept(File d, String name) {\r
- if (name.endsWith(lext)) {\r
- return true;\r
- }\r
- return false;\r
- }\r
- });\r
- }\r
- return names;\r
- }\r
-\r
- /**\r
- * Construct a file url from a file, using a base dir\r
- */\r
- public static URL getURL(String base, String file) {\r
- try {\r
- File baseF = new File(base);\r
- File f = new File(baseF, file);\r
- String path = f.getCanonicalPath();\r
- if (f.isDirectory()) {\r
- path += "/";\r
- }\r
- if (!f.exists())\r
- return null;\r
- return new URL("file", "", path);\r
- } catch (Exception ex) {\r
- ex.printStackTrace();\r
- return null;\r
- }\r
- }\r
-\r
- /**\r
- * Add elements from the classpath <i>cp </i> to a Vector <i>jars </i> as\r
- * file URLs (We use Vector for JDK 1.1 compat).\r
- * <p>\r
- *\r
- * @param jars The jar list\r
- * @param cp a String classpath of directory or jar file elements\r
- * separated by path.separator delimiters.\r
- * @throws IOException If an I/O error occurs\r
- * @throws MalformedURLException Doh ;)\r
- */\r
- public static void addJarsFromClassPath(Vector jars, String cp)\r
- throws IOException, MalformedURLException {\r
- String sep = System.getProperty("path.separator");\r
- String token;\r
- StringTokenizer st;\r
- if (cp != null) {\r
- st = new StringTokenizer(cp, sep);\r
- while (st.hasMoreTokens()) {\r
- File f = new File(st.nextToken());\r
- String path = f.getCanonicalPath();\r
- if (f.isDirectory()) {\r
- path += "/";\r
- }\r
- URL url = new URL("file", "", path);\r
- if (!jars.contains(url)) {\r
- jars.addElement(url);\r
- }\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * Return a URL[] that can be used to construct a class loader\r
- */\r
- public static URL[] getClassPath(Vector v) {\r
- URL[] urls = new URL[v.size()];\r
- for (int i = 0; i < v.size(); i++) {\r
- urls[i] = (URL) v.elementAt(i);\r
- }\r
- return urls;\r
- }\r
-\r
- /**\r
- * Construct a URL classpath from files in a directory, a cpath property,\r
- * and tools.jar.\r
- */\r
- public static URL[] getClassPath(String dir, String cpath,\r
- String cpathProp, boolean addTools) throws IOException,\r
- MalformedURLException {\r
- Vector jarsV = new Vector();\r
- if (dir != null) {\r
- // Add dir/classes first, if it exists\r
- URL url = getURL(dir, "classes");\r
- if (url != null)\r
- jarsV.addElement(url);\r
- addToClassPath(jarsV, dir);\r
- }\r
-\r
- if (cpath != null)\r
- addJarsFromClassPath(jarsV, cpath);\r
-\r
- if (cpathProp != null) {\r
- String cpath1 = System.getProperty(cpathProp);\r
- addJarsFromClassPath(jarsV, cpath1);\r
- }\r
-\r
- if (addTools)\r
- addToolsJar(jarsV);\r
-\r
- return getClassPath(jarsV);\r
- }\r
-\r
- // -------------------- Mapping command line params to setters\r
-\r
- public static boolean processArgs(Object proxy, String args[])\r
- throws Exception {\r
- String args0[] = null;\r
- if (null != findMethod(proxy.getClass(), "getOptions1", new Class[] {})) {\r
- args0 = (String[]) callMethod0(proxy, "getOptions1");\r
- }\r
-\r
- if (args0 == null) {\r
- //args0=findVoidSetters(proxy.getClass());\r
- args0 = findBooleanSetters(proxy.getClass());\r
- }\r
- Hashtable h = null;\r
- if (null != findMethod(proxy.getClass(), "getOptionAliases",\r
- new Class[] {})) {\r
- h = (Hashtable) callMethod0(proxy, "getOptionAliases");\r
- }\r
- return processArgs(proxy, args, args0, null, h);\r
- }\r
-\r
- public static boolean processArgs(Object proxy, String args[],\r
- String args0[], String args1[], Hashtable aliases) throws Exception {\r
- for (int i = 0; i < args.length; i++) {\r
- String arg = args[i];\r
- if (arg.startsWith("-"))\r
- arg = arg.substring(1);\r
- if (aliases != null && aliases.get(arg) != null)\r
- arg = (String) aliases.get(arg);\r
-\r
- if (args0 != null) {\r
- boolean set = false;\r
- for (int j = 0; j < args0.length; j++) {\r
- if (args0[j].equalsIgnoreCase(arg)) {\r
- setProperty(proxy, args0[j], "true");\r
- set = true;\r
- break;\r
- }\r
- }\r
- if (set)\r
- continue;\r
- }\r
- if (args1 != null) {\r
- for (int j = 0; j < args1.length; j++) {\r
- if (args1[j].equalsIgnoreCase(arg)) {\r
- i++;\r
- if (i >= args.length)\r
- return false;\r
- setProperty(proxy, arg, args[i]);\r
- break;\r
- }\r
- }\r
- } else {\r
- // if args1 is not specified,assume all other options have param\r
- i++;\r
- if (i >= args.length)\r
- return false;\r
- setProperty(proxy, arg, args[i]);\r
- }\r
-\r
- }\r
- return true;\r
- }\r
-\r
- // -------------------- other utils --------------------\r
- public static void clear() {\r
- objectMethods.clear();\r
- }\r
-\r
- public static String[] findVoidSetters(Class c) {\r
- Method m[] = findMethods(c);\r
- if (m == null)\r
- return null;\r
- Vector v = new Vector();\r
- for (int i = 0; i < m.length; i++) {\r
- if (m[i].getName().startsWith("set")\r
- && m[i].getParameterTypes().length == 0) {\r
- String arg = m[i].getName().substring(3);\r
- v.addElement(unCapitalize(arg));\r
- }\r
- }\r
- String s[] = new String[v.size()];\r
- for (int i = 0; i < s.length; i++) {\r
- s[i] = (String) v.elementAt(i);\r
- }\r
- return s;\r
- }\r
-\r
- public static String[] findBooleanSetters(Class c) {\r
- Method m[] = findMethods(c);\r
- if (m == null)\r
- return null;\r
- Vector v = new Vector();\r
- for (int i = 0; i < m.length; i++) {\r
- if (m[i].getName().startsWith("set")\r
- && m[i].getParameterTypes().length == 1\r
- && "boolean".equalsIgnoreCase(m[i].getParameterTypes()[0]\r
- .getName())) {\r
- String arg = m[i].getName().substring(3);\r
- v.addElement(unCapitalize(arg));\r
- }\r
- }\r
- String s[] = new String[v.size()];\r
- for (int i = 0; i < s.length; i++) {\r
- s[i] = (String) v.elementAt(i);\r
- }\r
- return s;\r
- }\r
-\r
- static Hashtable objectMethods = new Hashtable();\r
-\r
- public static Method[] findMethods(Class c) {\r
- Method methods[] = (Method[]) objectMethods.get(c);\r
- if (methods != null)\r
- return methods;\r
-\r
- methods = c.getMethods();\r
- objectMethods.put(c, methods);\r
- return methods;\r
- }\r
-\r
- public static Method findMethod(Class c, String name, Class params[]) {\r
- Method methods[] = findMethods(c);\r
- if (methods == null)\r
- return null;\r
- for (int i = 0; i < methods.length; i++) {\r
- if (methods[i].getName().equals(name)) {\r
- Class methodParams[] = methods[i].getParameterTypes();\r
- if (methodParams == null)\r
- if (params == null || params.length == 0)\r
- return methods[i];\r
- if (params == null)\r
- if (methodParams == null || methodParams.length == 0)\r
- return methods[i];\r
- if (params.length != methodParams.length)\r
- continue;\r
- boolean found = true;\r
- for (int j = 0; j < params.length; j++) {\r
- if (params[j] != methodParams[j]) {\r
- found = false;\r
- break;\r
- }\r
- }\r
- if (found)\r
- return methods[i];\r
- }\r
- }\r
- return null;\r
- }\r
-\r
- /** Test if the object implements a particular\r
- * method\r
- */\r
- public static boolean hasHook(Object obj, String methodN) {\r
- try {\r
- Method myMethods[] = findMethods(obj.getClass());\r
- for (int i = 0; i < myMethods.length; i++) {\r
- if (methodN.equals(myMethods[i].getName())) {\r
- // check if it's overriden\r
- Class declaring = myMethods[i].getDeclaringClass();\r
- Class parentOfDeclaring = declaring.getSuperclass();\r
- // this works only if the base class doesn't extend\r
- // another class.\r
-\r
- // if the method is declared in a top level class\r
- // like BaseInterceptor parent is Object, otherwise\r
- // parent is BaseInterceptor or an intermediate class\r
- if (!"java.lang.Object".equals(parentOfDeclaring.getName())) {\r
- return true;\r
- }\r
- }\r
- }\r
- } catch (Exception ex) {\r
- ex.printStackTrace();\r
- }\r
- return false;\r
- }\r
-\r
- public static void callMain(Class c, String args[]) throws Exception {\r
- Class p[] = new Class[1];\r
- p[0] = args.getClass();\r
- Method m = c.getMethod("main", p);\r
- m.invoke(c, new Object[] { args });\r
- }\r
-\r
- public static Object callMethod1(Object target, String methodN,\r
- Object param1, String typeParam1, ClassLoader cl) throws Exception {\r
- if (target == null || param1 == null) {\r
- d("Assert: Illegal params " + target + " " + param1);\r
- }\r
- if (dbg > 0)\r
- d("callMethod1 " + target.getClass().getName() + " "\r
- + param1.getClass().getName() + " " + typeParam1);\r
-\r
- Class params[] = new Class[1];\r
- if (typeParam1 == null)\r
- params[0] = param1.getClass();\r
- else\r
- params[0] = cl.loadClass(typeParam1);\r
- Method m = findMethod(target.getClass(), methodN, params);\r
- if (m == null)\r
- throw new NoSuchMethodException(target.getClass().getName() + " "\r
- + methodN);\r
- return m.invoke(target, new Object[] { param1 });\r
- }\r
-\r
- public static Object callMethod0(Object target, String methodN)\r
- throws Exception {\r
- if (target == null) {\r
- d("Assert: Illegal params " + target);\r
- return null;\r
- }\r
- if (dbg > 0)\r
- d("callMethod0 " + target.getClass().getName() + "." + methodN);\r
-\r
- Class params[] = new Class[0];\r
- Method m = findMethod(target.getClass(), methodN, params);\r
- if (m == null)\r
- throw new NoSuchMethodException(target.getClass().getName() + " "\r
- + methodN);\r
- return m.invoke(target, emptyArray);\r
- }\r
-\r
- static Object[] emptyArray = new Object[] {};\r
-\r
- public static Object callMethodN(Object target, String methodN,\r
- Object params[], Class typeParams[]) throws Exception {\r
- Method m = null;\r
- m = findMethod(target.getClass(), methodN, typeParams);\r
- if (m == null) {\r
- d("Can't find method " + methodN + " in " + target + " CLASS "\r
- + target.getClass());\r
- return null;\r
- }\r
- Object o = m.invoke(target, params);\r
-\r
- if (dbg > 0) {\r
- // debug\r
- StringBuffer sb = new StringBuffer();\r
- sb.append("" + target.getClass().getName() + "." + methodN + "( ");\r
- for (int i = 0; i < params.length; i++) {\r
- if (i > 0)\r
- sb.append(", ");\r
- sb.append(params[i]);\r
- }\r
- sb.append(")");\r
- d(sb.toString());\r
- }\r
- return o;\r
- }\r
-\r
- public static Object convert(String object, Class paramType) {\r
- Object result = null;\r
- if ("java.lang.String".equals(paramType.getName())) {\r
- result = object;\r
- } else if ("java.lang.Integer".equals(paramType.getName())\r
- || "int".equals(paramType.getName())) {\r
- try {\r
- result = new Integer(object);\r
- } catch (NumberFormatException ex) {\r
- }\r
- // Try a setFoo ( boolean )\r
- } else if ("java.lang.Boolean".equals(paramType.getName())\r
- || "boolean".equals(paramType.getName())) {\r
- result = new Boolean(object);\r
-\r
- // Try a setFoo ( InetAddress )\r
- } else if ("java.net.InetAddress".equals(paramType\r
- .getName())) {\r
- try {\r
- result = InetAddress.getByName(object);\r
- } catch (UnknownHostException exc) {\r
- d("Unable to resolve host name:" + object);\r
- }\r
-\r
- // Unknown type\r
- } else {\r
- d("Unknown type " + paramType.getName());\r
- }\r
- if (result == null) {\r
- throw new IllegalArgumentException("Can't convert argument: " + object);\r
- }\r
- return result;\r
- }\r
-\r
- // -------------------- Get property --------------------\r
- // This provides a layer of abstraction\r
-\r
- public static interface PropertySource {\r
-\r
- public String getProperty(String key);\r
-\r
- }\r
-\r
- public static interface AttributeHolder {\r
-\r
- public void setAttribute(String key, Object o);\r
-\r
- }\r
-\r
- // debug --------------------\r
- static final int dbg = 0;\r
-\r
- static void d(String s) {\r
- if (log.isDebugEnabled())\r
- log.debug("IntrospectionUtils: " + s);\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.demos;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.UnknownHostException;
+import java.util.Hashtable;
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+// Depends: JDK1.1
+
+/**
+ * Utils for introspection and reflection
+ */
+public final class IntrospectionUtils {
+
+
+ private static org.apache.commons.logging.Log log=
+ org.apache.commons.logging.LogFactory.getLog( IntrospectionUtils.class );
+
+ /**
+ * Call execute() - any ant-like task should work
+ */
+ public static void execute(Object proxy, String method) throws Exception {
+ Method executeM = null;
+ Class c = proxy.getClass();
+ Class params[] = new Class[0];
+ // params[0]=args.getClass();
+ executeM = findMethod(c, method, params);
+ if (executeM == null) {
+ throw new RuntimeException("No execute in " + proxy.getClass());
+ }
+ executeM.invoke(proxy, (Object[]) null);//new Object[] { args });
+ }
+
+ /**
+ * Call void setAttribute( String ,Object )
+ */
+ public static void setAttribute(Object proxy, String n, Object v)
+ throws Exception {
+ if (proxy instanceof AttributeHolder) {
+ ((AttributeHolder) proxy).setAttribute(n, v);
+ return;
+ }
+
+ Method executeM = null;
+ Class c = proxy.getClass();
+ Class params[] = new Class[2];
+ params[0] = String.class;
+ params[1] = Object.class;
+ executeM = findMethod(c, "setAttribute", params);
+ if (executeM == null) {
+ if (log.isDebugEnabled())
+ log.debug("No setAttribute in " + proxy.getClass());
+ return;
+ }
+ if (false)
+ if (log.isDebugEnabled())
+ log.debug("Setting " + n + "=" + v + " in " + proxy);
+ executeM.invoke(proxy, new Object[] { n, v });
+ return;
+ }
+
+ /**
+ * Call void getAttribute( String )
+ */
+ public static Object getAttribute(Object proxy, String n) throws Exception {
+ Method executeM = null;
+ Class c = proxy.getClass();
+ Class params[] = new Class[1];
+ params[0] = String.class;
+ executeM = findMethod(c, "getAttribute", params);
+ if (executeM == null) {
+ if (log.isDebugEnabled())
+ log.debug("No getAttribute in " + proxy.getClass());
+ return null;
+ }
+ return executeM.invoke(proxy, new Object[] { n });
+ }
+
+ /**
+ * Construct a URLClassLoader. Will compile and work in JDK1.1 too.
+ */
+ public static ClassLoader getURLClassLoader(URL urls[], ClassLoader parent) {
+ try {
+ Class urlCL = Class.forName("java.net.URLClassLoader");
+ Class paramT[] = new Class[2];
+ paramT[0] = urls.getClass();
+ paramT[1] = ClassLoader.class;
+ Method m = findMethod(urlCL, "newInstance", paramT);
+ if (m == null)
+ return null;
+
+ ClassLoader cl = (ClassLoader) m.invoke(urlCL, new Object[] { urls,
+ parent });
+ return cl;
+ } catch (ClassNotFoundException ex) {
+ // jdk1.1
+ return null;
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ return null;
+ }
+ }
+
+ public static String guessInstall(String installSysProp,
+ String homeSysProp, String jarName) {
+ return guessInstall(installSysProp, homeSysProp, jarName, null);
+ }
+
+ /**
+ * Guess a product install/home by analyzing the class path. It works for
+ * product using the pattern: lib/executable.jar or if executable.jar is
+ * included in classpath by a shell script. ( java -jar also works )
+ *
+ * Insures both "install" and "home" System properties are set. If either or
+ * both System properties are unset, "install" and "home" will be set to the
+ * same value. This value will be the other System property that is set, or
+ * the guessed value if neither is set.
+ */
+ public static String guessInstall(String installSysProp,
+ String homeSysProp, String jarName, String classFile) {
+ String install = null;
+ String home = null;
+
+ if (installSysProp != null)
+ install = System.getProperty(installSysProp);
+
+ if (homeSysProp != null)
+ home = System.getProperty(homeSysProp);
+
+ if (install != null) {
+ if (home == null)
+ System.getProperties().put(homeSysProp, install);
+ return install;
+ }
+
+ // Find the directory where jarName.jar is located
+
+ String cpath = System.getProperty("java.class.path");
+ String pathSep = System.getProperty("path.separator");
+ StringTokenizer st = new StringTokenizer(cpath, pathSep);
+ while (st.hasMoreTokens()) {
+ String path = st.nextToken();
+ // log( "path " + path );
+ if (path.endsWith(jarName)) {
+ home = path.substring(0, path.length() - jarName.length());
+ try {
+ if ("".equals(home)) {
+ home = new File("./").getCanonicalPath();
+ } else if (home.endsWith(File.separator)) {
+ home = home.substring(0, home.length() - 1);
+ }
+ File f = new File(home);
+ String parentDir = f.getParent();
+ if (parentDir == null)
+ parentDir = home; // unix style
+ File f1 = new File(parentDir);
+ install = f1.getCanonicalPath();
+ if (installSysProp != null)
+ System.getProperties().put(installSysProp, install);
+ if (home == null && homeSysProp != null)
+ System.getProperties().put(homeSysProp, install);
+ return install;
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ } else {
+ String fname = path + (path.endsWith("/") ? "" : "/")
+ + classFile;
+ if (new File(fname).exists()) {
+ try {
+ File f = new File(path);
+ String parentDir = f.getParent();
+ if (parentDir == null)
+ parentDir = path; // unix style
+ File f1 = new File(parentDir);
+ install = f1.getCanonicalPath();
+ if (installSysProp != null)
+ System.getProperties().put(installSysProp, install);
+ if (home == null && homeSysProp != null)
+ System.getProperties().put(homeSysProp, install);
+ return install;
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+ }
+ }
+
+ // if install directory can't be found, use home as the default
+ if (home != null) {
+ System.getProperties().put(installSysProp, home);
+ return home;
+ }
+
+ return null;
+ }
+
+ /**
+ * Debug method, display the classpath
+ */
+ public static void displayClassPath(String msg, URL[] cp) {
+ if (log.isDebugEnabled()) {
+ log.debug(msg);
+ for (int i = 0; i < cp.length; i++) {
+ log.debug(cp[i].getFile());
+ }
+ }
+ }
+
+ public static String PATH_SEPARATOR = System.getProperty("path.separator");
+
+ /**
+ * Adds classpath entries from a vector of URL's to the "tc_path_add" System
+ * property. This System property lists the classpath entries common to web
+ * applications. This System property is currently used by Jasper when its
+ * JSP servlet compiles the Java file for a JSP.
+ */
+ public static String classPathAdd(URL urls[], String cp) {
+ if (urls == null)
+ return cp;
+
+ for (int i = 0; i < urls.length; i++) {
+ if (cp != null)
+ cp += PATH_SEPARATOR + urls[i].getFile();
+ else
+ cp = urls[i].getFile();
+ }
+ return cp;
+ }
+
+ /**
+ * Find a method with the right name If found, call the method ( if param is
+ * int or boolean we'll convert value to the right type before) - that means
+ * you can have setDebug(1).
+ */
+ public static void setProperty(Object o, String name, String value) {
+ if (dbg > 1)
+ d("setProperty(" + o.getClass() + " " + name + "=" + value + ")");
+
+ String setter = "set" + capitalize(name);
+
+ try {
+ Method methods[] = findMethods(o.getClass());
+ Method setPropertyMethod = null;
+
+ // First, the ideal case - a setFoo( String ) method
+ for (int i = 0; i < methods.length; i++) {
+ Class paramT[] = methods[i].getParameterTypes();
+ if (setter.equals(methods[i].getName()) && paramT.length == 1
+ && "java.lang.String".equals(paramT[0].getName())) {
+
+ methods[i].invoke(o, new Object[] { value });
+ return;
+ }
+ }
+
+ // Try a setFoo ( int ) or ( boolean )
+ for (int i = 0; i < methods.length; i++) {
+ boolean ok = true;
+ if (setter.equals(methods[i].getName())
+ && methods[i].getParameterTypes().length == 1) {
+
+ // match - find the type and invoke it
+ Class paramType = methods[i].getParameterTypes()[0];
+ Object params[] = new Object[1];
+
+ // Try a setFoo ( int )
+ if ("java.lang.Integer".equals(paramType.getName())
+ || "int".equals(paramType.getName())) {
+ try {
+ params[0] = new Integer(value);
+ } catch (NumberFormatException ex) {
+ ok = false;
+ }
+ // Try a setFoo ( long )
+ }else if ("java.lang.Long".equals(paramType.getName())
+ || "long".equals(paramType.getName())) {
+ try {
+ params[0] = new Long(value);
+ } catch (NumberFormatException ex) {
+ ok = false;
+ }
+
+ // Try a setFoo ( boolean )
+ } else if ("java.lang.Boolean".equals(paramType.getName())
+ || "boolean".equals(paramType.getName())) {
+ params[0] = new Boolean(value);
+
+ // Try a setFoo ( InetAddress )
+ } else if ("java.net.InetAddress".equals(paramType
+ .getName())) {
+ try {
+ params[0] = InetAddress.getByName(value);
+ } catch (UnknownHostException exc) {
+ d("Unable to resolve host name:" + value);
+ ok = false;
+ }
+
+ // Unknown type
+ } else {
+ d("Unknown type " + paramType.getName());
+ }
+
+ if (ok) {
+ methods[i].invoke(o, params);
+ return;
+ }
+ }
+
+ // save "setProperty" for later
+ if ("setProperty".equals(methods[i].getName())) {
+ setPropertyMethod = methods[i];
+ }
+ }
+
+ // Ok, no setXXX found, try a setProperty("name", "value")
+ if (setPropertyMethod != null) {
+ Object params[] = new Object[2];
+ params[0] = name;
+ params[1] = value;
+ setPropertyMethod.invoke(o, params);
+ }
+
+ } catch (IllegalArgumentException ex2) {
+ log.warn("IAE " + o + " " + name + " " + value, ex2);
+ } catch (SecurityException ex1) {
+ if (dbg > 0)
+ d("SecurityException for " + o.getClass() + " " + name + "="
+ + value + ")");
+ if (dbg > 1)
+ ex1.printStackTrace();
+ } catch (IllegalAccessException iae) {
+ if (dbg > 0)
+ d("IllegalAccessException for " + o.getClass() + " " + name
+ + "=" + value + ")");
+ if (dbg > 1)
+ iae.printStackTrace();
+ } catch (InvocationTargetException ie) {
+ if (dbg > 0)
+ d("InvocationTargetException for " + o.getClass() + " " + name
+ + "=" + value + ")");
+ if (dbg > 1)
+ ie.printStackTrace();
+ }
+ }
+
+ public static Object getProperty(Object o, String name) {
+ String getter = "get" + capitalize(name);
+ String isGetter = "is" + capitalize(name);
+
+ try {
+ Method methods[] = findMethods(o.getClass());
+ Method getPropertyMethod = null;
+
+ // First, the ideal case - a getFoo() method
+ for (int i = 0; i < methods.length; i++) {
+ Class paramT[] = methods[i].getParameterTypes();
+ if (getter.equals(methods[i].getName()) && paramT.length == 0) {
+ return methods[i].invoke(o, (Object[]) null);
+ }
+ if (isGetter.equals(methods[i].getName()) && paramT.length == 0) {
+ return methods[i].invoke(o, (Object[]) null);
+ }
+
+ if ("getProperty".equals(methods[i].getName())) {
+ getPropertyMethod = methods[i];
+ }
+ }
+
+ // Ok, no setXXX found, try a getProperty("name")
+ if (getPropertyMethod != null) {
+ Object params[] = new Object[1];
+ params[0] = name;
+ return getPropertyMethod.invoke(o, params);
+ }
+
+ } catch (IllegalArgumentException ex2) {
+ log.warn("IAE " + o + " " + name, ex2);
+ } catch (SecurityException ex1) {
+ if (dbg > 0)
+ d("SecurityException for " + o.getClass() + " " + name + ")");
+ if (dbg > 1)
+ ex1.printStackTrace();
+ } catch (IllegalAccessException iae) {
+ if (dbg > 0)
+ d("IllegalAccessException for " + o.getClass() + " " + name
+ + ")");
+ if (dbg > 1)
+ iae.printStackTrace();
+ } catch (InvocationTargetException ie) {
+ if (dbg > 0)
+ d("InvocationTargetException for " + o.getClass() + " " + name
+ + ")");
+ if (dbg > 1)
+ ie.printStackTrace();
+ }
+ return null;
+ }
+
+ /**
+ */
+ public static void setProperty(Object o, String name) {
+ String setter = "set" + capitalize(name);
+ try {
+ Method methods[] = findMethods(o.getClass());
+ Method setPropertyMethod = null;
+ // find setFoo() method
+ for (int i = 0; i < methods.length; i++) {
+ Class paramT[] = methods[i].getParameterTypes();
+ if (setter.equals(methods[i].getName()) && paramT.length == 0) {
+ methods[i].invoke(o, new Object[] {});
+ return;
+ }
+ }
+ } catch (Exception ex1) {
+ if (dbg > 0)
+ d("Exception for " + o.getClass() + " " + name);
+ if (dbg > 1)
+ ex1.printStackTrace();
+ }
+ }
+
+ /**
+ * Replace ${NAME} with the property value
+ *
+ * @deprecated Use the explicit method
+ */
+ public static String replaceProperties(String value, Object getter) {
+ if (getter instanceof Hashtable)
+ return replaceProperties(value, (Hashtable) getter, null);
+
+ if (getter instanceof PropertySource) {
+ PropertySource src[] = new PropertySource[] { (PropertySource) getter };
+ return replaceProperties(value, null, src);
+ }
+ return value;
+ }
+
+ /**
+ * Replace ${NAME} with the property value
+ */
+ public static String replaceProperties(String value, Hashtable staticProp,
+ PropertySource dynamicProp[]) {
+ StringBuffer sb = new StringBuffer();
+ int prev = 0;
+ // assert value!=nil
+ int pos;
+ while ((pos = value.indexOf("$", prev)) >= 0) {
+ if (pos > 0) {
+ sb.append(value.substring(prev, pos));
+ }
+ if (pos == (value.length() - 1)) {
+ sb.append('$');
+ prev = pos + 1;
+ } else if (value.charAt(pos + 1) != '{') {
+ sb.append('$');
+ prev = pos + 1; // XXX
+ } else {
+ int endName = value.indexOf('}', pos);
+ if (endName < 0) {
+ sb.append(value.substring(pos));
+ prev = value.length();
+ continue;
+ }
+ String n = value.substring(pos + 2, endName);
+ String v = null;
+ if (staticProp != null) {
+ v = (String) ((Hashtable) staticProp).get(n);
+ }
+ if (v == null && dynamicProp != null) {
+ for (int i = 0; i < dynamicProp.length; i++) {
+ v = dynamicProp[i].getProperty(n);
+ if (v != null) {
+ break;
+ }
+ }
+ }
+ if (v == null)
+ v = "${" + n + "}";
+
+ sb.append(v);
+ prev = endName + 1;
+ }
+ }
+ if (prev < value.length())
+ sb.append(value.substring(prev));
+ return sb.toString();
+ }
+
+ /**
+ * Reverse of Introspector.decapitalize
+ */
+ public static String capitalize(String name) {
+ if (name == null || name.length() == 0) {
+ return name;
+ }
+ char chars[] = name.toCharArray();
+ chars[0] = Character.toUpperCase(chars[0]);
+ return new String(chars);
+ }
+
+ public static String unCapitalize(String name) {
+ if (name == null || name.length() == 0) {
+ return name;
+ }
+ char chars[] = name.toCharArray();
+ chars[0] = Character.toLowerCase(chars[0]);
+ return new String(chars);
+ }
+
+ // -------------------- Class path tools --------------------
+
+ /**
+ * Add all the jar files in a dir to the classpath, represented as a Vector
+ * of URLs.
+ */
+ public static void addToClassPath(Vector cpV, String dir) {
+ try {
+ String cpComp[] = getFilesByExt(dir, ".jar");
+ if (cpComp != null) {
+ int jarCount = cpComp.length;
+ for (int i = 0; i < jarCount; i++) {
+ URL url = getURL(dir, cpComp[i]);
+ if (url != null)
+ cpV.addElement(url);
+ }
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ public static void addToolsJar(Vector v) {
+ try {
+ // Add tools.jar in any case
+ File f = new File(System.getProperty("java.home")
+ + "/../lib/tools.jar");
+
+ if (!f.exists()) {
+ // On some systems java.home gets set to the root of jdk.
+ // That's a bug, but we can work around and be nice.
+ f = new File(System.getProperty("java.home") + "/lib/tools.jar");
+ if (f.exists()) {
+ if (log.isDebugEnabled())
+ log.debug("Detected strange java.home value "
+ + System.getProperty("java.home")
+ + ", it should point to jre");
+ }
+ }
+ URL url = new URL("file", "", f.getAbsolutePath());
+
+ v.addElement(url);
+ } catch (MalformedURLException ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ /**
+ * Return all files with a given extension in a dir
+ */
+ public static String[] getFilesByExt(String ld, String ext) {
+ File dir = new File(ld);
+ String[] names = null;
+ final String lext = ext;
+ if (dir.isDirectory()) {
+ names = dir.list(new FilenameFilter() {
+ public boolean accept(File d, String name) {
+ if (name.endsWith(lext)) {
+ return true;
+ }
+ return false;
+ }
+ });
+ }
+ return names;
+ }
+
+ /**
+ * Construct a file url from a file, using a base dir
+ */
+ public static URL getURL(String base, String file) {
+ try {
+ File baseF = new File(base);
+ File f = new File(baseF, file);
+ String path = f.getCanonicalPath();
+ if (f.isDirectory()) {
+ path += "/";
+ }
+ if (!f.exists())
+ return null;
+ return new URL("file", "", path);
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ return null;
+ }
+ }
+
+ /**
+ * Add elements from the classpath <i>cp </i> to a Vector <i>jars </i> as
+ * file URLs (We use Vector for JDK 1.1 compat).
+ * <p>
+ *
+ * @param jars The jar list
+ * @param cp a String classpath of directory or jar file elements
+ * separated by path.separator delimiters.
+ * @throws IOException If an I/O error occurs
+ * @throws MalformedURLException Doh ;)
+ */
+ public static void addJarsFromClassPath(Vector jars, String cp)
+ throws IOException, MalformedURLException {
+ String sep = System.getProperty("path.separator");
+ String token;
+ StringTokenizer st;
+ if (cp != null) {
+ st = new StringTokenizer(cp, sep);
+ while (st.hasMoreTokens()) {
+ File f = new File(st.nextToken());
+ String path = f.getCanonicalPath();
+ if (f.isDirectory()) {
+ path += "/";
+ }
+ URL url = new URL("file", "", path);
+ if (!jars.contains(url)) {
+ jars.addElement(url);
+ }
+ }
+ }
+ }
+
+ /**
+ * Return a URL[] that can be used to construct a class loader
+ */
+ public static URL[] getClassPath(Vector v) {
+ URL[] urls = new URL[v.size()];
+ for (int i = 0; i < v.size(); i++) {
+ urls[i] = (URL) v.elementAt(i);
+ }
+ return urls;
+ }
+
+ /**
+ * Construct a URL classpath from files in a directory, a cpath property,
+ * and tools.jar.
+ */
+ public static URL[] getClassPath(String dir, String cpath,
+ String cpathProp, boolean addTools) throws IOException,
+ MalformedURLException {
+ Vector jarsV = new Vector();
+ if (dir != null) {
+ // Add dir/classes first, if it exists
+ URL url = getURL(dir, "classes");
+ if (url != null)
+ jarsV.addElement(url);
+ addToClassPath(jarsV, dir);
+ }
+
+ if (cpath != null)
+ addJarsFromClassPath(jarsV, cpath);
+
+ if (cpathProp != null) {
+ String cpath1 = System.getProperty(cpathProp);
+ addJarsFromClassPath(jarsV, cpath1);
+ }
+
+ if (addTools)
+ addToolsJar(jarsV);
+
+ return getClassPath(jarsV);
+ }
+
+ // -------------------- Mapping command line params to setters
+
+ public static boolean processArgs(Object proxy, String args[])
+ throws Exception {
+ String args0[] = null;
+ if (null != findMethod(proxy.getClass(), "getOptions1", new Class[] {})) {
+ args0 = (String[]) callMethod0(proxy, "getOptions1");
+ }
+
+ if (args0 == null) {
+ //args0=findVoidSetters(proxy.getClass());
+ args0 = findBooleanSetters(proxy.getClass());
+ }
+ Hashtable h = null;
+ if (null != findMethod(proxy.getClass(), "getOptionAliases",
+ new Class[] {})) {
+ h = (Hashtable) callMethod0(proxy, "getOptionAliases");
+ }
+ return processArgs(proxy, args, args0, null, h);
+ }
+
+ public static boolean processArgs(Object proxy, String args[],
+ String args0[], String args1[], Hashtable aliases) throws Exception {
+ for (int i = 0; i < args.length; i++) {
+ String arg = args[i];
+ if (arg.startsWith("-"))
+ arg = arg.substring(1);
+ if (aliases != null && aliases.get(arg) != null)
+ arg = (String) aliases.get(arg);
+
+ if (args0 != null) {
+ boolean set = false;
+ for (int j = 0; j < args0.length; j++) {
+ if (args0[j].equalsIgnoreCase(arg)) {
+ setProperty(proxy, args0[j], "true");
+ set = true;
+ break;
+ }
+ }
+ if (set)
+ continue;
+ }
+ if (args1 != null) {
+ for (int j = 0; j < args1.length; j++) {
+ if (args1[j].equalsIgnoreCase(arg)) {
+ i++;
+ if (i >= args.length)
+ return false;
+ setProperty(proxy, arg, args[i]);
+ break;
+ }
+ }
+ } else {
+ // if args1 is not specified,assume all other options have param
+ i++;
+ if (i >= args.length)
+ return false;
+ setProperty(proxy, arg, args[i]);
+ }
+
+ }
+ return true;
+ }
+
+ // -------------------- other utils --------------------
+ public static void clear() {
+ objectMethods.clear();
+ }
+
+ public static String[] findVoidSetters(Class c) {
+ Method m[] = findMethods(c);
+ if (m == null)
+ return null;
+ Vector v = new Vector();
+ for (int i = 0; i < m.length; i++) {
+ if (m[i].getName().startsWith("set")
+ && m[i].getParameterTypes().length == 0) {
+ String arg = m[i].getName().substring(3);
+ v.addElement(unCapitalize(arg));
+ }
+ }
+ String s[] = new String[v.size()];
+ for (int i = 0; i < s.length; i++) {
+ s[i] = (String) v.elementAt(i);
+ }
+ return s;
+ }
+
+ public static String[] findBooleanSetters(Class c) {
+ Method m[] = findMethods(c);
+ if (m == null)
+ return null;
+ Vector v = new Vector();
+ for (int i = 0; i < m.length; i++) {
+ if (m[i].getName().startsWith("set")
+ && m[i].getParameterTypes().length == 1
+ && "boolean".equalsIgnoreCase(m[i].getParameterTypes()[0]
+ .getName())) {
+ String arg = m[i].getName().substring(3);
+ v.addElement(unCapitalize(arg));
+ }
+ }
+ String s[] = new String[v.size()];
+ for (int i = 0; i < s.length; i++) {
+ s[i] = (String) v.elementAt(i);
+ }
+ return s;
+ }
+
+ static Hashtable objectMethods = new Hashtable();
+
+ public static Method[] findMethods(Class c) {
+ Method methods[] = (Method[]) objectMethods.get(c);
+ if (methods != null)
+ return methods;
+
+ methods = c.getMethods();
+ objectMethods.put(c, methods);
+ return methods;
+ }
+
+ public static Method findMethod(Class c, String name, Class params[]) {
+ Method methods[] = findMethods(c);
+ if (methods == null)
+ return null;
+ for (int i = 0; i < methods.length; i++) {
+ if (methods[i].getName().equals(name)) {
+ Class methodParams[] = methods[i].getParameterTypes();
+ if (methodParams == null)
+ if (params == null || params.length == 0)
+ return methods[i];
+ if (params == null)
+ if (methodParams == null || methodParams.length == 0)
+ return methods[i];
+ if (params.length != methodParams.length)
+ continue;
+ boolean found = true;
+ for (int j = 0; j < params.length; j++) {
+ if (params[j] != methodParams[j]) {
+ found = false;
+ break;
+ }
+ }
+ if (found)
+ return methods[i];
+ }
+ }
+ return null;
+ }
+
+ /** Test if the object implements a particular
+ * method
+ */
+ public static boolean hasHook(Object obj, String methodN) {
+ try {
+ Method myMethods[] = findMethods(obj.getClass());
+ for (int i = 0; i < myMethods.length; i++) {
+ if (methodN.equals(myMethods[i].getName())) {
+ // check if it's overriden
+ Class declaring = myMethods[i].getDeclaringClass();
+ Class parentOfDeclaring = declaring.getSuperclass();
+ // this works only if the base class doesn't extend
+ // another class.
+
+ // if the method is declared in a top level class
+ // like BaseInterceptor parent is Object, otherwise
+ // parent is BaseInterceptor or an intermediate class
+ if (!"java.lang.Object".equals(parentOfDeclaring.getName())) {
+ return true;
+ }
+ }
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ return false;
+ }
+
+ public static void callMain(Class c, String args[]) throws Exception {
+ Class p[] = new Class[1];
+ p[0] = args.getClass();
+ Method m = c.getMethod("main", p);
+ m.invoke(c, new Object[] { args });
+ }
+
+ public static Object callMethod1(Object target, String methodN,
+ Object param1, String typeParam1, ClassLoader cl) throws Exception {
+ if (target == null || param1 == null) {
+ d("Assert: Illegal params " + target + " " + param1);
+ }
+ if (dbg > 0)
+ d("callMethod1 " + target.getClass().getName() + " "
+ + param1.getClass().getName() + " " + typeParam1);
+
+ Class params[] = new Class[1];
+ if (typeParam1 == null)
+ params[0] = param1.getClass();
+ else
+ params[0] = cl.loadClass(typeParam1);
+ Method m = findMethod(target.getClass(), methodN, params);
+ if (m == null)
+ throw new NoSuchMethodException(target.getClass().getName() + " "
+ + methodN);
+ return m.invoke(target, new Object[] { param1 });
+ }
+
+ public static Object callMethod0(Object target, String methodN)
+ throws Exception {
+ if (target == null) {
+ d("Assert: Illegal params " + target);
+ return null;
+ }
+ if (dbg > 0)
+ d("callMethod0 " + target.getClass().getName() + "." + methodN);
+
+ Class params[] = new Class[0];
+ Method m = findMethod(target.getClass(), methodN, params);
+ if (m == null)
+ throw new NoSuchMethodException(target.getClass().getName() + " "
+ + methodN);
+ return m.invoke(target, emptyArray);
+ }
+
+ static Object[] emptyArray = new Object[] {};
+
+ public static Object callMethodN(Object target, String methodN,
+ Object params[], Class typeParams[]) throws Exception {
+ Method m = null;
+ m = findMethod(target.getClass(), methodN, typeParams);
+ if (m == null) {
+ d("Can't find method " + methodN + " in " + target + " CLASS "
+ + target.getClass());
+ return null;
+ }
+ Object o = m.invoke(target, params);
+
+ if (dbg > 0) {
+ // debug
+ StringBuffer sb = new StringBuffer();
+ sb.append("" + target.getClass().getName() + "." + methodN + "( ");
+ for (int i = 0; i < params.length; i++) {
+ if (i > 0)
+ sb.append(", ");
+ sb.append(params[i]);
+ }
+ sb.append(")");
+ d(sb.toString());
+ }
+ return o;
+ }
+
+ public static Object convert(String object, Class paramType) {
+ Object result = null;
+ if ("java.lang.String".equals(paramType.getName())) {
+ result = object;
+ } else if ("java.lang.Integer".equals(paramType.getName())
+ || "int".equals(paramType.getName())) {
+ try {
+ result = new Integer(object);
+ } catch (NumberFormatException ex) {
+ }
+ // Try a setFoo ( boolean )
+ } else if ("java.lang.Boolean".equals(paramType.getName())
+ || "boolean".equals(paramType.getName())) {
+ result = new Boolean(object);
+
+ // Try a setFoo ( InetAddress )
+ } else if ("java.net.InetAddress".equals(paramType
+ .getName())) {
+ try {
+ result = InetAddress.getByName(object);
+ } catch (UnknownHostException exc) {
+ d("Unable to resolve host name:" + object);
+ }
+
+ // Unknown type
+ } else {
+ d("Unknown type " + paramType.getName());
+ }
+ if (result == null) {
+ throw new IllegalArgumentException("Can't convert argument: " + object);
+ }
+ return result;
+ }
+
+ // -------------------- Get property --------------------
+ // This provides a layer of abstraction
+
+ public static interface PropertySource {
+
+ public String getProperty(String key);
+
+ }
+
+ public static interface AttributeHolder {
+
+ public void setAttribute(String key, Object o);
+
+ }
+
+ // debug --------------------
+ static final int dbg = 0;
+
+ static void d(String s) {
+ if (log.isDebugEnabled())
+ log.debug("IntrospectionUtils: " + s);
+ }
+}
-/*\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.demos;\r
-\r
-import java.io.Serializable;\r
-import java.util.Random;\r
-\r
-import org.apache.catalina.tribes.ByteMessage;\r
-import org.apache.catalina.tribes.ChannelException;\r
-import org.apache.catalina.tribes.ChannelListener;\r
-import org.apache.catalina.tribes.ManagedChannel;\r
-import org.apache.catalina.tribes.Member;\r
-import org.apache.catalina.tribes.MembershipListener;\r
-import org.apache.catalina.tribes.io.XByteBuffer;\r
-import org.apache.catalina.tribes.Channel;\r
-import java.io.Externalizable;\r
-\r
-\r
-/**\r
- * <p>Title: </p>\r
- *\r
- * <p>Description: </p>\r
- *\r
- * <p>Copyright: Copyright (c) 2005</p>\r
- *\r
- * <p>Company: </p>\r
- *\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-public class LoadTest implements MembershipListener,ChannelListener, Runnable {\r
- protected static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LoadTest.class);\r
- public static int size = 24000;\r
- public static Object mutex = new Object();\r
- public boolean doRun = true;\r
- \r
- public long bytesReceived = 0;\r
- public float mBytesReceived = 0;\r
- public int messagesReceived = 0;\r
- public boolean send = true;\r
- public boolean debug = false;\r
- public int msgCount = 100;\r
- ManagedChannel channel=null;\r
- public int statsInterval = 10000;\r
- public long pause = 0;\r
- public boolean breakonChannelException = false;\r
- public boolean async = false;\r
- public long receiveStart = 0;\r
- public int channelOptions = Channel.SEND_OPTIONS_DEFAULT;\r
- \r
- static int messageSize = 0;\r
- \r
- public static long messagesSent = 0;\r
- public static long messageStartSendTime = 0;\r
- public static long messageEndSendTime = 0;\r
- public static int threadCount = 0;\r
- \r
- public static synchronized void startTest() {\r
- threadCount++;\r
- if ( messageStartSendTime == 0 ) messageStartSendTime = System.currentTimeMillis();\r
- }\r
- \r
- public static synchronized void endTest() {\r
- threadCount--;\r
- if ( messageEndSendTime == 0 && threadCount==0 ) messageEndSendTime = System.currentTimeMillis();\r
- }\r
-\r
- \r
- public static synchronized long addSendStats(long count) {\r
- messagesSent+=count;\r
- return 0l;\r
- } \r
- \r
- private static void printSendStats(long counter, int messageSize) {\r
- float cnt = (float)counter;\r
- float size = (float)messageSize;\r
- float time = (float)(System.currentTimeMillis()-messageStartSendTime) / 1000f;\r
- log.info("****SEND STATS-"+Thread.currentThread().getName()+"*****"+\r
- "\n\tMessage count:"+counter+\r
- "\n\tTotal bytes :"+(long)(size*cnt)+\r
- "\n\tTotal seconds:"+(time)+\r
- "\n\tBytes/second :"+(size*cnt/time)+\r
- "\n\tMBytes/second:"+(size*cnt/time/1024f/1024f));\r
- }\r
-\r
- \r
- \r
- public LoadTest(ManagedChannel channel, \r
- boolean send,\r
- int msgCount,\r
- boolean debug,\r
- long pause,\r
- int stats,\r
- boolean breakOnEx) {\r
- this.channel = channel;\r
- this.send = send;\r
- this.msgCount = msgCount;\r
- this.debug = debug;\r
- this.pause = pause;\r
- this.statsInterval = stats;\r
- this.breakonChannelException = breakOnEx;\r
- }\r
- \r
- \r
- \r
- public void run() {\r
- \r
- long counter = 0;\r
- long total = 0;\r
- LoadMessage msg = new LoadMessage();\r
- int messageSize = LoadTest.messageSize;\r
- \r
- try {\r
- startTest();\r
- while (total < msgCount) {\r
- if (channel.getMembers().length == 0 || (!send)) {\r
- synchronized (mutex) {\r
- try {\r
- mutex.wait();\r
- } catch (InterruptedException x) {\r
- log.info("Thread interrupted from wait");\r
- }\r
- }\r
- } else {\r
- try {\r
- //msg.setMsgNr((int)++total);\r
- counter++;\r
- if (debug) {\r
- printArray(msg.getMessage());\r
- }\r
- channel.send(channel.getMembers(), msg, channelOptions);\r
- if ( pause > 0 ) {\r
- if ( debug) System.out.println("Pausing sender for "+pause+" ms.");\r
- Thread.sleep(pause);\r
- }\r
- } catch (ChannelException x) {\r
- if ( debug ) log.error("Unable to send message:"+x.getMessage(),x);\r
- log.error("Unable to send message:"+x.getMessage());\r
- ChannelException.FaultyMember[] faulty = x.getFaultyMembers();\r
- for (int i=0; i<faulty.length; i++ ) log.error("Faulty: "+faulty[i]);\r
- --counter;\r
- if ( this.breakonChannelException ) throw x;\r
- }\r
- }\r
- if ( (counter % statsInterval) == 0 && (counter > 0)) {\r
- //add to the global counter\r
- counter = addSendStats(counter);\r
- //print from the global counter\r
- //printSendStats(LoadTest.messagesSent, LoadTest.messageSize, LoadTest.messageSendTime);\r
- printSendStats(LoadTest.messagesSent, LoadTest.messageSize);\r
- \r
- }\r
-\r
- }\r
- }catch ( Exception x ) {\r
- log.error("Captured error while sending:"+x.getMessage());\r
- if ( debug ) log.error("",x);\r
- printSendStats(LoadTest.messagesSent, LoadTest.messageSize);\r
- }\r
- endTest();\r
- }\r
-\r
- \r
-\r
- /**\r
- * memberAdded\r
- *\r
- * @param member Member\r
- * @todo Implement this org.apache.catalina.tribes.MembershipListener\r
- * method\r
- */\r
- public void memberAdded(Member member) {\r
- log.info("Member added:"+member);\r
- synchronized (mutex) {\r
- mutex.notifyAll();\r
- }\r
- }\r
-\r
- /**\r
- * memberDisappeared\r
- *\r
- * @param member Member\r
- * @todo Implement this org.apache.catalina.tribes.MembershipListener\r
- * method\r
- */\r
- public void memberDisappeared(Member member) {\r
- log.info("Member disappeared:"+member);\r
- }\r
- \r
- public boolean accept(Serializable msg, Member mbr){ \r
- return (msg instanceof LoadMessage) || (msg instanceof ByteMessage);\r
- }\r
- \r
- public void messageReceived(Serializable msg, Member mbr){ \r
- if ( receiveStart == 0 ) receiveStart = System.currentTimeMillis();\r
- if ( debug ) {\r
- if ( msg instanceof LoadMessage ) {\r
- printArray(((LoadMessage)msg).getMessage());\r
- }\r
- }\r
- \r
- if ( msg instanceof ByteMessage && !(msg instanceof LoadMessage)) {\r
- LoadMessage tmp = new LoadMessage();\r
- tmp.setMessage(((ByteMessage)msg).getMessage());\r
- msg = tmp;\r
- tmp = null;\r
- }\r
- \r
- \r
- bytesReceived+=((LoadMessage)msg).getMessage().length;\r
- mBytesReceived+=((float)((LoadMessage)msg).getMessage().length)/1024f/1024f;\r
- messagesReceived++;\r
- if ( (messagesReceived%statsInterval)==0 || (messagesReceived==msgCount)) {\r
- float bytes = (float)(((LoadMessage)msg).getMessage().length*messagesReceived);\r
- float seconds = ((float)(System.currentTimeMillis()-receiveStart)) / 1000f;\r
- log.info("****RECEIVE STATS-"+Thread.currentThread().getName()+"*****"+\r
- "\n\tMessage count :"+(long)messagesReceived+\r
- "\n\tTotal bytes :"+(long)bytes+\r
- "\n\tTotal mbytes :"+(long)mBytesReceived+\r
- "\n\tTime since 1st:"+seconds+" seconds"+\r
- "\n\tBytes/second :"+(bytes/seconds)+\r
- "\n\tMBytes/second :"+(mBytesReceived/seconds)+"\n");\r
-\r
- }\r
- }\r
- \r
- \r
- public static void printArray(byte[] data) {\r
- System.out.print("{");\r
- for (int i=0; i<data.length; i++ ) {\r
- System.out.print(data[i]);\r
- System.out.print(",");\r
- }\r
- System.out.println("} size:"+data.length);\r
- }\r
-\r
- \r
- \r
- //public static class LoadMessage implements Serializable {\r
- public static class LoadMessage extends ByteMessage implements Serializable {\r
- \r
- public static byte[] outdata = new byte[size];\r
- public static Random r = new Random(System.currentTimeMillis());\r
- public static int getMessageSize (LoadMessage msg) {\r
- int messageSize = msg.getMessage().length;\r
- if ( ((Object)msg) instanceof ByteMessage ) return messageSize;\r
- try {\r
- messageSize = XByteBuffer.serialize(new LoadMessage()).length;\r
- log.info("Average message size:" + messageSize + " bytes");\r
- } catch (Exception x) {\r
- log.error("Unable to calculate test message size.", x);\r
- }\r
- return messageSize;\r
- }\r
- static {\r
- r.nextBytes(outdata);\r
- }\r
- \r
- protected byte[] message = getMessage();\r
- \r
- public LoadMessage() {\r
- }\r
- \r
- public byte[] getMessage() {\r
- if ( message == null ) {\r
- message = outdata;\r
- }\r
- return message;\r
- }\r
- \r
- public void setMessage(byte[] data) {\r
- this.message = data;\r
- }\r
- }\r
- \r
- public static void usage() {\r
- System.out.println("Tribes Load tester.");\r
- System.out.println("The load tester can be used in sender or received mode or both");\r
- System.out.println("Usage:\n\t"+\r
- "java LoadTest [options]\n\t"+\r
- "Options:\n\t\t"+\r
- "[-mode receive|send|both] \n\t\t"+\r
- "[-startoptions startflags (default is Channel.DEFAULT) ] \n\t\t"+\r
- "[-debug] \n\t\t"+\r
- "[-count messagecount] \n\t\t"+\r
- "[-stats statinterval] \n\t\t"+\r
- "[-pause nrofsecondstopausebetweensends] \n\t\t"+\r
- "[-threads numberofsenderthreads] \n\t\t"+\r
- "[-size messagesize] \n\t\t"+\r
- "[-sendoptions channeloptions] \n\t\t"+\r
- "[-break (halts execution on exception)]\n"+\r
- "[-shutdown (issues a channel.stop() command after send is completed)]\n"+\r
- "\tChannel options:"+\r
- ChannelCreator.usage()+"\n\n"+\r
- "Example:\n\t"+\r
- "java LoadTest -port 4004\n\t"+\r
- "java LoadTest -bind 192.168.0.45 -port 4005\n\t"+\r
- "java LoadTest -bind 192.168.0.45 -port 4005 -mbind 192.168.0.45 -count 100 -stats 10\n");\r
- }\r
- \r
- public static void main(String[] args) throws Exception {\r
- boolean send = true;\r
- boolean debug = false;\r
- long pause = 0;\r
- int count = 1000000;\r
- int stats = 10000;\r
- boolean breakOnEx = false;\r
- int threads = 1;\r
- boolean shutdown = false;\r
- int startoptions = Channel.DEFAULT;\r
- int channelOptions = Channel.SEND_OPTIONS_DEFAULT;\r
- if ( args.length == 0 ) {\r
- args = new String[] {"-help"};\r
- }\r
- for (int i = 0; i < args.length; i++) {\r
- if ("-threads".equals(args[i])) {\r
- threads = Integer.parseInt(args[++i]);\r
- } else if ("-count".equals(args[i])) {\r
- count = Integer.parseInt(args[++i]);\r
- System.out.println("Sending "+count+" messages.");\r
- } else if ("-pause".equals(args[i])) {\r
- pause = Long.parseLong(args[++i])*1000;\r
- } else if ("-break".equals(args[i])) {\r
- breakOnEx = true;\r
- } else if ("-shutdown".equals(args[i])) {\r
- shutdown = true;\r
- } else if ("-stats".equals(args[i])) {\r
- stats = Integer.parseInt(args[++i]);\r
- System.out.println("Stats every "+stats+" message");\r
- } else if ("-sendoptions".equals(args[i])) {\r
- channelOptions = Integer.parseInt(args[++i]);\r
- System.out.println("Setting send options to "+channelOptions);\r
- } else if ("-startoptions".equals(args[i])) {\r
- startoptions = Integer.parseInt(args[++i]);\r
- System.out.println("Setting start options to "+startoptions);\r
- } else if ("-size".equals(args[i])) {\r
- size = Integer.parseInt(args[++i])-4;\r
- System.out.println("Message size will be:"+(size+4)+" bytes");\r
- } else if ("-mode".equals(args[i])) {\r
- if ( "receive".equals(args[++i]) ) send = false;\r
- } else if ("-debug".equals(args[i])) {\r
- debug = true;\r
- } else if ("-help".equals(args[i])) \r
- {\r
- usage();\r
- System.exit(1);\r
- }\r
- }\r
- \r
- ManagedChannel channel = (ManagedChannel)ChannelCreator.createChannel(args);\r
- \r
- LoadTest test = new LoadTest(channel,send,count,debug,pause,stats,breakOnEx);\r
- test.channelOptions = channelOptions;\r
- LoadMessage msg = new LoadMessage();\r
- \r
- messageSize = LoadMessage.getMessageSize(msg);\r
- channel.addChannelListener(test);\r
- channel.addMembershipListener(test);\r
- channel.start(startoptions);\r
- Runtime.getRuntime().addShutdownHook(new Shutdown(channel));\r
- while ( threads > 1 ) {\r
- Thread t = new Thread(test);\r
- t.setDaemon(true);\r
- t.start();\r
- threads--;\r
- test = new LoadTest(channel,send,count,debug,pause,stats,breakOnEx);\r
- test.channelOptions = channelOptions;\r
- }\r
- test.run();\r
- if ( shutdown && send ) channel.stop(channel.DEFAULT);\r
- System.out.println("System test complete, sleeping to let threads finish.");\r
- Thread.sleep(60*1000*60);\r
- } \r
- \r
- public static class Shutdown extends Thread {\r
- ManagedChannel channel = null;\r
- public Shutdown(ManagedChannel channel) {\r
- this.channel = channel;\r
- }\r
- \r
- public void run() {\r
- System.out.println("Shutting down...");\r
- SystemExit exit = new SystemExit(5000);\r
- exit.setDaemon(true);\r
- exit.start();\r
- try {\r
- channel.stop(channel.DEFAULT);\r
- \r
- }catch ( Exception x ) {\r
- x.printStackTrace();\r
- }\r
- System.out.println("Channel stopped.");\r
- }\r
- }\r
- public static class SystemExit extends Thread {\r
- private long delay;\r
- public SystemExit(long delay) {\r
- this.delay = delay;\r
- }\r
- public void run () {\r
- try {\r
- Thread.sleep(delay);\r
- }catch ( Exception x ) {\r
- x.printStackTrace();\r
- }\r
- System.exit(0);\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.demos;
+
+import java.io.Serializable;
+import java.util.Random;
+
+import org.apache.catalina.tribes.ByteMessage;
+import org.apache.catalina.tribes.ChannelException;
+import org.apache.catalina.tribes.ChannelListener;
+import org.apache.catalina.tribes.ManagedChannel;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.MembershipListener;
+import org.apache.catalina.tribes.io.XByteBuffer;
+import org.apache.catalina.tribes.Channel;
+import java.io.Externalizable;
+
+
+/**
+ * <p>Title: </p>
+ *
+ * <p>Description: </p>
+ *
+ * <p>Copyright: Copyright (c) 2005</p>
+ *
+ * <p>Company: </p>
+ *
+ * @author not attributable
+ * @version 1.0
+ */
+public class LoadTest implements MembershipListener,ChannelListener, Runnable {
+ protected static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LoadTest.class);
+ public static int size = 24000;
+ public static Object mutex = new Object();
+ public boolean doRun = true;
+
+ public long bytesReceived = 0;
+ public float mBytesReceived = 0;
+ public int messagesReceived = 0;
+ public boolean send = true;
+ public boolean debug = false;
+ public int msgCount = 100;
+ ManagedChannel channel=null;
+ public int statsInterval = 10000;
+ public long pause = 0;
+ public boolean breakonChannelException = false;
+ public boolean async = false;
+ public long receiveStart = 0;
+ public int channelOptions = Channel.SEND_OPTIONS_DEFAULT;
+
+ static int messageSize = 0;
+
+ public static long messagesSent = 0;
+ public static long messageStartSendTime = 0;
+ public static long messageEndSendTime = 0;
+ public static int threadCount = 0;
+
+ public static synchronized void startTest() {
+ threadCount++;
+ if ( messageStartSendTime == 0 ) messageStartSendTime = System.currentTimeMillis();
+ }
+
+ public static synchronized void endTest() {
+ threadCount--;
+ if ( messageEndSendTime == 0 && threadCount==0 ) messageEndSendTime = System.currentTimeMillis();
+ }
+
+
+ public static synchronized long addSendStats(long count) {
+ messagesSent+=count;
+ return 0l;
+ }
+
+ private static void printSendStats(long counter, int messageSize) {
+ float cnt = (float)counter;
+ float size = (float)messageSize;
+ float time = (float)(System.currentTimeMillis()-messageStartSendTime) / 1000f;
+ log.info("****SEND STATS-"+Thread.currentThread().getName()+"*****"+
+ "\n\tMessage count:"+counter+
+ "\n\tTotal bytes :"+(long)(size*cnt)+
+ "\n\tTotal seconds:"+(time)+
+ "\n\tBytes/second :"+(size*cnt/time)+
+ "\n\tMBytes/second:"+(size*cnt/time/1024f/1024f));
+ }
+
+
+
+ public LoadTest(ManagedChannel channel,
+ boolean send,
+ int msgCount,
+ boolean debug,
+ long pause,
+ int stats,
+ boolean breakOnEx) {
+ this.channel = channel;
+ this.send = send;
+ this.msgCount = msgCount;
+ this.debug = debug;
+ this.pause = pause;
+ this.statsInterval = stats;
+ this.breakonChannelException = breakOnEx;
+ }
+
+
+
+ public void run() {
+
+ long counter = 0;
+ long total = 0;
+ LoadMessage msg = new LoadMessage();
+ int messageSize = LoadTest.messageSize;
+
+ try {
+ startTest();
+ while (total < msgCount) {
+ if (channel.getMembers().length == 0 || (!send)) {
+ synchronized (mutex) {
+ try {
+ mutex.wait();
+ } catch (InterruptedException x) {
+ log.info("Thread interrupted from wait");
+ }
+ }
+ } else {
+ try {
+ //msg.setMsgNr((int)++total);
+ counter++;
+ if (debug) {
+ printArray(msg.getMessage());
+ }
+ channel.send(channel.getMembers(), msg, channelOptions);
+ if ( pause > 0 ) {
+ if ( debug) System.out.println("Pausing sender for "+pause+" ms.");
+ Thread.sleep(pause);
+ }
+ } catch (ChannelException x) {
+ if ( debug ) log.error("Unable to send message:"+x.getMessage(),x);
+ log.error("Unable to send message:"+x.getMessage());
+ ChannelException.FaultyMember[] faulty = x.getFaultyMembers();
+ for (int i=0; i<faulty.length; i++ ) log.error("Faulty: "+faulty[i]);
+ --counter;
+ if ( this.breakonChannelException ) throw x;
+ }
+ }
+ if ( (counter % statsInterval) == 0 && (counter > 0)) {
+ //add to the global counter
+ counter = addSendStats(counter);
+ //print from the global counter
+ //printSendStats(LoadTest.messagesSent, LoadTest.messageSize, LoadTest.messageSendTime);
+ printSendStats(LoadTest.messagesSent, LoadTest.messageSize);
+
+ }
+
+ }
+ }catch ( Exception x ) {
+ log.error("Captured error while sending:"+x.getMessage());
+ if ( debug ) log.error("",x);
+ printSendStats(LoadTest.messagesSent, LoadTest.messageSize);
+ }
+ endTest();
+ }
+
+
+
+ /**
+ * memberAdded
+ *
+ * @param member Member
+ * @todo Implement this org.apache.catalina.tribes.MembershipListener
+ * method
+ */
+ public void memberAdded(Member member) {
+ log.info("Member added:"+member);
+ synchronized (mutex) {
+ mutex.notifyAll();
+ }
+ }
+
+ /**
+ * memberDisappeared
+ *
+ * @param member Member
+ * @todo Implement this org.apache.catalina.tribes.MembershipListener
+ * method
+ */
+ public void memberDisappeared(Member member) {
+ log.info("Member disappeared:"+member);
+ }
+
+ public boolean accept(Serializable msg, Member mbr){
+ return (msg instanceof LoadMessage) || (msg instanceof ByteMessage);
+ }
+
+ public void messageReceived(Serializable msg, Member mbr){
+ if ( receiveStart == 0 ) receiveStart = System.currentTimeMillis();
+ if ( debug ) {
+ if ( msg instanceof LoadMessage ) {
+ printArray(((LoadMessage)msg).getMessage());
+ }
+ }
+
+ if ( msg instanceof ByteMessage && !(msg instanceof LoadMessage)) {
+ LoadMessage tmp = new LoadMessage();
+ tmp.setMessage(((ByteMessage)msg).getMessage());
+ msg = tmp;
+ tmp = null;
+ }
+
+
+ bytesReceived+=((LoadMessage)msg).getMessage().length;
+ mBytesReceived+=((float)((LoadMessage)msg).getMessage().length)/1024f/1024f;
+ messagesReceived++;
+ if ( (messagesReceived%statsInterval)==0 || (messagesReceived==msgCount)) {
+ float bytes = (float)(((LoadMessage)msg).getMessage().length*messagesReceived);
+ float seconds = ((float)(System.currentTimeMillis()-receiveStart)) / 1000f;
+ log.info("****RECEIVE STATS-"+Thread.currentThread().getName()+"*****"+
+ "\n\tMessage count :"+(long)messagesReceived+
+ "\n\tTotal bytes :"+(long)bytes+
+ "\n\tTotal mbytes :"+(long)mBytesReceived+
+ "\n\tTime since 1st:"+seconds+" seconds"+
+ "\n\tBytes/second :"+(bytes/seconds)+
+ "\n\tMBytes/second :"+(mBytesReceived/seconds)+"\n");
+
+ }
+ }
+
+
+ public static void printArray(byte[] data) {
+ System.out.print("{");
+ for (int i=0; i<data.length; i++ ) {
+ System.out.print(data[i]);
+ System.out.print(",");
+ }
+ System.out.println("} size:"+data.length);
+ }
+
+
+
+ //public static class LoadMessage implements Serializable {
+ public static class LoadMessage extends ByteMessage implements Serializable {
+
+ public static byte[] outdata = new byte[size];
+ public static Random r = new Random(System.currentTimeMillis());
+ public static int getMessageSize (LoadMessage msg) {
+ int messageSize = msg.getMessage().length;
+ if ( ((Object)msg) instanceof ByteMessage ) return messageSize;
+ try {
+ messageSize = XByteBuffer.serialize(new LoadMessage()).length;
+ log.info("Average message size:" + messageSize + " bytes");
+ } catch (Exception x) {
+ log.error("Unable to calculate test message size.", x);
+ }
+ return messageSize;
+ }
+ static {
+ r.nextBytes(outdata);
+ }
+
+ protected byte[] message = getMessage();
+
+ public LoadMessage() {
+ }
+
+ public byte[] getMessage() {
+ if ( message == null ) {
+ message = outdata;
+ }
+ return message;
+ }
+
+ public void setMessage(byte[] data) {
+ this.message = data;
+ }
+ }
+
+ public static void usage() {
+ System.out.println("Tribes Load tester.");
+ System.out.println("The load tester can be used in sender or received mode or both");
+ System.out.println("Usage:\n\t"+
+ "java LoadTest [options]\n\t"+
+ "Options:\n\t\t"+
+ "[-mode receive|send|both] \n\t\t"+
+ "[-startoptions startflags (default is Channel.DEFAULT) ] \n\t\t"+
+ "[-debug] \n\t\t"+
+ "[-count messagecount] \n\t\t"+
+ "[-stats statinterval] \n\t\t"+
+ "[-pause nrofsecondstopausebetweensends] \n\t\t"+
+ "[-threads numberofsenderthreads] \n\t\t"+
+ "[-size messagesize] \n\t\t"+
+ "[-sendoptions channeloptions] \n\t\t"+
+ "[-break (halts execution on exception)]\n"+
+ "[-shutdown (issues a channel.stop() command after send is completed)]\n"+
+ "\tChannel options:"+
+ ChannelCreator.usage()+"\n\n"+
+ "Example:\n\t"+
+ "java LoadTest -port 4004\n\t"+
+ "java LoadTest -bind 192.168.0.45 -port 4005\n\t"+
+ "java LoadTest -bind 192.168.0.45 -port 4005 -mbind 192.168.0.45 -count 100 -stats 10\n");
+ }
+
+ public static void main(String[] args) throws Exception {
+ boolean send = true;
+ boolean debug = false;
+ long pause = 0;
+ int count = 1000000;
+ int stats = 10000;
+ boolean breakOnEx = false;
+ int threads = 1;
+ boolean shutdown = false;
+ int startoptions = Channel.DEFAULT;
+ int channelOptions = Channel.SEND_OPTIONS_DEFAULT;
+ if ( args.length == 0 ) {
+ args = new String[] {"-help"};
+ }
+ for (int i = 0; i < args.length; i++) {
+ if ("-threads".equals(args[i])) {
+ threads = Integer.parseInt(args[++i]);
+ } else if ("-count".equals(args[i])) {
+ count = Integer.parseInt(args[++i]);
+ System.out.println("Sending "+count+" messages.");
+ } else if ("-pause".equals(args[i])) {
+ pause = Long.parseLong(args[++i])*1000;
+ } else if ("-break".equals(args[i])) {
+ breakOnEx = true;
+ } else if ("-shutdown".equals(args[i])) {
+ shutdown = true;
+ } else if ("-stats".equals(args[i])) {
+ stats = Integer.parseInt(args[++i]);
+ System.out.println("Stats every "+stats+" message");
+ } else if ("-sendoptions".equals(args[i])) {
+ channelOptions = Integer.parseInt(args[++i]);
+ System.out.println("Setting send options to "+channelOptions);
+ } else if ("-startoptions".equals(args[i])) {
+ startoptions = Integer.parseInt(args[++i]);
+ System.out.println("Setting start options to "+startoptions);
+ } else if ("-size".equals(args[i])) {
+ size = Integer.parseInt(args[++i])-4;
+ System.out.println("Message size will be:"+(size+4)+" bytes");
+ } else if ("-mode".equals(args[i])) {
+ if ( "receive".equals(args[++i]) ) send = false;
+ } else if ("-debug".equals(args[i])) {
+ debug = true;
+ } else if ("-help".equals(args[i]))
+ {
+ usage();
+ System.exit(1);
+ }
+ }
+
+ ManagedChannel channel = (ManagedChannel)ChannelCreator.createChannel(args);
+
+ LoadTest test = new LoadTest(channel,send,count,debug,pause,stats,breakOnEx);
+ test.channelOptions = channelOptions;
+ LoadMessage msg = new LoadMessage();
+
+ messageSize = LoadMessage.getMessageSize(msg);
+ channel.addChannelListener(test);
+ channel.addMembershipListener(test);
+ channel.start(startoptions);
+ Runtime.getRuntime().addShutdownHook(new Shutdown(channel));
+ while ( threads > 1 ) {
+ Thread t = new Thread(test);
+ t.setDaemon(true);
+ t.start();
+ threads--;
+ test = new LoadTest(channel,send,count,debug,pause,stats,breakOnEx);
+ test.channelOptions = channelOptions;
+ }
+ test.run();
+ if ( shutdown && send ) channel.stop(channel.DEFAULT);
+ System.out.println("System test complete, sleeping to let threads finish.");
+ Thread.sleep(60*1000*60);
+ }
+
+ public static class Shutdown extends Thread {
+ ManagedChannel channel = null;
+ public Shutdown(ManagedChannel channel) {
+ this.channel = channel;
+ }
+
+ public void run() {
+ System.out.println("Shutting down...");
+ SystemExit exit = new SystemExit(5000);
+ exit.setDaemon(true);
+ exit.start();
+ try {
+ channel.stop(channel.DEFAULT);
+
+ }catch ( Exception x ) {
+ x.printStackTrace();
+ }
+ System.out.println("Channel stopped.");
+ }
+ }
+ public static class SystemExit extends Thread {
+ private long delay;
+ public SystemExit(long delay) {
+ this.delay = delay;
+ }
+ public void run () {
+ try {
+ Thread.sleep(delay);
+ }catch ( Exception x ) {
+ x.printStackTrace();
+ }
+ System.exit(0);
+
+ }
+ }
+
}
\ 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
- */\r
-package org.apache.catalina.tribes.test.channel;\r
-\r
-import org.apache.catalina.tribes.group.GroupChannel;\r
-import junit.framework.TestCase;\r
-\r
-/**\r
- * @author Filip Hanik\r
- * @version 1.0\r
- */\r
-public class ChannelStartStop extends TestCase {\r
- GroupChannel channel = null;\r
- protected void setUp() throws Exception {\r
- super.setUp();\r
- channel = new GroupChannel();\r
- }\r
-\r
- protected void tearDown() throws Exception {\r
- super.tearDown();\r
- try {channel.stop(channel.DEFAULT);}catch (Exception ignore){}\r
- }\r
- \r
- public void testDoubleFullStart() throws Exception {\r
- int count = 0;\r
- try {\r
- channel.start(channel.DEFAULT);\r
- count++;\r
- } catch ( Exception x){x.printStackTrace();}\r
- try {\r
- channel.start(channel.DEFAULT);\r
- count++;\r
- } catch ( Exception x){x.printStackTrace();}\r
- assertEquals(count,2);\r
- channel.stop(channel.DEFAULT);\r
- }\r
-\r
- public void testDoublePartialStart() throws Exception {\r
- //try to double start the RX \r
- int count = 0;\r
- try {\r
- channel.start(channel.SND_RX_SEQ);\r
- channel.start(channel.MBR_RX_SEQ);\r
- count++;\r
- } catch ( Exception x){x.printStackTrace();}\r
- try {\r
- channel.start(channel.MBR_RX_SEQ);\r
- count++;\r
- } catch ( Exception x){/*expected*/}\r
- assertEquals(count,1);\r
- channel.stop(channel.DEFAULT);\r
- //double the membership sender\r
- count = 0;\r
- try {\r
- channel.start(channel.SND_RX_SEQ);\r
- channel.start(channel.MBR_TX_SEQ);\r
- count++;\r
- } catch ( Exception x){x.printStackTrace();}\r
- try {\r
- channel.start(channel.MBR_TX_SEQ);\r
- count++;\r
- } catch ( Exception x){/*expected*/}\r
- assertEquals(count,1);\r
- channel.stop(channel.DEFAULT);\r
- \r
- count = 0;\r
- try {\r
- channel.start(channel.SND_RX_SEQ);\r
- count++;\r
- } catch ( Exception x){x.printStackTrace();}\r
- try {\r
- channel.start(channel.SND_RX_SEQ);\r
- count++;\r
- } catch ( Exception x){/*expected*/}\r
- assertEquals(count,1);\r
- channel.stop(channel.DEFAULT);\r
-\r
- count = 0;\r
- try {\r
- channel.start(channel.SND_TX_SEQ);\r
- count++;\r
- } catch ( Exception x){x.printStackTrace();}\r
- try {\r
- channel.start(channel.SND_TX_SEQ);\r
- count++;\r
- } catch ( Exception x){/*expected*/}\r
- assertEquals(count,1);\r
- channel.stop(channel.DEFAULT);\r
- }\r
- \r
- public void testFalseOption() throws Exception {\r
- int flag = 0xFFF0;//should get ignored by the underlying components\r
- int count = 0;\r
- try {\r
- channel.start(flag);\r
- count++;\r
- } catch ( Exception x){x.printStackTrace();}\r
- try {\r
- channel.start(flag);\r
- count++;\r
- } catch ( Exception x){/*expected*/}\r
- assertEquals(count,2);\r
- channel.stop(channel.DEFAULT);\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
+ */
+package org.apache.catalina.tribes.test.channel;
+
+import org.apache.catalina.tribes.group.GroupChannel;
+import junit.framework.TestCase;
+
+/**
+ * @author Filip Hanik
+ * @version 1.0
+ */
+public class ChannelStartStop extends TestCase {
+ GroupChannel channel = null;
+ protected void setUp() throws Exception {
+ super.setUp();
+ channel = new GroupChannel();
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ try {channel.stop(channel.DEFAULT);}catch (Exception ignore){}
+ }
+
+ public void testDoubleFullStart() throws Exception {
+ int count = 0;
+ try {
+ channel.start(channel.DEFAULT);
+ count++;
+ } catch ( Exception x){x.printStackTrace();}
+ try {
+ channel.start(channel.DEFAULT);
+ count++;
+ } catch ( Exception x){x.printStackTrace();}
+ assertEquals(count,2);
+ channel.stop(channel.DEFAULT);
+ }
+
+ public void testDoublePartialStart() throws Exception {
+ //try to double start the RX
+ int count = 0;
+ try {
+ channel.start(channel.SND_RX_SEQ);
+ channel.start(channel.MBR_RX_SEQ);
+ count++;
+ } catch ( Exception x){x.printStackTrace();}
+ try {
+ channel.start(channel.MBR_RX_SEQ);
+ count++;
+ } catch ( Exception x){/*expected*/}
+ assertEquals(count,1);
+ channel.stop(channel.DEFAULT);
+ //double the membership sender
+ count = 0;
+ try {
+ channel.start(channel.SND_RX_SEQ);
+ channel.start(channel.MBR_TX_SEQ);
+ count++;
+ } catch ( Exception x){x.printStackTrace();}
+ try {
+ channel.start(channel.MBR_TX_SEQ);
+ count++;
+ } catch ( Exception x){/*expected*/}
+ assertEquals(count,1);
+ channel.stop(channel.DEFAULT);
+
+ count = 0;
+ try {
+ channel.start(channel.SND_RX_SEQ);
+ count++;
+ } catch ( Exception x){x.printStackTrace();}
+ try {
+ channel.start(channel.SND_RX_SEQ);
+ count++;
+ } catch ( Exception x){/*expected*/}
+ assertEquals(count,1);
+ channel.stop(channel.DEFAULT);
+
+ count = 0;
+ try {
+ channel.start(channel.SND_TX_SEQ);
+ count++;
+ } catch ( Exception x){x.printStackTrace();}
+ try {
+ channel.start(channel.SND_TX_SEQ);
+ count++;
+ } catch ( Exception x){/*expected*/}
+ assertEquals(count,1);
+ channel.stop(channel.DEFAULT);
+ }
+
+ public void testFalseOption() throws Exception {
+ int flag = 0xFFF0;//should get ignored by the underlying components
+ int count = 0;
+ try {
+ channel.start(flag);
+ count++;
+ } catch ( Exception x){x.printStackTrace();}
+ try {
+ channel.start(flag);
+ count++;
+ } catch ( Exception x){/*expected*/}
+ assertEquals(count,2);
+ channel.stop(channel.DEFAULT);
+ }
+
+}
-package org.apache.catalina.tribes.test.channel;\r
-\r
-import junit.framework.TestCase;\r
-import java.io.Serializable;\r
-import java.util.Random;\r
-import java.util.Arrays;\r
-import org.apache.catalina.tribes.ChannelListener;\r
-import org.apache.catalina.tribes.Member;\r
-import org.apache.catalina.tribes.group.GroupChannel;\r
-import java.io.PrintStream;\r
-\r
-/**\r
- * <p>Title: </p> \r
- * \r
- * <p>Description: </p> \r
- * \r
- * <p>Copyright: Copyright (c) 2005</p> \r
- * \r
- * <p>Company: </p>\r
- * \r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-public class TestRemoteProcessException extends TestCase {\r
- int msgCount = 10000;\r
- GroupChannel channel1;\r
- GroupChannel channel2;\r
- Listener listener1;\r
- protected void setUp() throws Exception {\r
- super.setUp();\r
- channel1 = new GroupChannel();\r
- channel2 = new GroupChannel();\r
- listener1 = new Listener();\r
- channel2.addChannelListener(listener1);\r
- channel1.start(GroupChannel.DEFAULT);\r
- channel2.start(GroupChannel.DEFAULT);\r
- }\r
-\r
- protected void tearDown() throws Exception {\r
- super.tearDown();\r
- channel1.stop(GroupChannel.DEFAULT);\r
- channel2.stop(GroupChannel.DEFAULT);\r
- }\r
-\r
- public void testDataSendSYNCACK() throws Exception {\r
- System.err.println("Starting SYNC_ACK");\r
- int errC=0, nerrC=0;\r
- for (int i=0; i<msgCount; i++) {\r
- boolean error = Data.r.nextBoolean();\r
- channel1.send(channel1.getMembers(),Data.createRandomData(error),GroupChannel.SEND_OPTIONS_SYNCHRONIZED_ACK|GroupChannel.SEND_OPTIONS_USE_ACK);\r
- if ( error ) errC++; else nerrC++;\r
- }\r
- System.err.println("Finished SYNC_ACK");\r
- assertEquals("Checking failure messages.",errC,listener1.errCnt);\r
- assertEquals("Checking success messages.",nerrC,listener1.noErrCnt);\r
- assertEquals("Checking all messages.",msgCount,listener1.noErrCnt+listener1.errCnt);\r
- System.out.println("Listener 1 stats:");\r
- listener1.printStats(System.out);\r
- }\r
-\r
- public static class Listener implements ChannelListener {\r
- long noErrCnt = 0;\r
- long errCnt = 0;\r
- public boolean accept(Serializable s, Member m) {\r
- return (s instanceof Data);\r
- }\r
-\r
- public void messageReceived(Serializable s, Member m) {\r
- Data d = (Data)s;\r
- if ( !Data.verify(d) ) {\r
- System.err.println("ERROR");\r
- } else {\r
- if (d.error) {\r
- errCnt++;\r
- if ( (errCnt % 100) == 0) {\r
- printStats(System.err);\r
- }\r
- throw new IllegalArgumentException();\r
- } else {\r
- noErrCnt++;\r
- if ( (noErrCnt % 100) == 0) {\r
- printStats(System.err);\r
- }\r
- }\r
- }\r
- }\r
-\r
- public void printStats(PrintStream stream) {\r
- stream.println("NORMAL:" + noErrCnt);\r
- stream.println("FAILURES:" + errCnt);\r
- stream.println("TOTAL:" + (errCnt+noErrCnt));\r
- }\r
- }\r
-\r
- public static class Data implements Serializable {\r
- public int length;\r
- public byte[] data;\r
- public byte key;\r
- public boolean error = false;\r
- public static Random r = new Random(System.currentTimeMillis());\r
- public static Data createRandomData(boolean error) {\r
- int i = r.nextInt();\r
- i = ( i % 127 );\r
- int length = Math.abs(r.nextInt() % 65555);\r
- Data d = new Data();\r
- d.length = length;\r
- d.key = (byte)i;\r
- d.data = new byte[length];\r
- Arrays.fill(d.data,d.key);\r
- d.error = error;\r
- return d;\r
- }\r
-\r
- public static boolean verify(Data d) {\r
- boolean result = (d.length == d.data.length);\r
- for ( int i=0; result && (i<d.data.length); i++ ) result = result && d.data[i] == d.key;\r
- return result;\r
- }\r
- }\r
-\r
-\r
-\r
-}\r
+package org.apache.catalina.tribes.test.channel;
+
+import junit.framework.TestCase;
+import java.io.Serializable;
+import java.util.Random;
+import java.util.Arrays;
+import org.apache.catalina.tribes.ChannelListener;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.group.GroupChannel;
+import java.io.PrintStream;
+
+/**
+ * <p>Title: </p>
+ *
+ * <p>Description: </p>
+ *
+ * <p>Copyright: Copyright (c) 2005</p>
+ *
+ * <p>Company: </p>
+ *
+ * @author not attributable
+ * @version 1.0
+ */
+public class TestRemoteProcessException extends TestCase {
+ int msgCount = 10000;
+ GroupChannel channel1;
+ GroupChannel channel2;
+ Listener listener1;
+ protected void setUp() throws Exception {
+ super.setUp();
+ channel1 = new GroupChannel();
+ channel2 = new GroupChannel();
+ listener1 = new Listener();
+ channel2.addChannelListener(listener1);
+ channel1.start(GroupChannel.DEFAULT);
+ channel2.start(GroupChannel.DEFAULT);
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ channel1.stop(GroupChannel.DEFAULT);
+ channel2.stop(GroupChannel.DEFAULT);
+ }
+
+ public void testDataSendSYNCACK() throws Exception {
+ System.err.println("Starting SYNC_ACK");
+ int errC=0, nerrC=0;
+ for (int i=0; i<msgCount; i++) {
+ boolean error = Data.r.nextBoolean();
+ channel1.send(channel1.getMembers(),Data.createRandomData(error),GroupChannel.SEND_OPTIONS_SYNCHRONIZED_ACK|GroupChannel.SEND_OPTIONS_USE_ACK);
+ if ( error ) errC++; else nerrC++;
+ }
+ System.err.println("Finished SYNC_ACK");
+ assertEquals("Checking failure messages.",errC,listener1.errCnt);
+ assertEquals("Checking success messages.",nerrC,listener1.noErrCnt);
+ assertEquals("Checking all messages.",msgCount,listener1.noErrCnt+listener1.errCnt);
+ System.out.println("Listener 1 stats:");
+ listener1.printStats(System.out);
+ }
+
+ public static class Listener implements ChannelListener {
+ long noErrCnt = 0;
+ long errCnt = 0;
+ public boolean accept(Serializable s, Member m) {
+ return (s instanceof Data);
+ }
+
+ public void messageReceived(Serializable s, Member m) {
+ Data d = (Data)s;
+ if ( !Data.verify(d) ) {
+ System.err.println("ERROR");
+ } else {
+ if (d.error) {
+ errCnt++;
+ if ( (errCnt % 100) == 0) {
+ printStats(System.err);
+ }
+ throw new IllegalArgumentException();
+ } else {
+ noErrCnt++;
+ if ( (noErrCnt % 100) == 0) {
+ printStats(System.err);
+ }
+ }
+ }
+ }
+
+ public void printStats(PrintStream stream) {
+ stream.println("NORMAL:" + noErrCnt);
+ stream.println("FAILURES:" + errCnt);
+ stream.println("TOTAL:" + (errCnt+noErrCnt));
+ }
+ }
+
+ public static class Data implements Serializable {
+ public int length;
+ public byte[] data;
+ public byte key;
+ public boolean error = false;
+ public static Random r = new Random(System.currentTimeMillis());
+ public static Data createRandomData(boolean error) {
+ int i = r.nextInt();
+ i = ( i % 127 );
+ int length = Math.abs(r.nextInt() % 65555);
+ Data d = new Data();
+ d.length = length;
+ d.key = (byte)i;
+ d.data = new byte[length];
+ Arrays.fill(d.data,d.key);
+ d.error = error;
+ return d;
+ }
+
+ public static boolean verify(Data d) {
+ boolean result = (d.length == d.data.length);
+ for ( int i=0; result && (i<d.data.length); i++ ) result = result && d.data[i] == d.key;
+ return result;
+ }
+ }
+
+
+
+}
-/*\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
- */\r
-\r
-package org.apache.catalina.tribes.test.interceptors;\r
-\r
-import junit.framework.TestCase;\r
-\r
-/**\r
- * <p>Title: </p> \r
- * \r
- * <p>Description: </p> \r
- * \r
- * <p>Copyright: Copyright (c) 2005</p> \r
- * \r
- * <p>Company: </p>\r
- * \r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-public class TestTwoPhaseCommit extends TestCase {\r
-\r
- protected void setUp() throws Exception {\r
- super.setUp();\r
- }\r
-\r
- protected void tearDown() throws Exception {\r
- super.tearDown();\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
+ */
+
+package org.apache.catalina.tribes.test.interceptors;
+
+import junit.framework.TestCase;
+
+/**
+ * <p>Title: </p>
+ *
+ * <p>Description: </p>
+ *
+ * <p>Copyright: Copyright (c) 2005</p>
+ *
+ * <p>Company: </p>
+ *
+ * @author not attributable
+ * @version 1.0
+ */
+public class TestTwoPhaseCommit extends TestCase {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+}
-/*\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
- */\r
-package org.apache.catalina.tribes.test.membership;\r
-\r
-import junit.framework.TestCase;\r
-import org.apache.catalina.tribes.membership.MemberImpl;\r
-import java.util.Arrays;\r
-\r
-/**\r
- * <p>Title: </p>\r
- *\r
- * <p>Description: </p>\r
- *\r
- * <p>Copyright: Copyright (c) 2005</p>\r
- *\r
- * <p>Company: </p>\r
- *\r
- * @author not attributable\r
- * @version 1.0\r
- */\r
-public class MemberSerialization extends TestCase {\r
- MemberImpl m1, m2, p1,p2;\r
- byte[] payload = null;\r
- protected void setUp() throws Exception {\r
- super.setUp();\r
- payload = new byte[333];\r
- Arrays.fill(payload,(byte)1);\r
- m1 = new MemberImpl("localhost",3333,1,payload);\r
- m2 = new MemberImpl("localhost",3333,1);\r
- payload = new byte[333];\r
- Arrays.fill(payload,(byte)2);\r
- p1 = new MemberImpl("127.0.0.1",3333,1,payload);\r
- p2 = new MemberImpl("localhost",3331,1,payload);\r
- m1.setDomain(new byte[] {1,2,3,4,5,6,7,8,9});\r
- m2.setDomain(new byte[] {1,2,3,4,5,6,7,8,9});\r
- m1.setCommand(new byte[] {1,2,4,5,6,7,8,9});\r
- m2.setCommand(new byte[] {1,2,4,5,6,7,8,9});\r
- }\r
- \r
- public void testCompare() throws Exception {\r
- assertTrue(m1.equals(m2));\r
- assertTrue(m2.equals(m1));\r
- assertTrue(p1.equals(m2));\r
- assertFalse(m1.equals(p2));\r
- assertFalse(m1.equals(p2));\r
- assertFalse(m2.equals(p2));\r
- assertFalse(p1.equals(p2));\r
- }\r
- \r
- public void testSerializationOne() throws Exception {\r
- MemberImpl m = m1;\r
- byte[] md1 = m.getData(false,true);\r
- byte[] mda1 = m.getData(false,false);\r
- assertTrue(Arrays.equals(md1,mda1));\r
- assertTrue(md1==mda1);\r
- mda1 = m.getData(true,true);\r
- MemberImpl ma1 = MemberImpl.getMember(mda1);\r
- assertTrue(compareMembers(m,ma1));\r
- mda1 = p1.getData(false);\r
- assertFalse(Arrays.equals(md1,mda1));\r
- ma1 = MemberImpl.getMember(mda1);\r
- assertTrue(compareMembers(p1,ma1));\r
- \r
- md1 = m.getData(true,true);\r
- Thread.sleep(50);\r
- mda1 = m.getData(true,true);\r
- MemberImpl a1 = MemberImpl.getMember(md1);\r
- MemberImpl a2 = MemberImpl.getMember(mda1);\r
- assertTrue(a1.equals(a2));\r
- assertFalse(Arrays.equals(md1,mda1));\r
- \r
- \r
- }\r
- \r
- public boolean compareMembers(MemberImpl impl1, MemberImpl impl2) {\r
- boolean result = true;\r
- result = result && Arrays.equals(impl1.getHost(),impl2.getHost());\r
- result = result && Arrays.equals(impl1.getPayload(),impl2.getPayload());\r
- result = result && Arrays.equals(impl1.getUniqueId(),impl2.getUniqueId());\r
- result = result && impl1.getPort() == impl2.getPort();\r
- return result;\r
- }\r
-\r
- protected void tearDown() throws Exception {\r
- super.tearDown();\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
+ */
+package org.apache.catalina.tribes.test.membership;
+
+import junit.framework.TestCase;
+import org.apache.catalina.tribes.membership.MemberImpl;
+import java.util.Arrays;
+
+/**
+ * <p>Title: </p>
+ *
+ * <p>Description: </p>
+ *
+ * <p>Copyright: Copyright (c) 2005</p>
+ *
+ * <p>Company: </p>
+ *
+ * @author not attributable
+ * @version 1.0
+ */
+public class MemberSerialization extends TestCase {
+ MemberImpl m1, m2, p1,p2;
+ byte[] payload = null;
+ protected void setUp() throws Exception {
+ super.setUp();
+ payload = new byte[333];
+ Arrays.fill(payload,(byte)1);
+ m1 = new MemberImpl("localhost",3333,1,payload);
+ m2 = new MemberImpl("localhost",3333,1);
+ payload = new byte[333];
+ Arrays.fill(payload,(byte)2);
+ p1 = new MemberImpl("127.0.0.1",3333,1,payload);
+ p2 = new MemberImpl("localhost",3331,1,payload);
+ m1.setDomain(new byte[] {1,2,3,4,5,6,7,8,9});
+ m2.setDomain(new byte[] {1,2,3,4,5,6,7,8,9});
+ m1.setCommand(new byte[] {1,2,4,5,6,7,8,9});
+ m2.setCommand(new byte[] {1,2,4,5,6,7,8,9});
+ }
+
+ public void testCompare() throws Exception {
+ assertTrue(m1.equals(m2));
+ assertTrue(m2.equals(m1));
+ assertTrue(p1.equals(m2));
+ assertFalse(m1.equals(p2));
+ assertFalse(m1.equals(p2));
+ assertFalse(m2.equals(p2));
+ assertFalse(p1.equals(p2));
+ }
+
+ public void testSerializationOne() throws Exception {
+ MemberImpl m = m1;
+ byte[] md1 = m.getData(false,true);
+ byte[] mda1 = m.getData(false,false);
+ assertTrue(Arrays.equals(md1,mda1));
+ assertTrue(md1==mda1);
+ mda1 = m.getData(true,true);
+ MemberImpl ma1 = MemberImpl.getMember(mda1);
+ assertTrue(compareMembers(m,ma1));
+ mda1 = p1.getData(false);
+ assertFalse(Arrays.equals(md1,mda1));
+ ma1 = MemberImpl.getMember(mda1);
+ assertTrue(compareMembers(p1,ma1));
+
+ md1 = m.getData(true,true);
+ Thread.sleep(50);
+ mda1 = m.getData(true,true);
+ MemberImpl a1 = MemberImpl.getMember(md1);
+ MemberImpl a2 = MemberImpl.getMember(mda1);
+ assertTrue(a1.equals(a2));
+ assertFalse(Arrays.equals(md1,mda1));
+
+
+ }
+
+ public boolean compareMembers(MemberImpl impl1, MemberImpl impl2) {
+ boolean result = true;
+ result = result && Arrays.equals(impl1.getHost(),impl2.getHost());
+ result = result && Arrays.equals(impl1.getPayload(),impl2.getPayload());
+ result = result && Arrays.equals(impl1.getUniqueId(),impl2.getUniqueId());
+ result = result && impl1.getPort() == impl2.getPort();
+ return result;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+}
-package org.apache.catalina.tribes.test.membership;\r
-\r
-import java.util.ArrayList;\r
-\r
-import org.apache.catalina.tribes.Channel;\r
-import org.apache.catalina.tribes.ManagedChannel;\r
-import org.apache.catalina.tribes.Member;\r
-import org.apache.catalina.tribes.MembershipListener;\r
-import org.apache.catalina.tribes.group.GroupChannel;\r
-import junit.framework.TestCase;\r
-import org.apache.catalina.tribes.group.interceptors.DomainFilterInterceptor;\r
-import org.apache.catalina.tribes.util.UUIDGenerator;\r
-\r
-public class TestDomainFilter\r
- extends TestCase {\r
- private static int count = 10;\r
- private ManagedChannel[] channels = new ManagedChannel[count];\r
- private TestMbrListener[] listeners = new TestMbrListener[count];\r
-\r
- protected void setUp() throws Exception {\r
- super.setUp();\r
- for (int i = 0; i < channels.length; i++) {\r
- channels[i] = new GroupChannel();\r
- channels[i].getMembershipService().setPayload( ("Channel-" + (i + 1)).getBytes("ASCII"));\r
- listeners[i] = new TestMbrListener( ("Listener-" + (i + 1)));\r
- channels[i].addMembershipListener(listeners[i]);\r
- DomainFilterInterceptor filter = new DomainFilterInterceptor();\r
- filter.setDomain(UUIDGenerator.randomUUID(false));\r
- channels[i].addInterceptor(filter);\r
- }\r
- }\r
-\r
- public void clear() {\r
- for (int i = 0; i < channels.length; i++) {\r
- listeners[i].members.clear();\r
- }\r
- }\r
-\r
- public void testMemberArrival() throws Exception {\r
- //purpose of this test is to make sure that we have received all the members\r
- //that we can expect before the start method returns\r
- Thread[] threads = new Thread[channels.length];\r
- for (int i=0; i<channels.length; i++ ) {\r
- final Channel channel = channels[i];\r
- Thread t = new Thread() {\r
- public void run() {\r
- try {\r
- channel.start(Channel.DEFAULT);\r
- }catch ( Exception x ) {\r
- throw new RuntimeException(x);\r
- }\r
- }\r
- };\r
- threads[i] = t;\r
- }\r
- for (int i=0; i<threads.length; i++ ) threads[i].start();\r
- for (int i=0; i<threads.length; i++ ) threads[i].join();\r
- System.out.println("All channels started.");\r
- for (int i=listeners.length-1; i>=0; i-- ) assertEquals("Checking member arrival length",0,listeners[i].members.size());\r
- }\r
-\r
- protected void tearDown() throws Exception {\r
-\r
- for (int i = 0; i < channels.length; i++) {\r
- try {\r
- channels[i].stop(Channel.DEFAULT);\r
- } catch (Exception ignore) {}\r
- }\r
- super.tearDown();\r
- }\r
-\r
- public class TestMbrListener\r
- implements MembershipListener {\r
- public String name = null;\r
- public TestMbrListener(String name) {\r
- this.name = name;\r
- }\r
-\r
- public ArrayList members = new ArrayList();\r
- public void memberAdded(Member member) {\r
- if (!members.contains(member)) {\r
- members.add(member);\r
- try {\r
- System.out.println(name + ":member added[" + new String(member.getPayload(), "ASCII") + "; Thread:"+Thread.currentThread().getName()+"]");\r
- } catch (Exception x) {\r
- System.out.println(name + ":member added[unknown]");\r
- }\r
- }\r
- }\r
-\r
- public void memberDisappeared(Member member) {\r
- if (members.contains(member)) {\r
- members.remove(member);\r
- try {\r
- System.out.println(name + ":member disappeared[" + new String(member.getPayload(), "ASCII") + "; Thread:"+Thread.currentThread().getName()+"]");\r
- } catch (Exception x) {\r
- System.out.println(name + ":member disappeared[unknown]");\r
- }\r
- }\r
- }\r
-\r
- }\r
-\r
-}\r
+package org.apache.catalina.tribes.test.membership;
+
+import java.util.ArrayList;
+
+import org.apache.catalina.tribes.Channel;
+import org.apache.catalina.tribes.ManagedChannel;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.MembershipListener;
+import org.apache.catalina.tribes.group.GroupChannel;
+import junit.framework.TestCase;
+import org.apache.catalina.tribes.group.interceptors.DomainFilterInterceptor;
+import org.apache.catalina.tribes.util.UUIDGenerator;
+
+public class TestDomainFilter
+ extends TestCase {
+ private static int count = 10;
+ private ManagedChannel[] channels = new ManagedChannel[count];
+ private TestMbrListener[] listeners = new TestMbrListener[count];
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ for (int i = 0; i < channels.length; i++) {
+ channels[i] = new GroupChannel();
+ channels[i].getMembershipService().setPayload( ("Channel-" + (i + 1)).getBytes("ASCII"));
+ listeners[i] = new TestMbrListener( ("Listener-" + (i + 1)));
+ channels[i].addMembershipListener(listeners[i]);
+ DomainFilterInterceptor filter = new DomainFilterInterceptor();
+ filter.setDomain(UUIDGenerator.randomUUID(false));
+ channels[i].addInterceptor(filter);
+ }
+ }
+
+ public void clear() {
+ for (int i = 0; i < channels.length; i++) {
+ listeners[i].members.clear();
+ }
+ }
+
+ public void testMemberArrival() throws Exception {
+ //purpose of this test is to make sure that we have received all the members
+ //that we can expect before the start method returns
+ Thread[] threads = new Thread[channels.length];
+ for (int i=0; i<channels.length; i++ ) {
+ final Channel channel = channels[i];
+ Thread t = new Thread() {
+ public void run() {
+ try {
+ channel.start(Channel.DEFAULT);
+ }catch ( Exception x ) {
+ throw new RuntimeException(x);
+ }
+ }
+ };
+ threads[i] = t;
+ }
+ for (int i=0; i<threads.length; i++ ) threads[i].start();
+ for (int i=0; i<threads.length; i++ ) threads[i].join();
+ System.out.println("All channels started.");
+ for (int i=listeners.length-1; i>=0; i-- ) assertEquals("Checking member arrival length",0,listeners[i].members.size());
+ }
+
+ protected void tearDown() throws Exception {
+
+ for (int i = 0; i < channels.length; i++) {
+ try {
+ channels[i].stop(Channel.DEFAULT);
+ } catch (Exception ignore) {}
+ }
+ super.tearDown();
+ }
+
+ public class TestMbrListener
+ implements MembershipListener {
+ public String name = null;
+ public TestMbrListener(String name) {
+ this.name = name;
+ }
+
+ public ArrayList members = new ArrayList();
+ public void memberAdded(Member member) {
+ if (!members.contains(member)) {
+ members.add(member);
+ try {
+ System.out.println(name + ":member added[" + new String(member.getPayload(), "ASCII") + "; Thread:"+Thread.currentThread().getName()+"]");
+ } catch (Exception x) {
+ System.out.println(name + ":member added[unknown]");
+ }
+ }
+ }
+
+ public void memberDisappeared(Member member) {
+ if (members.contains(member)) {
+ members.remove(member);
+ try {
+ System.out.println(name + ":member disappeared[" + new String(member.getPayload(), "ASCII") + "; Thread:"+Thread.currentThread().getName()+"]");
+ } catch (Exception x) {
+ System.out.println(name + ":member disappeared[unknown]");
+ }
+ }
+ }
+
+ }
+
+}
-package org.apache.catalina.tribes.test.transport;\r
-\r
-import java.io.OutputStream;\r
-import java.net.Socket;\r
-import java.text.DecimalFormat;\r
-import org.apache.catalina.tribes.membership.MemberImpl;\r
-import org.apache.catalina.tribes.io.XByteBuffer;\r
-import org.apache.catalina.tribes.Member;\r
-import org.apache.catalina.tribes.io.ChannelData;\r
-import org.apache.catalina.tribes.Channel;\r
-import java.math.BigDecimal;\r
-\r
-public class SocketSend {\r
-\r
- public static void main(String[] args) throws Exception {\r
- \r
- \r
- Member mbr = new MemberImpl("localhost", 9999, 0);\r
- ChannelData data = new ChannelData();\r
- data.setOptions(Channel.SEND_OPTIONS_BYTE_MESSAGE);\r
- data.setAddress(mbr);\r
- byte[] buf = new byte[8192 * 4];\r
- data.setMessage(new XByteBuffer(buf,false));\r
- buf = XByteBuffer.createDataPackage(data);\r
- int len = buf.length;\r
- System.out.println("Message size:"+len+" bytes");\r
- BigDecimal total = new BigDecimal((double)0);\r
- BigDecimal bytes = new BigDecimal((double)len);\r
- Socket socket = new Socket("localhost",9999);\r
- System.out.println("Writing to 9999");\r
- OutputStream out = socket.getOutputStream();\r
- long start = 0;\r
- double mb = 0;\r
- boolean first = true;\r
- int count = 0;\r
- DecimalFormat df = new DecimalFormat("##.00");\r
- while ( count<100000 ) {\r
- if ( first ) { first = false; start = System.currentTimeMillis();}\r
- out.write(buf,0,buf.length);\r
- mb += ( (double) buf.length) / 1024 / 1024;\r
- total = total.add(bytes);\r
- if ( ((++count) % 10000) == 0 ) {\r
- long time = System.currentTimeMillis();\r
- double seconds = ((double)(time-start))/1000;\r
- System.out.println("Throughput "+df.format(mb/seconds)+" MB/seconds messages "+count+", total "+mb+" MB, total "+total+" bytes.");\r
- }\r
- }\r
- out.flush(); \r
- System.out.println("Complete, sleeping 5 seconds");\r
- Thread.sleep(5000);\r
-\r
- }\r
-}\r
+package org.apache.catalina.tribes.test.transport;
+
+import java.io.OutputStream;
+import java.net.Socket;
+import java.text.DecimalFormat;
+import org.apache.catalina.tribes.membership.MemberImpl;
+import org.apache.catalina.tribes.io.XByteBuffer;
+import org.apache.catalina.tribes.Member;
+import org.apache.catalina.tribes.io.ChannelData;
+import org.apache.catalina.tribes.Channel;
+import java.math.BigDecimal;
+
+public class SocketSend {
+
+ public static void main(String[] args) throws Exception {
+
+
+ Member mbr = new MemberImpl("localhost", 9999, 0);
+ ChannelData data = new ChannelData();
+ data.setOptions(Channel.SEND_OPTIONS_BYTE_MESSAGE);
+ data.setAddress(mbr);
+ byte[] buf = new byte[8192 * 4];
+ data.setMessage(new XByteBuffer(buf,false));
+ buf = XByteBuffer.createDataPackage(data);
+ int len = buf.length;
+ System.out.println("Message size:"+len+" bytes");
+ BigDecimal total = new BigDecimal((double)0);
+ BigDecimal bytes = new BigDecimal((double)len);
+ Socket socket = new Socket("localhost",9999);
+ System.out.println("Writing to 9999");
+ OutputStream out = socket.getOutputStream();
+ long start = 0;
+ double mb = 0;
+ boolean first = true;
+ int count = 0;
+ DecimalFormat df = new DecimalFormat("##.00");
+ while ( count<100000 ) {
+ if ( first ) { first = false; start = System.currentTimeMillis();}
+ out.write(buf,0,buf.length);
+ mb += ( (double) buf.length) / 1024 / 1024;
+ total = total.add(bytes);
+ if ( ((++count) % 10000) == 0 ) {
+ long time = System.currentTimeMillis();
+ double seconds = ((double)(time-start))/1000;
+ System.out.println("Throughput "+df.format(mb/seconds)+" MB/seconds messages "+count+", total "+mb+" MB, total "+total+" bytes.");
+ }
+ }
+ out.flush();
+ System.out.println("Complete, sleeping 5 seconds");
+ Thread.sleep(5000);
+
+ }
+}