KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > beehive > netui > tools > testrecorder > client > MasterTestRecorderJUnitTest


1 /*
2  * Copyright 2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * $Header:$
17  */

18
19 package org.apache.beehive.netui.tools.testrecorder.client;
20
21 import junit.framework.TestSuite;
22 import junit.framework.Test;
23 import junit.framework.TestCase;
24 import org.apache.beehive.netui.tools.testrecorder.shared.Logger;
25 import org.apache.beehive.netui.tools.testrecorder.shared.Constants;
26 import org.apache.beehive.netui.tools.testrecorder.shared.xmlbeans.XMLHelper;
27 import org.apache.beehive.netui.tools.testrecorder.shared.config.TestDefinitions;
28 import org.apache.beehive.netui.tools.testrecorder.shared.config.TestDefinition;
29 import org.apache.beehive.netui.tools.testrecorder.shared.config.RuntimeConfigException;
30 import org.apache.beehive.netui.tools.testrecorder.shared.config.WebappConfig;
31 import org.apache.beehive.netui.tools.testrecorder.shared.config.ServerDefinition;
32 import org.apache.beehive.netui.tools.testrecorder.shared.config.WebappDefinition;
33 import org.apache.beehive.netui.tools.testrecorder.shared.config.ConfigException;
34 import org.apache.beehive.netui.tools.testrecorder.shared.config.Config;
35 import org.apache.beehive.netui.tools.testrecorder.shared.config.Webapps;
36 import org.apache.commons.httpclient.NameValuePair;
37 import org.apache.commons.httpclient.HttpMethod;
38 import org.apache.commons.httpclient.HttpClient;
39 import org.apache.commons.httpclient.HttpRecoverableException;
40 import org.apache.commons.httpclient.methods.GetMethod;
41
42 import java.util.List JavaDoc;
43 import java.util.ArrayList JavaDoc;
44 import java.util.StringTokenizer JavaDoc;
45 import java.util.HashMap JavaDoc;
46 import java.util.Map JavaDoc;
47 import java.util.Iterator JavaDoc;
48 import java.io.InputStream JavaDoc;
49 import java.io.IOException JavaDoc;
50
51
52 /**
53  */

54 public class MasterTestRecorderJUnitTest extends TestCase {
55
56     private static final Logger log = Logger.getInstance( MasterTestRecorderJUnitTest.class );
57     // specified when invoking the test to describe the tests to run
58
public static final String JavaDoc TESTS_PROPERTY = "test.recorder.run.tests";
59     public static final String JavaDoc CATEGORIES_PROPERTY = "test.recorder.run.categories";
60     public static final String JavaDoc WEBAPPS_PROPERTY = "test.recorder.run.webapps";
61     public static final String JavaDoc DELETE_RESULTS_PROPERTY = "test.recorder.run.results.delete";
62     private static final NameValuePair configParam = new NameValuePair( Constants.FILE,
63             Constants.FILE_TYPE_CONFIG );
64     private static final NameValuePair webappParam = new NameValuePair( Constants.FILE,
65             Constants.FILE_TYPE_WEBAPP );
66     private static final NameValuePair testsParam = new NameValuePair( Constants.FILE, Constants.FILE_TYPE_TESTS );
67
68     private static ServerDefinition serverDef;
69     private static NameValuePair[] queryParams = new NameValuePair[3];
70
71     static {
72         queryParams[0] = new NameValuePair( Constants.MODE, "xml" );
73         queryParams[1] = new NameValuePair( Constants.CMD, "xml" );
74     }
75
76     private static HttpClient controlClient = new HttpClient();
77
78     public MasterTestRecorderJUnitTest() {
79         super( "MasterTestRecorderJUnitTest" );
80     }
81
82     public static Test suite() {
83         TestSuite suite = null;
84         try {
85             initialize();
86             suite = new TestSuite();
87             buildSuite( suite );
88         }
89         catch ( Throwable JavaDoc e ) {
90             String JavaDoc msg = "Failed building test recorder junit suite, exception( " + e.getMessage() + " )";
91             log.error( msg, e );
92             if ( e instanceof RuntimeException JavaDoc ) {
93                 throw (RuntimeException JavaDoc) e;
94             }
95             throw new RuntimeException JavaDoc( msg, e );
96         }
97         return suite;
98     }
99
100     private static void buildSuite( TestSuite suite ) {
101         boolean delete = getDeleteResultsProperty();
102         HashMap JavaDoc webappMap = new HashMap JavaDoc();
103         TestDefinitions testDefs = null;
104         TestDefinitions[] testDefList = serverDef.getTestDefinitions();
105         boolean includeWebappInName = ( testDefList.length > 1 ) ? true : false;
106         for ( int i = 0; i < testDefList.length; i++ ) {
107             testDefs = (TestDefinitions) testDefList[i];
108             List JavaDoc list = getTestList( getTestsProperty(), testDefs );
109             addList( list, suite, webappMap, includeWebappInName );
110             list = getTestsByCategory( getCategoriesProperty(), testDefs );
111             addList( list, suite, webappMap, includeWebappInName );
112         }
113         if ( log.isInfoEnabled() ) {
114             log.info( "Test recorder test suite consists of (" + suite.countTestCases() + ") tests" );
115         }
116         if ( suite.countTestCases() == 0 ) {
117             String JavaDoc msg = "ERROR: no tests specified, check for warning of skipped webapps, tests and categories";
118             System.err.println( msg );
119             log.fatal( msg );
120             throw new RuntimeConfigException( msg );
121         }
122         // Delete results file for all webapps used, create results directory if it doesn't exist
123
// TODO move to server to allow for playback from remote server
124
Iterator JavaDoc it = webappMap.values().iterator();
125         WebappConfig webapp = null;
126         while ( it.hasNext() ) {
127             webapp = (WebappConfig) it.next();
128             // delete all results only if requested
129
if ( delete ) {
130                 log.info( "Deleting results for webapp( " + webapp.getName() + " )" );
131                 if ( !webapp.deleteResults() ) {
132                     String JavaDoc msg = "WARNING: unable to delete all results files for webapp( " + webapp.getName() +
133                             " )";
134                     System.out.println( msg );
135                     log.warn( msg );
136                 }
137             }
138             if ( !webapp.createResultsDirectory() ) {
139                 String JavaDoc msg = "ERROR: unable to create results directory( " + webapp.getResultsDirectory() +
140                         " ), for webapp( " + webapp.getName() + " )";
141                 System.err.println( msg );
142                 log.error( msg );
143                 throw new RuntimeConfigException( msg );
144             }
145         }
146     }
147
148     private static void addList( List JavaDoc list, TestSuite suite, HashMap JavaDoc webappMap, boolean includeWebappInName ) {
149         TestDefinition def = null;
150         for ( int i = 0; i < list.size(); i++ ) {
151             def = (TestDefinition) list.get( i );
152             log.debug( "Adding test( " + def.getName() + " )to JUnit suite" );
153             if ( includeWebappInName ) {
154                 suite.addTest( new TestRecorderJUnitTest( def, def.getWebapp().getName() + "-" + def.getName() ) );
155             }
156             else {
157                 suite.addTest( new TestRecorderJUnitTest( def ) );
158             }
159             addWebapp( webappMap, def.getWebapp() );
160         }
161     }
162
163     private static void initialize() throws ConfigException, IOException JavaDoc {
164         InputStream JavaDoc is = Thread.currentThread().getContextClassLoader().getResourceAsStream(
165                 Constants.SERVER_FILE );
166         try {
167             serverDef = XMLHelper.getServerDefinition( is, Constants.SERVER_FILE );
168         }
169         catch ( Throwable JavaDoc e ) {
170             String JavaDoc msg = "Failed to obtain test recorder server definition from XML";
171             log.error( msg, e );
172             throw new ConfigException( msg, e );
173         }
174         finally {
175             if ( is != null ) {
176                 try {
177                     is.close();
178                 }
179                 catch ( IOException JavaDoc e ) {
180                     log.error( "Failed closing stream of server definition XML", e );
181                     throw e;
182                 }
183             }
184         }
185         if ( serverDef == null ) {
186             String JavaDoc msg = "Failed to obtain test recorder server definition from XML";
187             log.error( msg );
188             throw new ConfigException( msg );
189         }
190         // the schema insures that at least one webapp is defined
191
assert serverDef.getWebappCount() != 0 : "no webapps defined in server definition XML file" ;
192         String JavaDoc webappList = getWebappsProperty();
193         if ( webappList == null ) {
194             String JavaDoc msg = "ERROR: the '" + WEBAPPS_PROPERTY + "' property must be set.";
195             log.error( msg );
196             throw new ConfigException( msg );
197         }
198         webappList = webappList.trim();
199         WebappDefinition webapp = null;
200         TestDefinitions tests = null;
201         if ( webappList.equalsIgnoreCase( "all" ) ) {
202             WebappDefinition[] webappDefList = serverDef.getWebapps();
203             for ( int i = 0; i < webappDefList.length; i++ ) {
204                 webapp = webappDefList[i];
205                 tests = getTestDefinitions( webapp );
206                 if ( tests == null ) {
207                     continue;
208                 }
209                 serverDef.addTestDefinitions( webapp, tests );
210             }
211         }
212         else {
213             String JavaDoc webappName = null;
214             for ( StringTokenizer JavaDoc stringTokenizer = new StringTokenizer JavaDoc( webappList, "," );
215                     stringTokenizer.hasMoreTokens(); ) {
216                 webappName = stringTokenizer.nextToken().trim();
217                 if ( webappName.length() == 0 ) {
218                     continue;
219                 }
220                 webapp = serverDef.getWebapp( webappName );
221                 if ( webapp == null ) {
222                     String JavaDoc msg = "WARNING: no webapp found with name( " + webappName + " )";
223                     if ( log.isErrorEnabled() ) {
224                         log.error( msg );
225                     }
226                     System.err.println( msg );
227                     continue;
228                 }
229                 if ( log.isDebugEnabled() ) {
230                     log.debug( "retrieving test definition for webapp at( " + webapp.getContextRoot() + " )" );
231                 }
232                 tests = getTestDefinitions( webapp );
233                 if ( tests == null ) {
234                     continue;
235                 }
236                 serverDef.addTestDefinitions( webapp, tests );
237             }
238         }
239         if ( serverDef.getTestDefinitionsCount() == 0 ) {
240             String JavaDoc msg = "ERROR: no test definitions found";
241             log.error( msg );
242             throw new ConfigException( msg );
243         }
244     }
245
246     private static TestDefinitions getTestDefinitions( WebappDefinition webapp ) {
247         TestDefinitions tests = null;
248         try {
249             tests = retrieveTestDefinitions( serverDef, webapp );
250         }
251         catch ( ConfigException e ) {
252             String JavaDoc msg = "WARNING: failed to obtain test definitions for webapp at( " +
253                     webapp.getContextRoot() + " )";
254             if ( log.isErrorEnabled() ) {
255                 log.warn( msg, e );
256             }
257             e.printStackTrace();
258             System.err.println( msg );
259         }
260         return tests;
261     }
262
263     private static TestDefinitions retrieveTestDefinitions( ServerDefinition server, WebappDefinition webapp )
264             throws ConfigException {
265         String JavaDoc uri = genUri( "http", server.getHostname(), server.getPort(), webapp.getServletUri() );
266         HttpMethod method = new GetMethod( uri );
267         queryParams[2] = configParam;
268         method.setQueryString( queryParams );
269         InputStream JavaDoc is = executeXMLRequest( method, uri, Constants.CONFIG_FILE );
270         Config config = null;
271         try {
272             config = XMLHelper.getConfig( is, Constants.CONFIG_FILE );
273         }
274         catch ( Exception JavaDoc e ) {
275             String JavaDoc msg = "ERROR: encountered exception processing resource( " + Constants.CONFIG_FILE + " )";
276             log.fatal( msg, e );
277             if ( e instanceof ConfigException ) {
278                 throw (ConfigException) e;
279             }
280             throw new ConfigException( msg, e );
281         }
282         finally {
283             try {
284                 if ( is != null ) {
285                     is.close();
286                 }
287             }
288             catch ( IOException JavaDoc e ) {
289                 if ( log.isWarnEnabled() ) {
290                     log.warn( "WARNING: received exception closing HTTP stream for( " + Constants.CONFIG_FILE +
291                             " )", e );
292                 }
293                 //ignore
294
}
295             method.releaseConnection();
296         }
297         if ( log.isInfoEnabled() ) {
298             log.info( "config( " + config + " )" );
299         }
300
301         method = new GetMethod( uri );
302         queryParams[2] = webappParam;
303         method.setQueryString( queryParams );
304         is = executeXMLRequest( method, uri, Constants.WEBAPPS_FILE );
305         Webapps webapps = null;
306         try {
307             webapps = XMLHelper.getWebapps( is, Constants.WEBAPPS_FILE, config );
308         }
309         catch ( Exception JavaDoc e ) {
310             String JavaDoc msg = "ERROR: encountered exception processing resource( " + Constants.WEBAPPS_FILE + " )";
311             log.fatal( msg, e );
312             if ( e instanceof ConfigException ) {
313                 throw (ConfigException) e;
314             }
315             throw new ConfigException( msg, e );
316         }
317         finally {
318             try {
319                 if ( is != null ) {
320                     is.close();
321                 }
322             }
323             catch ( IOException JavaDoc e ) {
324                 if ( log.isWarnEnabled() ) {
325                     log.warn( "WARNING: received exception closing HTTP stream for( " + Constants.WEBAPPS_FILE +
326                             " )", e );
327                 }
328                 // ignore
329
}
330             method.releaseConnection();
331         }
332         if ( log.isInfoEnabled() ) {
333             log.info( "webapps( " + webapps + " )" );
334         }
335
336         method = new GetMethod( uri );
337         queryParams[2] = testsParam;
338         method.setQueryString( queryParams );
339         is = executeXMLRequest( method, uri, Constants.TESTS_FILE );
340         TestDefinitions testDefinitions = null;
341         try {
342             testDefinitions = XMLHelper.getTestDefinitionsInstance( is, Constants.TESTS_FILE, webapps,
343                     config.getBaseDirectory().getAbsolutePath() );
344         }
345         catch ( Exception JavaDoc e ) {
346             String JavaDoc msg = "ERROR: encountered exception processing resource( " + Constants.TESTS_FILE + " )";
347             log.fatal( msg, e );
348             if ( e instanceof ConfigException ) {
349                 throw (ConfigException) e;
350             }
351             throw new ConfigException( msg, e );
352         }
353         finally {
354             try {
355                 if ( is != null ) {
356                     is.close();
357                 }
358             }
359             catch ( IOException JavaDoc e ) {
360                 if ( log.isWarnEnabled() ) {
361                     log.warn( "WARNING: received exception closing HTTP stream for( " + Constants.TESTS_FILE +
362                             " )", e );
363                 }
364                 // ignore
365
}
366             method.releaseConnection();
367         }
368         if ( log.isDebugEnabled() ) {
369 // log.debug( "testDefinitions( " + testDefinitions + " )" );
370
}
371         return testDefinitions;
372     }
373
374     private static InputStream JavaDoc executeXMLRequest( HttpMethod method, String JavaDoc uri, String JavaDoc resourceIdentifier )
375             throws ConfigException {
376         InputStream JavaDoc is = null;
377         try {
378             is = executeHttpRequest( controlClient, method );
379         }
380         catch ( Exception JavaDoc e ) {
381             String JavaDoc msg = "Failed to obtain '" + resourceIdentifier + "' from webapp at uri( " + uri + " )";
382             log.error( msg, e );
383             if ( is != null ) {
384                 try {
385                     is.close();
386                 }
387                 catch ( IOException JavaDoc e1 ) {
388                     // ignore
389
}
390             }
391             method.releaseConnection();
392             throw new ConfigException( msg, e );
393         }
394         return is;
395     }
396
397     private static InputStream JavaDoc executeHttpRequest( HttpClient client, HttpMethod method ) throws ConfigException,
398             IOException JavaDoc {
399         int statusCode = -1;
400         // retry up to 3 times.
401
for ( int attempt = 0; statusCode == -1 && attempt < 3; attempt++ ) {
402             try {
403                 statusCode = client.executeMethod( method );
404             }
405             catch ( HttpRecoverableException e ) {
406                 if ( log.isWarnEnabled() ) {
407                     String JavaDoc msg = "A recoverable exception occurred calling URI( " + method.getURI() +
408                             " ), retrying. exception( " + e.getMessage() + " )";
409                     log.error( msg, e );
410                 }
411             }
412             catch ( IOException JavaDoc e ) {
413                 String JavaDoc msg = "Failed executing request( " + method.getURI() + " ), exception( " + e.getMessage() +
414                         " )";
415                 log.error( msg, e );
416                 throw e;
417             }
418         }
419         // Retries failed
420
if ( statusCode == -1 ) {
421             String JavaDoc msg = "Failed to execute request( " + method.getURI() + " )";
422             log.error( msg );
423             throw new ConfigException( msg );
424         }
425         InputStream JavaDoc is = method.getResponseBodyAsStream();
426         return is;
427     }
428
429     public static String JavaDoc genUri( String JavaDoc protocol, String JavaDoc host, int port, String JavaDoc path ) {
430         return protocol + "://" + host + ":" + port + path;
431     }
432
433     /**
434      * Returns a List of TestDefinition objects
435      */

436     private static List JavaDoc getTestList( String JavaDoc testList, TestDefinitions testDefs ) {
437         List JavaDoc list = new ArrayList JavaDoc();
438         if ( testList == null ) {
439             return list;
440         }
441         String JavaDoc name = null;
442         TestDefinition test = null;
443         for ( StringTokenizer JavaDoc stringTokenizer = new StringTokenizer JavaDoc( testList, "," );
444                 stringTokenizer.hasMoreTokens(); ) {
445             name = stringTokenizer.nextToken().trim();
446             if ( name.length() == 0 ) {
447                 continue;
448             }
449             test = testDefs.getTest( name );
450             if ( test == null ) {
451                 String JavaDoc msg = "WARNING: unable to find test with name( " + name +" ) in webapp( " +
452                 testDefs.getWebapps().toString() + " ), skippping";
453                 if ( log.isWarnEnabled() ) {
454                     log.warn( msg );
455                 }
456                 System.err.println( msg );
457                 continue;
458             }
459             list.add( test );
460         }
461         return list;
462     }
463
464     private static List JavaDoc getTestsByCategory( String JavaDoc categoryList, TestDefinitions testDefs ) {
465         String JavaDoc category = null;
466         List JavaDoc list = new ArrayList JavaDoc();
467         if ( categoryList == null ) {
468             return list;
469         }
470         List JavaDoc temp = null;
471         for ( StringTokenizer JavaDoc stringTokenizer = new StringTokenizer JavaDoc( categoryList, "," );
472                 stringTokenizer.hasMoreTokens(); ) {
473             category = stringTokenizer.nextToken().trim();
474             if ( category.length() == 0 ) {
475                 continue;
476             }
477             // implicit category
478
if ( category.equalsIgnoreCase( "all" ) ) {
479                 temp = testDefs.getTestDefinitions();
480             }
481             else {
482                 temp = testDefs.getCategories().getTests( category );
483             }
484             if ( temp == null ) {
485                 String JavaDoc msg = "WARNING: unable to find category( " + category + " ) in webapp( " +
486                 testDefs.getWebapps().toString() + " ), skippping";
487                 if ( log.isWarnEnabled() ) {
488                     log.warn( msg );
489                 }
490                 System.err.println( msg );
491                 continue;
492             }
493             list.addAll( temp );
494         }
495         return list;
496     }
497
498     private static boolean getDeleteResultsProperty() {
499         return Boolean.valueOf( getProperty( DELETE_RESULTS_PROPERTY ) ).booleanValue();
500     }
501
502     private static String JavaDoc getTestsProperty() {
503         return getProperty( TESTS_PROPERTY );
504     }
505
506     private static String JavaDoc getCategoriesProperty() {
507         return getProperty( CATEGORIES_PROPERTY );
508     }
509
510     private static String JavaDoc getWebappsProperty() {
511         return getProperty( WEBAPPS_PROPERTY );
512     }
513
514
515     private static String JavaDoc getProperty( String JavaDoc prop ) {
516         String JavaDoc value = null;
517         try {
518             value = System.getProperty( prop );
519         }
520         catch ( Exception JavaDoc ex ) {
521             log.fatal( "unable to obtain system property( " + prop + " ), ex( " + ex.getMessage() + " )", ex );
522             throw new RuntimeException JavaDoc( "unable to obtain system property( " + prop + " ), exception( " +
523                     ex.toString() + " )" );
524         }
525         assert value != null : "system property( " + prop + " ) has value( " + value + " )";
526         return value;
527     }
528
529     private static void addWebapp( Map JavaDoc map, WebappConfig webapp ) {
530         if ( !map.containsKey( webapp.getName() ) ) {
531             map.put( webapp.getName(), webapp );
532         }
533     }
534 }
535
Popular Tags