KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > management > TestMain


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.enterprise.management;
24
25 import java.util.Map JavaDoc;
26 import java.util.Set JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.Collection JavaDoc;
31 import java.util.Collections JavaDoc;
32 import java.util.Properties JavaDoc;
33
34 import java.lang.reflect.Method JavaDoc;
35
36 import java.io.File JavaDoc;
37 import java.io.IOException JavaDoc;
38 import java.io.FileInputStream JavaDoc;
39 import java.io.FileNotFoundException JavaDoc;
40 import java.io.ByteArrayInputStream JavaDoc;
41 import java.util.Properties JavaDoc;
42
43 import javax.management.MBeanServer JavaDoc;
44 import javax.management.MBeanServerFactory JavaDoc;
45 import javax.management.ObjectName JavaDoc;
46 import javax.management.remote.JMXConnector JavaDoc;
47 import javax.management.NotificationListener JavaDoc;
48 import javax.management.Notification JavaDoc;
49 import javax.management.remote.JMXConnectionNotification JavaDoc;
50 import javax.management.MBeanServerConnection JavaDoc;
51
52 import com.sun.appserv.management.DomainRoot;
53 import com.sun.appserv.management.base.SystemInfo;
54
55 import com.sun.appserv.management.base.AMX;
56 import com.sun.appserv.management.base.AMXDebug;
57 import com.sun.appserv.management.base.XTypes;
58 import com.sun.appserv.management.base.Util;
59
60 import com.sun.appserv.management.client.TLSParams;
61 import com.sun.appserv.management.client.TrustStoreTrustManager;
62 import com.sun.appserv.management.client.ConnectionSource;
63 import com.sun.appserv.management.client.AppserverConnectionSource;
64 import com.sun.appserv.management.client.HandshakeCompletedListenerImpl;
65
66
67 import com.sun.appserv.management.config.NodeAgentConfig;
68 import com.sun.appserv.management.config.JMXConnectorConfig;
69 import com.sun.appserv.management.config.OfflineConfigIniter;
70
71
72 import com.sun.appserv.management.util.misc.ExceptionUtil;
73 import com.sun.appserv.management.util.misc.StringUtil;
74 import com.sun.appserv.management.util.misc.MapUtil;
75 import com.sun.appserv.management.util.misc.GSetUtil;
76 import com.sun.appserv.management.util.misc.FileUtils;
77 import com.sun.appserv.management.util.misc.ClassUtil;
78 import com.sun.appserv.management.util.misc.CollectionUtil;
79 import com.sun.appserv.management.util.misc.TypeCast;
80 import com.sun.appserv.management.util.stringifier.ArrayStringifier;
81 import com.sun.appserv.management.util.stringifier.StringifierRegistryImpl;
82 import com.sun.appserv.management.util.stringifier.SmartStringifier;
83 import com.sun.appserv.management.util.jmx.stringifier.StringifierRegistryIniter;
84 import com.sun.appserv.management.util.jmx.JMXUtil;
85 import com.sun.appserv.management.util.jmx.MBeanServerConnectionSource;
86
87
88 import static com.sun.enterprise.management.PropertyKeys.*;
89 import com.sun.enterprise.management.monitor.AMXMonitorTestBase;
90
91
92 /**
93     Main class that runs all the unit tests
94  */

95 public final class TestMain implements NotificationListener JavaDoc
96 {
97     private final DomainRoot mDomainRoot;
98     private HandshakeCompletedListenerImpl mHandshakeCompletedListener;
99     
100     
101         private static void
102     printUsage()
103     {
104         println( "USAGE: java " + TestMain.class.getName() + " <properties-file> [name=value [name=value]*]" );
105         
106         final String JavaDoc example = MapUtil.toString( PropertyKeys.getDefaults(), "\n" ) +
107             "\n\nAdditional properties may be included and will be placed into a Map " +
108             "for use by any unit test.";
109         println( "Properties file format:\n" + example );
110         println( "" );
111         println( "The optional property " + StringUtil.quote(TEST_CLASSES_FILE_KEY) +
112             " may contain the name of a file which specifies which test classes to run. " +
113             "Files should be listed with fully-qualified classnames, one per line. " +
114             "The # character may be used to comment-out classnames."
115             );
116         println( "" );
117         println( "Additional properties may also be passed directly on the command line." );
118         println( "These override any properties found in the specified properties file." );
119         println( "[all properties intended for permanent use should be defined in PropertyKeys.java]" );
120         println( "EXAMPLE:" );
121         println( "java TestMain amxtest.properties amxtest.verbose=true my-temp=true" );
122     }
123     
124         
125         private static boolean
126     isHelp( final String JavaDoc s )
127     {
128         return( s.equals( "help" ) || s.equals( "--help" ) || s.equals( "-?" ) );
129     }
130     
131         protected static void
132     checkAssertsOn()
133     {
134         try
135         {
136             assert( false );
137             throw new Error JavaDoc( "Assertions must be enabled for unit tests" );
138         }
139         catch( AssertionError JavaDoc a )
140         {
141         }
142     }
143     
144     
145         private static Map JavaDoc<String JavaDoc,String JavaDoc>
146     argsToMap( final String JavaDoc[] args )
147     {
148         final Map JavaDoc<String JavaDoc,String JavaDoc> params = new HashMap JavaDoc<String JavaDoc,String JavaDoc>();
149         
150         params.put( DEFAULT_PROPERTIES_FILE, args[ 0 ] );
151         
152         for( int i = 1; i < args.length; ++i )
153         {
154             final String JavaDoc pair= args[ i ];
155             final int delimIndex = pair.indexOf( "=" );
156             String JavaDoc name = null;
157             String JavaDoc value = null;
158             if ( delimIndex < 0 )
159             {
160                 name = pair;
161                 value = null;
162             }
163             else
164             {
165                 name = pair.substring( 0, delimIndex);
166                 value = pair.substring( name.length() + 1, pair.length() );
167                 
168             }
169             params.put( name, value );
170         }
171         
172         return params;
173     }
174     
175         private static DomainRoot
176     initOffline( final File JavaDoc domainXML )
177     {
178         final MBeanServer JavaDoc server = MBeanServerFactory.createMBeanServer( "test" );
179         assert( domainXML.exists() && domainXML.length() != 0 );
180         
181         final OfflineConfigIniter initer = new OfflineConfigIniter( server, domainXML );
182         final DomainRoot domainRoot = initer.getDomainRoot();
183         
184         return domainRoot;
185     }
186     
187         public static void
188     main( final String JavaDoc[] args )
189         throws Exception JavaDoc
190     {
191         checkAssertsOn();
192         // for friendlier output via Stringifiers
193
new StringifierRegistryIniter( StringifierRegistryImpl.DEFAULT );
194         
195         
196         if ( args.length == 0 ||
197             ( args.length == 1 && isHelp( args[ 0 ] ) ) )
198         {
199             printUsage();
200             System.exit( 255 );
201         }
202         
203         final Map JavaDoc<String JavaDoc,String JavaDoc> cmdLineParams = argsToMap( args );
204         
205         try
206         {
207             new TestMain( args.length == 0 ? null : args[ 0 ], cmdLineParams);
208         }
209         catch( Throwable JavaDoc t )
210         {
211             final Throwable JavaDoc rootCause = ExceptionUtil.getRootCause( t );
212             
213             if ( rootCause instanceof java.net.ConnectException JavaDoc )
214             {
215                 System.err.println( "\nERROR: The connection to the server could not be made" );
216             }
217             else
218             {
219                 System.err.println( "\nERROR: exception of type: " + rootCause.getClass().getName() );
220                 rootCause.printStackTrace();
221             }
222             System.exit( -1 );
223         }
224     }
225
226     private static void println( Object JavaDoc o )
227     {
228         System.out.println( o );
229     }
230     
231         public static String JavaDoc
232     toString( Object JavaDoc o )
233     {
234         return( SmartStringifier.toString( o ) );
235     }
236     
237
238     
239         private final DomainRoot
240     getDomainRoot()
241     {
242         return( mDomainRoot );
243     }
244     
245     
246     
247         private TLSParams
248     createTLSParams(
249         final File JavaDoc trustStoreFile,
250         final String JavaDoc password )
251     {
252         final char[] trustStorePassword = password.toCharArray();
253                     
254         mHandshakeCompletedListener = new HandshakeCompletedListenerImpl();
255         final TestClientTrustStoreTrustManager trustMgr =
256             new TestClientTrustStoreTrustManager( trustStoreFile, trustStorePassword);
257
258         final TLSParams tlsParams = new TLSParams( trustMgr, mHandshakeCompletedListener );
259
260         return( tlsParams );
261     }
262     
263     /**
264         Read connect properties from a file.
265      */

266         private final Map JavaDoc<String JavaDoc,String JavaDoc>
267     getProperties( final String JavaDoc file )
268         throws IOException JavaDoc
269     {
270         Map JavaDoc<String JavaDoc,String JavaDoc> props = PropertyKeys.getDefaults();
271         
272         props.remove( TEST_CLASSES_FILE_KEY );
273         
274         if ( file != null )
275         {
276             println( "Reading properties from: " + StringUtil.quote( file ) );
277             
278             final String JavaDoc propsString = FileUtils.fileToString( new File JavaDoc( file ) );
279             final Properties JavaDoc fromFile = new Properties JavaDoc();
280             fromFile.load( new ByteArrayInputStream JavaDoc( propsString.getBytes() ) );
281             
282             props = MapUtil.toStringStringMap( fromFile );
283         }
284         else
285         {
286             println( "Using default properties." );
287         }
288         
289         return( props );
290     }
291     
292     /**
293         @param host hostname or IP address of Domain Admin Server
294         @param port RMI administrative port
295         @param user admin user
296         @param password admin user password
297         @param tlsParams TLS parameters, may be null
298         @return AppserverConnectionSource
299      */

300         public static AppserverConnectionSource
301     connect(
302         final String JavaDoc host,
303         final int port,
304         final String JavaDoc user,
305         final String JavaDoc password,
306         final TLSParams tlsParams )
307         throws IOException JavaDoc
308     {
309         final String JavaDoc info = "host=" + host + ", port=" + port +
310             ", user=" + user + ", password=" + password +
311             ", tls=" + (tlsParams != null);
312             
313         println( "Connecting: " + info + "...");
314         
315         final AppserverConnectionSource conn =
316             new AppserverConnectionSource( AppserverConnectionSource.PROTOCOL_RMI,
317                 host, port, user, password, tlsParams, null);
318
319         conn.getJMXConnector( false );
320         //println( "Connected: " + info );
321

322         return( conn );
323     }
324     
325     private final class PropertyGetter
326     {
327         final Map JavaDoc<String JavaDoc,Object JavaDoc> mItems;
328         
329         public PropertyGetter( final Map JavaDoc<String JavaDoc,Object JavaDoc> props )
330         {
331             mItems = new HashMap JavaDoc<String JavaDoc,Object JavaDoc>();
332             mItems.putAll( props );
333         }
334         
335             public Object JavaDoc
336         get( final String JavaDoc key )
337         {
338             Object JavaDoc result = System.getProperty( key );
339             if ( result == null )
340             {
341                 result = mItems.get( key );
342             }
343
344             return( result );
345         }
346         
347         public String JavaDoc getString( final String JavaDoc key ) { return( (String JavaDoc)get( key ) ); }
348         public File JavaDoc getFile( final String JavaDoc key )
349         {
350             final String JavaDoc value = getString( key );
351             
352             return( value == null ? null : new File JavaDoc( value ) );
353         }
354         public int getint( final String JavaDoc key ) { return( Integer.parseInt( getString( key ) ) ); }
355         public Integer JavaDoc getInteger( final String JavaDoc key ) { return( new Integer JavaDoc( getString( key ) ) ); }
356         public boolean getboolean( final String JavaDoc key ) { return( Boolean.valueOf( getString( key ) ).booleanValue() ); }
357         public Boolean JavaDoc getBoolean( final String JavaDoc key ) { return( Boolean.valueOf( getString( key ) ) ); }
358     };
359     
360     
361         private AppserverConnectionSource
362     _getConnectionSource(
363         final PropertyGetter getter,
364         final String JavaDoc host,
365         final int port )
366         throws IOException JavaDoc
367     {
368         final String JavaDoc user = getter.getString( USER_KEY );
369         final String JavaDoc password = getter.getString( PASSWORD_KEY );
370         final File JavaDoc trustStore = getter.getFile( TRUSTSTORE_KEY);
371         final String JavaDoc trustStorePassword = getter.getString( TRUSTSTORE_PASSWORD_KEY);
372         final boolean useTLS = getter.getboolean( USE_TLS_KEY );
373         
374         final TLSParams tlsParams = useTLS ?
375             createTLSParams( trustStore, trustStorePassword) : null;
376         
377         AppserverConnectionSource conn = null;
378         
379         try
380         {
381             conn = connect( host, port, user, password, tlsParams );
382             if ( mHandshakeCompletedListener != null )
383             {
384                 assert( mHandshakeCompletedListener.getLastEvent() != null );
385                 println( "HandshakeCompletedEvent: " +
386                     toString( mHandshakeCompletedListener.getLastEvent() ) );
387             }
388         }
389         catch( IOException JavaDoc e )
390         {
391             if ( useTLS )
392             {
393                 // try without TLS
394
println( "Attempting connection without TLS..." );
395                 conn = connect( host, port, user, password, null );
396             }
397         }
398         
399         if ( conn != null )
400         {
401             conn.getJMXConnector( false ).addConnectionNotificationListener( this, null, conn );
402         }
403         
404         return( conn );
405     }
406     
407         private AppserverConnectionSource
408     _getConnectionSource( final PropertyGetter getter )
409         throws IOException JavaDoc
410     {
411         final String JavaDoc host = getter.getString( HOST_KEY );
412         final int port = getter.getint( PORT_KEY );
413         
414         return _getConnectionSource( getter, host, port );
415     }
416     
417         
418         private AppserverConnectionSource
419     getConnectionSource(
420         final PropertyGetter getter,
421         boolean retry )
422         throws Exception JavaDoc
423     {
424         AppserverConnectionSource conn = null;
425         
426         final long PAUSE_MILLIS = 3*1000;
427         
428         for( int i = 0; i < 5; ++i )
429         {
430             try
431             {
432                 conn = _getConnectionSource( getter );
433                 break;
434             }
435             catch( Exception JavaDoc e )
436             {
437                 final Throwable JavaDoc rootCause = ExceptionUtil.getRootCause( e );
438                 
439                 if ( rootCause instanceof java.net.ConnectException JavaDoc )
440                 {
441                     println( "ConnectException: " + rootCause.getMessage() +
442                         "...retry..." );
443                     Thread.sleep( PAUSE_MILLIS );
444                     continue;
445                 }
446                 throw e;
447             }
448         }
449
450         return( conn );
451     }
452     
453     
454     
455         public void
456     handleNotification(
457         final Notification JavaDoc notifIn,
458         final Object JavaDoc handback)
459     {
460         if ( notifIn instanceof JMXConnectionNotification JavaDoc )
461         {
462             final String JavaDoc type = notifIn.getType();
463             if ( type.equals( JMXConnectionNotification.FAILED ) )
464             {
465                 System.err.println( "\n\n### JMXConnection FAILED: " + handback + "\n\n" );
466             }
467             else if ( type.equals( JMXConnectionNotification.CLOSED ) )
468             {
469                 System.err.println( "\n\n### JMXConnection CLOSED: " + handback + "\n\n" );
470             }
471             else if ( type.equals( JMXConnectionNotification.OPENED ) )
472             {
473                 System.err.println( "\n\n### JMXConnection OPENED: " + handback + "\n\n" );
474             }
475             else if ( type.equals( JMXConnectionNotification.NOTIFS_LOST ) )
476             {
477                 System.err.println( "\n\n### JMXConnection NOTIFS_LOST: " + handback + "\n\n" + notifIn );
478                 Observer.getInstance().notifsLost();
479             }
480         }
481     }
482
483         private void
484     printItems(
485         final String JavaDoc[] items,
486         final String JavaDoc prefix )
487     {
488         for( int i = 0; i < items.length; ++i )
489         {
490             println( prefix + items[ i ] );
491         }
492     }
493     
494         private String JavaDoc[]
495     classesToStrings( final Set JavaDoc<Class JavaDoc<junit.framework.TestCase>> classes )
496     {
497         final String JavaDoc[] names = new String JavaDoc[ classes.size() ];
498         
499         int i = 0;
500         for ( final Class JavaDoc<?> c : classes )
501         {
502             names[ i ] = c.getName();
503             ++i;
504         }
505         return names;
506     }
507     
508         private void
509     warnUntestedClasses( final List JavaDoc<Class JavaDoc<junit.framework.TestCase>> actual )
510     {
511         final Set JavaDoc<Class JavaDoc<junit.framework.TestCase>> actualSet = GSetUtil.newSet( actual );
512         final Set JavaDoc<Class JavaDoc<junit.framework.TestCase>> allSet = GSetUtil.newSet( Tests.getTestClasses() );
513         
514         final Set JavaDoc<Class JavaDoc<junit.framework.TestCase>> untested = GSetUtil.newSet( allSet );
515         untested.removeAll( actualSet );
516         if ( untested.size() != 0 )
517         {
518             println( "\nWARNING: the following tests WILL NOT BE RUN:" );
519             final String JavaDoc[] names = classesToStrings( untested );
520             for( int i = 0; i < names.length; ++i )
521             {
522                 names[i] = "!" + names[i] + "!"; // indicate not being run
523
}
524
525             println( ArrayStringifier.stringify( names, "\n" ) );
526             println( "" );
527         }
528         
529         final Set JavaDoc<Class JavaDoc<junit.framework.TestCase>> extras = GSetUtil.newSet( actualSet );
530         extras.removeAll( actualSet );
531         if ( extras.size() != 0 )
532         {
533             println( "\nNOTE: the following non-default tests WILL BE RUN:" );
534             final String JavaDoc[] names = classesToStrings( extras );
535             
536             println( ArrayStringifier.stringify( names, "\n" ) );
537             println( "" );
538         }
539     }
540     
541         private void
542     warnDisabledTests()
543     {
544         final String JavaDoc WARNING =
545 "----------------------------------------\n" +
546 "- -\n" +
547 "- NOTE: -\n" +
548 "- Generic tests currently disabled for -\n" +
549 "- AMX MBeans which reside in non-DAS -\n" +
550 "- server instances eg Logging, CallFlow.-\n" +
551 "- Denoted by 'remoteIncomplete' -\n" +
552 "- -\n" +
553 "- -\n" +
554 "----------------------------------------";
555
556         println( WARNING );
557     }
558         private List JavaDoc<Class JavaDoc<junit.framework.TestCase>>
559     getTestClasses( final File JavaDoc testsFile )
560         throws FileNotFoundException JavaDoc, IOException JavaDoc
561     {
562         List JavaDoc<Class JavaDoc<junit.framework.TestCase>> testClasses = null;
563
564         if ( testsFile == null )
565         {
566             testClasses = Tests.getTestClasses();
567             println( "NO TEST FILE SPECIFIED--TESTING ALL CLASSES in " + Tests.class.getName());
568         }
569         else
570         {
571             println( "Reading test classes from: " + StringUtil.quote( testsFile.toString() ));
572             
573             final String JavaDoc fileString = FileUtils.fileToString( testsFile );
574             final String JavaDoc temp = fileString.replaceAll( "\r\n", "\n" ).replaceAll( "\r", "\n" );
575             final String JavaDoc[] classnames = temp.split( "\n" );
576             
577             testClasses = new ArrayList JavaDoc<Class JavaDoc<junit.framework.TestCase>>();
578             
579             for( int i = 0; i < classnames.length; ++i )
580             {
581                 final String JavaDoc classname = classnames[ i ].trim();
582                         
583                 if ( classname.length() != 0 && ! classname.startsWith( "#" ) )
584                 {
585                     try
586                     {
587                         final Class JavaDoc<junit.framework.TestCase> theClass =
588                             TypeCast.asClass( ClassUtil.getClassFromName( classname ) );
589                         
590                         testClasses.add( theClass );
591                     }
592                     catch( Throwable JavaDoc t )
593                     {
594                         final String JavaDoc msg = "Can't load test class: " + classname;
595                         
596                         throw new Error JavaDoc( msg );
597                     }
598                 }
599             }
600             
601             warnUntestedClasses( testClasses );
602             warnDisabledTests();
603         }
604         
605         return( testClasses );
606     }
607
608
609         private void
610     warnUnknownProperties( final Map JavaDoc<String JavaDoc,String JavaDoc> props )
611     {
612         final Map JavaDoc<String JavaDoc,String JavaDoc> known = new HashMap JavaDoc<String JavaDoc,String JavaDoc>( getDefaults() );
613         final Map JavaDoc<String JavaDoc,String JavaDoc> unknown = new HashMap JavaDoc<String JavaDoc,String JavaDoc>( props );
614         
615         unknown.keySet().removeAll( known.keySet() );
616         if ( unknown.keySet().size() != 0 )
617         {
618             println( "\nNOTE: the following properties are not recognized but " +
619             "will be included in the environment for use by unit tests:");
620             println( MapUtil.toString( unknown, "\n" ) );
621             println( "" );
622         }
623     }
624     
625     private static final String JavaDoc RMI_PROTOCOL_IN_CONFIG = "rmi_jrmp";
626     
627         public Map JavaDoc<String JavaDoc,AppserverConnectionSource>
628     getNodeAgentConnections(
629         final DomainRoot domainRoot,
630         final PropertyGetter getter )
631     {
632         final Map JavaDoc<String JavaDoc,NodeAgentConfig> nodeAgentConfigs =
633             domainRoot.getDomainConfig().getNodeAgentConfigMap();
634         
635         final Map JavaDoc<String JavaDoc,AppserverConnectionSource> nodeAgentConnections =
636             new HashMap JavaDoc<String JavaDoc,AppserverConnectionSource>();
637         
638         println( "" );
639         println( "Contacting node agents..." );
640         
641         for( final NodeAgentConfig nodeAgentConfig : nodeAgentConfigs.values() )
642         {
643             final String JavaDoc nodeAgentName = nodeAgentConfig.getName();
644             
645             final JMXConnectorConfig connConfig = nodeAgentConfig.getJMXConnectorConfig();
646             
647             if ( ! connConfig.getEnabled() )
648             {
649                 println( nodeAgentName + ": DISABLED CONNECTOR");
650                 continue;
651             }
652             
653             final String JavaDoc address = connConfig.getAddress();
654             final int port = Integer.parseInt( connConfig.getPort() );
655             final boolean tlsEnabled = connConfig.getSecurityEnabled();
656             final String JavaDoc protocol = connConfig.getProtocol();
657             
658             if ( ! RMI_PROTOCOL_IN_CONFIG.equals( protocol ) )
659             {
660                 println( nodeAgentName + ": UNSUPPORTED CONNECTOR PROTOCOL: " + protocol );
661                 continue;
662             }
663             
664             // See if we can connect
665
try
666             {
667                 final AppserverConnectionSource asConn =
668                     _getConnectionSource( getter, address, port );
669                 final MBeanServerConnection JavaDoc conn = asConn.getMBeanServerConnection( false );
670                 final boolean alive =
671                     conn.isRegistered( JMXUtil.getMBeanServerDelegateObjectName() );
672                 assert( alive );
673                 
674                 nodeAgentConnections.put( nodeAgentName, asConn );
675                 println( nodeAgentName + ": ALIVE" );
676             }
677             catch( Exception JavaDoc e )
678             {
679                 println( "Node agent " + nodeAgentConfig.getName() +
680                     " could not be contacted: " + e.getClass().getName() );
681                 println( nodeAgentName + ": COULD NOT BE CONTACTED" );
682                 continue;
683             }
684         }
685         
686         println( "" );
687         
688         return nodeAgentConnections;
689     }
690     
691         private Capabilities
692     getCapabilities( final Class JavaDoc c )
693     {
694         Capabilities capabilities = AMXTestBase.getDefaultCapabilities();
695         
696         try
697         {
698             final Method JavaDoc getCapabilities = c.getDeclaredMethod( "getCapabilities", (Class JavaDoc[])null );
699             
700             capabilities = (Capabilities)getCapabilities.invoke( null, (Object JavaDoc[])null );
701         }
702         catch( Exception JavaDoc e )
703         {
704         }
705         
706         return capabilities;
707     }
708     
709         private List JavaDoc<Class JavaDoc<junit.framework.TestCase>>
710     filterTestClasses(
711         final DomainRoot domainRoot,
712         final PropertyGetter getter,
713         final List JavaDoc<Class JavaDoc<junit.framework.TestCase>> classes )
714     {
715         final boolean offline = getter.getboolean( TEST_OFFLINE_KEY );
716         
717         final SystemInfo systemInfo = domainRoot == null ? null : domainRoot.getSystemInfo();
718         
719         final boolean clustersSupported = systemInfo == null ?
720             false : systemInfo.supportsFeature( SystemInfo.CLUSTERS_FEATURE );
721             
722         final boolean multipleServersSupported = systemInfo == null ?
723             false : systemInfo.supportsFeature( SystemInfo.MULTIPLE_SERVERS_FEATURE );
724             
725         final boolean monitorsSupported = ! offline;
726         
727         final List JavaDoc<Class JavaDoc<junit.framework.TestCase>> included = new ArrayList JavaDoc<Class JavaDoc<junit.framework.TestCase>>();
728         final List JavaDoc<Class JavaDoc<junit.framework.TestCase>> omitted = new ArrayList JavaDoc<Class JavaDoc<junit.framework.TestCase>>();
729         for( final Class JavaDoc<junit.framework.TestCase> c : classes )
730         {
731             boolean include = true;
732             
733             final Capabilities capabilities = getCapabilities( c );
734             
735             if ( (! monitorsSupported ) &&
736                 AMXMonitorTestBase.class.isAssignableFrom( c ) )
737             {
738                 include = false;
739             }
740             else if ( offline && ! capabilities.getOfflineCapable() )
741             {
742                 include = false;
743             }
744             else if ( ClusterSupportRequired.class.isAssignableFrom( c ) &&
745                 ! clustersSupported )
746             {
747                 include = false;
748             }
749             else if ( MultipleServerSupportRequired.class.isAssignableFrom( c ) &&
750                 ! multipleServersSupported )
751             {
752                 include = false;
753             }
754             
755             if ( include )
756             {
757                 included.add( c );
758             }
759             else
760             {
761                 omitted.add( c );
762             }
763         }
764         
765         return included;
766     }
767     
768         
769     /**
770      */

771         public
772     TestMain(
773         final String JavaDoc optionalPropertiesFile,
774         final Map JavaDoc<String JavaDoc,String JavaDoc> cmdLineParams )
775         throws Exception JavaDoc
776     {
777         AMXDebug.getInstance().setAll( true );
778         
779         checkAssertsOn();
780         
781         final Map JavaDoc<String JavaDoc,String JavaDoc> props = getProperties( optionalPropertiesFile );
782         
783         final Map JavaDoc<String JavaDoc,String JavaDoc> envIn = new HashMap JavaDoc<String JavaDoc,String JavaDoc>( props );
784         envIn.putAll( cmdLineParams );
785         warnUnknownProperties( envIn );
786         
787         final Map JavaDoc<String JavaDoc,Object JavaDoc> env = new HashMap JavaDoc<String JavaDoc,Object JavaDoc>();
788         env.putAll( envIn );
789         
790         println( "" );
791         println( "ENVIRONMENT:\n" + MapUtil.toString( env, "\n" ) );
792         println( "" );
793         
794         final PropertyGetter getter = new PropertyGetter( env );
795         
796         ConnectionSource conn = null;
797             
798         final boolean testOffline = getter.getboolean( TEST_OFFLINE_KEY );
799         if ( testOffline )
800         {
801             final String JavaDoc domainXML = getter.getString( DOMAIN_XML_KEY );
802             mDomainRoot = initOffline( new File JavaDoc( domainXML ) );
803             
804             final MBeanServer JavaDoc server = (MBeanServer JavaDoc)
805                 Util.getExtra( mDomainRoot ).getConnectionSource().getExistingMBeanServerConnection();
806         
807             final Set JavaDoc<ObjectName JavaDoc> mbeans =
808                 JMXUtil.queryNames( server, Util.newObjectName( "*:*" ), null );
809             //println( "\n\n------------------------------------------" );
810
//println( "MBeans registered:" );
811
//println( CollectionUtil.toString( mbeans, "\n" ) );
812
//println( "\n\n" );
813

814             conn = new MBeanServerConnectionSource( server );
815         }
816         else
817         {
818             if ( getter.getboolean( CONNECT_KEY ) )
819             {
820                 final AppserverConnectionSource acs = getConnectionSource( getter, true );
821             
822                 if ( acs == null )
823                 {
824                     throw new IOException JavaDoc( "Can't connect to server" );
825                 }
826
827                 mDomainRoot = acs.getDomainRoot();
828                 
829                 conn = acs;
830             }
831             else
832             {
833                 mDomainRoot = null;
834                 conn = null;
835             }
836         }
837         
838         if ( mDomainRoot != null )
839         {
840             Observer.create( mDomainRoot );
841         }
842         
843         final boolean expandedTesting = testOffline ?
844             false :getter.getboolean( EXPANDED_TESTING_KEY );
845         
846         if ( mDomainRoot != null && expandedTesting )
847         {
848             final Map JavaDoc<String JavaDoc,AppserverConnectionSource> connections =
849                 getNodeAgentConnections( mDomainRoot, getter );
850             
851             env.put( NODE_AGENTS_KEY, connections );
852         }
853         
854         
855         final boolean threaded = getter.getboolean( RUN_THREADED_KEY );
856         
857         if ( getter.getboolean( VERBOSE_KEY ) )
858         {
859             println( "VERBOSE mode enabled" );
860             if ( threaded )
861             {
862                 println( "NOTE: timings displayed when running " +
863                     "threaded tests will be impacted by other concurrent tests." );
864             }
865         }
866         
867         final List JavaDoc<Class JavaDoc<junit.framework.TestCase>> specifiedClasses =
868             getTestClasses( getter.getFile( TEST_CLASSES_FILE_KEY ) );
869         
870         final List JavaDoc<Class JavaDoc<junit.framework.TestCase>> testClasses =
871             filterTestClasses( mDomainRoot, getter, specifiedClasses );
872         
873         final int iterations = getter.getInteger( ITERATIONS_KEY ).intValue();
874         iterateTests(
875             testClasses,
876             iterations,
877             conn,
878             threaded,
879             Collections.unmodifiableMap( env ) );
880         
881         
882         println( "" );
883         println( "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" );
884         println( ">>>> Please inspect amxtest.coverage <<<<" );
885         println( " ^ " );
886         println( " ^ " );
887         println( " ^ " );
888         println( " ^ " );
889     }
890     
891         private void
892     iterateTests(
893         final List JavaDoc<Class JavaDoc<junit.framework.TestCase>> testClasses,
894         final int iterations,
895         final ConnectionSource conn,
896         final boolean threaded,
897         final Map JavaDoc<String JavaDoc,Object JavaDoc> env )
898         throws Exception JavaDoc
899     {
900         for( int i = 0; i < iterations; ++i )
901         {
902             if ( iterations != 1 )
903             {
904                 println( "#########################################################" );
905                 println( "\n### ITERATION " + (i+1) );
906                 println( "#########################################################" );
907             }
908
909             final long start = System.currentTimeMillis();
910         
911             final TestRunner runner = new TestRunner( conn );
912             runner.runAll( testClasses, threaded, env );
913             
914             final long elapsed = System.currentTimeMillis() - start;
915             println( "Time to run tests: " + (elapsed/1000) + " seconds" );
916         }
917     }
918 }
919
920
921
922
923
924
925
926
927
928
Popular Tags