KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > beehive > netui > tools > testrecorder > shared > xmlbeans > XMLHelper


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.shared.xmlbeans;
20
21 import org.apache.beehive.netui.tools.testrecorder.x2004.*;
22 import org.apache.beehive.netui.tools.testrecorder.x2004.TestsType;
23 import org.apache.beehive.netui.tools.testrecorder.x2004.TestType;
24 import org.apache.beehive.netui.tools.testrecorder.x2004.server.ServerDefinitionDocument;
25 import org.apache.beehive.netui.tools.testrecorder.x2004.server.WebappDefType;
26 import org.apache.beehive.netui.tools.testrecorder.x2004.diffsession.RecorderDiffDocument;
27 import org.apache.beehive.netui.tools.testrecorder.x2004.diffsession.TestDiffType;
28 import org.apache.beehive.netui.tools.testrecorder.x2004.session.*;
29
30 import java.util.List JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Set JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.io.File JavaDoc;
35 import java.io.IOException JavaDoc;
36 import java.io.InputStream JavaDoc;
37 import java.io.FileInputStream JavaDoc;
38 import java.text.ParseException JavaDoc;
39
40 import org.apache.beehive.netui.tools.testrecorder.shared.util.StringHelper;
41 import org.apache.beehive.netui.tools.testrecorder.shared.config.*;
42 import org.apache.beehive.netui.tools.testrecorder.shared.*;
43
44 import org.apache.xmlbeans.XmlException;
45 import org.apache.xmlbeans.XmlOptions;
46 import org.apache.xmlbeans.XmlObject;
47
48 import javax.servlet.http.Cookie JavaDoc;
49
50 /**
51  */

52 public class XMLHelper {
53
54     private static final Logger log = Logger.getInstance( XMLHelper.class );
55
56     public static ServerDefinition getServerDefinition( File JavaDoc file ) throws ConfigException, IOException JavaDoc {
57         if ( log.isInfoEnabled() ) {
58             log.info( "file( " + file.getAbsolutePath() + " )" );
59         }
60         InputStream JavaDoc is = new FileInputStream JavaDoc( file );
61         return getServerDefinition( is, file.getAbsolutePath() );
62     }
63
64     public static ServerDefinition getServerDefinition( InputStream JavaDoc is, String JavaDoc resourceIdentifier )
65             throws ConfigException, IOException JavaDoc {
66         ServerDefinitionDocument doc = null;
67
68         StringBuffer JavaDoc inputStr = new StringBuffer JavaDoc();
69         try {
70             // First read the response into a buffer; that way, we can print it on error.
71
int c;
72             while ( ( c = is.read() ) != -1 )
73             {
74                 inputStr.append( ( char ) c );
75             }
76             
77             XmlOptions loadOptions = new XmlOptions();
78             loadOptions.setLoadLineNumbers();
79             doc = ServerDefinitionDocument.Factory.parse( inputStr.toString(), loadOptions );
80         }
81         catch ( XmlException e ) {
82             log.fatal( "test recorder parse exception while parsing this document: " + inputStr.toString(), e );
83             ConfigException ex = new ConfigException( "ERROR: failed parsing test recorder server definition XML, file( " +
84                     resourceIdentifier + " )", e );
85             log.fatal( ex );
86             throw ex;
87         }
88         finally {
89             if ( is != null ) {
90                 try {
91                     is.close();
92                 }
93                 catch ( IOException JavaDoc e ) {
94                     log.error( "ERROR: failed to close stream for file( " + resourceIdentifier + " )" );
95                 }
96             }
97         }
98
99         assert doc != null;
100         try {
101             validate( doc, resourceIdentifier,
102                     "ERROR: test recorder server definition XML document is not valid against the schema" );
103         }
104         catch ( ConfigException e ) {
105             log.fatal( "test recorder failed validating server definition file( " + resourceIdentifier + " )", e );
106             throw e;
107         }
108         ServerDefinition server = new ServerDefinition( doc.getServerDefinition().getName(),
109                 doc.getServerDefinition().getHostname(), doc.getServerDefinition().getPort() );
110         populateServerDefinition( server, doc );
111         return server;
112     }
113
114     public static void populateServerDefinition( final ServerDefinition server, final ServerDefinitionDocument doc ) {
115         int cnt = doc.getServerDefinition().getWebapps().sizeOfWebappArray();
116         WebappDefType webappType = null;
117         WebappDefinition webapp = null;
118         for ( int i = 0; i < cnt; i++ ) {
119             webappType = doc.getServerDefinition().getWebapps().getWebappArray( i );
120             webapp = new WebappDefinition( webappType.getName(), webappType.getDescription(),
121                     webappType.getContextRoot(), webappType.getServletURI() );
122             server.addWebapp( webapp );
123         }
124         return;
125     }
126
127     public static RecordSessionBean getRecordSessionBean( File JavaDoc file ) throws SessionXMLException, IOException JavaDoc {
128         if ( log.isInfoEnabled() ) {
129             log.info( "file( " + file.getAbsolutePath() + " )" );
130         }
131         InputStream JavaDoc is = new FileInputStream JavaDoc( file );
132         return getRecordSessionBean( is, file.getAbsolutePath() );
133     }
134
135     public static RecordSessionBean getRecordSessionBean( InputStream JavaDoc is, String JavaDoc resourceIdentifier )
136             throws SessionXMLException, IOException JavaDoc {
137         RecorderSessionDocument doc = null;
138         try {
139             XmlOptions loadOptions = new XmlOptions();
140             loadOptions.setLoadLineNumbers();
141             doc = RecorderSessionDocument.Factory.parse( is, loadOptions );
142         }
143         catch ( XmlException e ) {
144             log.fatal( "test recorder parse exception", e );
145             SessionXMLException ex = new SessionXMLException( "ERROR: failed parsing test recorder record session XML, file( " +
146                     resourceIdentifier + " )", e );
147             log.fatal( ex );
148             throw ex;
149         }
150         finally {
151             if ( is != null ) {
152                 try {
153                     is.close();
154                 }
155                 catch ( IOException JavaDoc e ) {
156                     log.error( "ERROR: failed to close stream for file( " + resourceIdentifier + " )" );
157                 }
158             }
159         }
160
161         assert doc != null;
162         try {
163             validate( doc, resourceIdentifier,
164                     "ERROR: test recorder record session XML document is not valid against the schema" );
165         }
166         catch ( ConfigException e ) {
167             throw new SessionXMLException( e.getMessage(), e );
168         }
169         RecorderSessionDocument.RecorderSession xmlSession = doc.getRecorderSession();
170         RecordSessionBean bean = new RecordSessionBean( xmlSession.getSessionName() );
171         bean = getRecordSessionBean( bean, doc );
172         return bean;
173     }
174
175     public static PlaybackSessionBean getPlaybackSessionBean( File JavaDoc file ) throws SessionXMLException, IOException JavaDoc {
176         if ( log.isInfoEnabled() ) {
177             log.info( "file( " + file.getAbsolutePath() + " )" );
178         }
179         InputStream JavaDoc is = new FileInputStream JavaDoc( file );
180         return getPlaybackSessionBean( is, file.getAbsolutePath() );
181     }
182
183     public static PlaybackSessionBean getPlaybackSessionBean( InputStream JavaDoc is, String JavaDoc resourceIdentifier )
184             throws SessionXMLException, IOException JavaDoc {
185         RecorderSessionDocument doc = null;
186         try {
187             XmlOptions loadOptions = new XmlOptions();
188             loadOptions.setLoadLineNumbers();
189             doc = RecorderSessionDocument.Factory.parse( is, loadOptions );
190         }
191         catch ( XmlException e ) {
192             log.fatal( "test recorder parse exception", e );
193             SessionXMLException ex = new SessionXMLException( "ERROR: failed parsing test recorder playback session XML, file( " +
194                     resourceIdentifier + " )", e );
195             log.fatal( ex );
196             throw ex;
197         }
198         finally {
199             if ( is != null ) {
200                 try {
201                     is.close();
202                 }
203                 catch ( IOException JavaDoc e ) {
204                     log.error( "ERROR: failed to close stream for file( " + resourceIdentifier + " )" );
205                 }
206             }
207         }
208
209         assert doc != null;
210         try {
211             validate( doc, resourceIdentifier,
212                     "ERROR: test recorder playback session XML document is not valid against the schema" );
213         }
214         catch ( ConfigException e ) {
215             throw new SessionXMLException( e.getMessage(), e );
216         }
217         PlaybackSessionBean bean = getPlaybackSessionBean( doc );
218         return bean;
219     }
220
221     public static List JavaDoc getDiffResults( File JavaDoc file ) throws SessionXMLException, IOException JavaDoc {
222         if ( log.isInfoEnabled() ) {
223             log.info( "file( " + file.getAbsolutePath() + " )" );
224         }
225         InputStream JavaDoc is = new FileInputStream JavaDoc( file );
226         return getDiffResults( is, file.getAbsolutePath() );
227     }
228
229     public static List JavaDoc getDiffResults( InputStream JavaDoc is, String JavaDoc resourceIdentifier )
230             throws SessionXMLException, IOException JavaDoc {
231         RecorderDiffDocument doc = null;
232         try {
233             XmlOptions loadOptions = new XmlOptions();
234             loadOptions.setLoadLineNumbers();
235             doc = RecorderDiffDocument.Factory.parse( is, loadOptions );
236         }
237         catch ( XmlException e ) {
238             log.fatal( "test recorder parse exception", e );
239             SessionXMLException ex = new SessionXMLException( "ERROR: failed parsing test recorder diff XML, file( " +
240                     resourceIdentifier + " )", e );
241             log.fatal( ex );
242             throw ex;
243         }
244         finally {
245             if ( is != null ) {
246                 try {
247                     is.close();
248                 }
249                 catch ( IOException JavaDoc e ) {
250                     log.error( "ERROR: failed to close stream for file( " + resourceIdentifier + " )" );
251                 }
252             }
253         }
254
255         assert doc != null;
256         try {
257             validate( doc, resourceIdentifier,
258                     "ERROR: test recorder diff XML document is not valid against the schema" );
259         }
260         catch ( ConfigException e ) {
261             throw new SessionXMLException( e.getMessage(), e );
262         }
263         List JavaDoc list = getDiffResults( doc );
264         return list;
265     }
266
267     public static void createRecordFile( File JavaDoc recordFile, RecordSessionBean bean ) throws IOException JavaDoc {
268         XmlOptions xmlOptions = new XmlOptions();
269         xmlOptions.setSavePrettyPrint();
270         xmlOptions.setSavePrettyPrintIndent( 3 );
271         RecorderSessionDocument doc = createRecorderSessionDocument( bean, xmlOptions );
272         doc.save( recordFile, xmlOptions );
273     }
274
275     public static void createPlaybackFile( File JavaDoc playbackFile, PlaybackSessionBean bean ) throws IOException JavaDoc {
276         XmlOptions xmlOptions = new XmlOptions();
277         xmlOptions.setSavePrettyPrint();
278         xmlOptions.setSavePrettyPrintIndent( 3 );
279         RecorderSessionDocument doc = createPlaybackSessionDocument( bean, xmlOptions );
280         doc.save( playbackFile, xmlOptions );
281     }
282
283     public static void createDiffFile( File JavaDoc diffFile, PlaybackSessionBean bean ) throws IOException JavaDoc {
284         XmlOptions xmlOptions = new XmlOptions();
285         xmlOptions.setSavePrettyPrint();
286         xmlOptions.setSavePrettyPrintIndent( 3 );
287         RecorderDiffDocument doc = createDiffSessionDocument( bean, xmlOptions );
288         doc.save( diffFile, xmlOptions );
289     }
290
291     private static RecorderDiffDocument createDiffSessionDocument( PlaybackSessionBean bean, XmlOptions options ) {
292         RecorderDiffDocument doc = RecorderDiffDocument.Factory.newInstance( options );
293         RecorderDiffDocument.RecorderDiff diff = doc.addNewRecorderDiff();
294         TestResults results = null;
295         RequestData request = null;
296         for ( int i = 0; i < bean.getTestCount(); i++ ) {
297             results = bean.getTestResults( i );
298             if ( results.isTestPassed() ) {
299                 continue;
300             }
301             // failure, persist diff data
302
request = bean.getRequestData( i );
303             populateTestDiffType( diff.addNewRequest(), results, request );
304         }
305         return doc;
306     }
307
308     private static RecorderSessionDocument createPlaybackSessionDocument( PlaybackSessionBean bean,
309             XmlOptions options ) {
310         RecorderSessionDocument doc = createRecorderSessionDocument( (RecordSessionBean) bean, options );
311         RecorderSessionDocument.RecorderSession session = doc.getRecorderSession();
312         addTestResults( doc, bean );
313         session.setSessionStatus( StatusType.Enum.forString( bean.getStatus().toLowerCase() ) );
314         session.setPassedCount( bean.getPassedCount() );
315         session.setFailedCount( bean.getFailedCount() );
316         session.setTestCount( bean.getTestCount() );
317         return doc;
318     }
319
320     private static RecorderSessionDocument createRecorderSessionDocument( RecordSessionBean bean,
321             XmlOptions options ) {
322         RecorderSessionDocument doc = createRecorderSessionDocument( (SessionBean) bean, options );
323         RecorderSessionDocument.RecorderSession session = doc.getRecorderSession();
324         session.setTestCount( bean.getTestCount() );
325         // TODO add for record
326
// session.setSessionStatus( );
327
addTests( doc, bean );
328         return doc;
329     }
330
331     private static RecorderSessionDocument createRecorderSessionDocument( SessionBean bean, XmlOptions options ) {
332         RecorderSessionDocument doc = RecorderSessionDocument.Factory.newInstance( options );
333         RecorderSessionDocument.RecorderSession session = doc.addNewRecorderSession();
334         session.setSessionName( bean.getSessionName() );
335         session.setTester( bean.getTester() );
336         session.setDescription( bean.getDescription() );
337         session.setStartDate( bean.getStartDateString() );
338         session.setEndDate( bean.getEndDateString() );
339         return doc;
340     }
341
342     private static void addTests( RecorderSessionDocument doc, RecordSessionBean bean ) {
343         org.apache.beehive.netui.tools.testrecorder.x2004.session.TestsType tests = doc.getRecorderSession()
344                 .addNewTests();
345         org.apache.beehive.netui.tools.testrecorder.x2004.session.TestType test = null;
346         for ( int i = 0; i < bean.getTestCount(); i++ ) {
347             test = tests.addNewTest();
348             test.setTestNumber( i + 1 );
349             populateRequestType( test.addNewRequest(), bean.getRequestData( i ) );
350             populateResponseType( test.addNewResponse(), bean.getResponseData( i ) );
351         }
352         return;
353     }
354
355     private static void addTestResults( RecorderSessionDocument doc, PlaybackSessionBean bean ) {
356         int count = doc.getRecorderSession().getTests().sizeOfTestArray();
357         org.apache.beehive.netui.tools.testrecorder.x2004.session.TestsType tests = doc.getRecorderSession()
358                 .getTests();
359         org.apache.beehive.netui.tools.testrecorder.x2004.session.TestType test = null;
360         for ( int i = 0; i < count; i++ ) {
361             test = tests.getTestArray( i );
362             populateTestResultsType( test.addNewTestResults(), bean.getTestResults( i ) );
363         }
364         return;
365     }
366
367     /**
368      * @param requestType
369      * @param data
370      * @return
371      */

372     private static RequestType populateRequestType( final RequestType requestType, final RequestData data ) {
373         requestType.setProtocol( ProtocolType.Enum.forString( data.getProtocol() ) );
374         requestType.setProtocolVersion( data.getProtocolVersion() );
375         requestType.setHost( data.getHost() );
376         requestType.setPort( data.getPort() );
377         requestType.setUri( data.getPath() );
378         requestType.setMethod( MethodType.Enum.forString( data.getMethod() ) );
379         populateParametersType( requestType.addNewParameters(), data );
380         populateCookiesType( requestType.addNewCookies(), data );
381         populateHeadersType( requestType.addNewHeaders(), data );
382         return requestType;
383     }
384
385     private static ResponseType populateResponseType( final ResponseType responseType, final ResponseData data ) {
386         responseType.setStatusCode( data.getStatusCode() );
387         responseType.setReason( data.getReason() );
388         responseType.setResponseBody( data.getBody() );
389         return responseType;
390     }
391
392     private static TestResultsType populateTestResultsType( final TestResultsType testResultsType,
393             final TestResults data ) {
394         testResultsType.setTestStatus( StatusType.Enum.forString( data.getStatus().toLowerCase() ) );
395         return testResultsType;
396     }
397
398     private static TestDiffType populateTestDiffType( final TestDiffType diffType,
399             final TestResults results, final RequestData request ) {
400         diffType.setTestNumber( results.getTestNumber() );
401         diffType.setUri( request.getPath() );
402         diffType.setDiffResults( getDiffString( results ) );
403         return diffType;
404     }
405
406     private static String JavaDoc getDiffString( TestResults results ) {
407         List JavaDoc list = results.getDiffResults();
408         StringBuffer JavaDoc sb = new StringBuffer JavaDoc( 64 * list.size() );
409         sb.append( "\n" );
410         for ( int i = 0; i < list.size(); i++ ) {
411             sb.append( (String JavaDoc) list.get( i ) + "\n" );
412         }
413         return sb.toString();
414     }
415
416     private static ParametersType populateParametersType( final ParametersType paramsType, final RequestData data ) {
417         NameValueType param = null;
418         for ( int i = 0; i < data.getParamCount(); i++ ) {
419             param = paramsType.addNewParameter();
420             param.setName( data.getParamName( i ) );
421             param.setValue( data.getParamValue( i ) );
422         }
423         return paramsType;
424     }
425
426     private static CookiesType populateCookiesType( final CookiesType cookies, final RequestData data ) {
427         NameValueType cookie = null;
428         for ( int i = 0; i < data.getCookieCount(); i++ ) {
429             cookie = cookies.addNewCookie();
430             cookie.setName( data.getCookieName( i ) );
431             cookie.setValue( data.getCookieValue( i ) );
432         }
433         return cookies;
434     }
435
436     private static HeadersType populateHeadersType( final HeadersType headersType, final RequestData data ) {
437         NameValueType header = null;
438         for ( int i = 0; i < data.getHeaderCount(); i++ ) {
439             header = headersType.addNewHeader();
440             header.setName( data.getHeaderName( i ) );
441             header.setValue( data.getHeaderValue( i ) );
442         }
443         return headersType;
444     }
445
446     /**
447      * returns a List of TestResults objects.
448      *
449      * @param document
450      * @return
451      * @throws SessionXMLException
452      */

453     private static List JavaDoc getDiffResults( RecorderDiffDocument document ) throws SessionXMLException {
454         RecorderDiffDocument.RecorderDiff diff = document.getRecorderDiff();
455         List JavaDoc list = new ArrayList JavaDoc( diff.sizeOfRequestArray() );
456         TestDiffType diffType = null;
457         TestResults results = null;
458         for ( int i = 0; i < diff.sizeOfRequestArray(); i++ ) {
459             diffType = diff.getRequestArray( i );
460             results = new TestResults( diffType.getTestNumber(), diffType.getUri(), false, false );
461             results.addDiffResult( diffType.getDiffResults() );
462             list.add( results );
463         }
464         return list;
465     }
466
467     private static PlaybackSessionBean getPlaybackSessionBean( RecorderSessionDocument document )
468             throws SessionXMLException {
469         RecorderSessionDocument.RecorderSession xmlSession = document.getRecorderSession();
470         boolean error = true;
471         String JavaDoc status = null;
472         status = xmlSession.getSessionStatus().toString();
473         if ( Constants.ERROR.equals( status ) ) {
474             error = true;
475         }
476         PlaybackSessionBean bean = new PlaybackSessionBean( xmlSession.getSessionName(), error );
477         bean = (PlaybackSessionBean) getRecordSessionBean( bean, document );
478         org.apache.beehive.netui.tools.testrecorder.x2004.session.TestsType tests = xmlSession.getTests();
479         org.apache.beehive.netui.tools.testrecorder.x2004.session.TestType testType = null;
480         boolean passed = false;
481         for ( int i = 0; i < tests.sizeOfTestArray(); i++ ) {
482             testType = tests.getTestArray( i );
483             status = testType.getTestResults().getTestStatus().toString();
484             if ( Constants.ERROR.equals( status ) ) {
485                 error = true;
486                 passed = false;
487             }
488             else if ( Constants.PASS.equals( status ) ) {
489                 error = false;
490                 passed = true;
491             }
492             else {
493                 error = false;
494                 passed = false;
495             }
496             bean.addTestResults(
497                     new TestResults( testType.getTestNumber(), testType.getRequest().getUri(), error, passed ) );
498         }
499         // TODO add recorded count to XML populate bean with data.
500
bean.setRecordedTestCount( xmlSession.getTestCount() );
501         return bean;
502     }
503
504     // doc -> object
505
private static RecordSessionBean getRecordSessionBean( RecordSessionBean bean,
506             RecorderSessionDocument document ) throws SessionXMLException {
507         RecorderSessionDocument.RecorderSession xmlSession = document.getRecorderSession();
508         bean.setTester( xmlSession.getTester() );
509         bean.setDescription( xmlSession.getDescription() );
510         try {
511             bean.setStartDate( xmlSession.getStartDate() );
512         }
513         catch ( ParseException JavaDoc e ) {
514             String JavaDoc msg = "ERROR: failed parsing start date( " + xmlSession.getStartDate() + " )";
515             log.error( msg );
516             throw new SessionXMLException( msg, e );
517         }
518         try {
519             bean.setEndDate( xmlSession.getEndDate() );
520         }
521         catch ( ParseException JavaDoc e ) {
522             String JavaDoc msg = "ERROR: failed parsing end date( " + xmlSession.getEndDate() + " )";
523             log.error( msg );
524             throw new SessionXMLException( msg, e );
525         }
526         org.apache.beehive.netui.tools.testrecorder.x2004.session.TestsType tests = xmlSession.getTests();
527         org.apache.beehive.netui.tools.testrecorder.x2004.session.TestType[] testArray = tests.getTestArray();
528         org.apache.beehive.netui.tools.testrecorder.x2004.session.TestType testType = null;
529         RequestType requestType = null;
530         ResponseType responseType = null;
531         RequestData request = null;
532         ResponseData response = null;
533         for ( int i = 0; i < testArray.length; i++ ) {
534             testType = testArray[i];
535             requestType = testType.getRequest();
536             request = getRequestData( requestType );
537             responseType = testType.getResponse();
538             response = getResponseData( responseType, request );
539             bean.addRequestResponseData( request, response );
540         }
541         return bean;
542     }
543
544     private static RequestData getRequestData( RequestType requestType ) {
545         RequestData request = new RequestData();
546         request.setProtocol( requestType.getProtocol().toString() );
547         request.setProtocolVersion( requestType.getProtocolVersion() );
548         request.setHost( requestType.getHost() );
549         request.setPort( requestType.getPort() );
550         request.setPath( requestType.getUri() );
551         request.setMethod( requestType.getMethod().toString() );
552         request.setParameters( getNVPairs( requestType.getParameters().getParameterArray() ) );
553         request.setHeaders( getNVPairs( requestType.getHeaders().getHeaderArray() ) );
554         request.setCookies( getCookies( requestType.getCookies().getCookieArray() ) );
555         return request;
556     }
557
558     private static NVPair[] getNVPairs( NameValueType[] nvArray ) {
559         NVPair[] pairs = new NVPair[nvArray.length];
560         NVPair pair = null;
561         NameValueType nv = null;
562         for ( int i = 0; i < nvArray.length; i++ ) {
563             nv = nvArray[i];
564             pair = new NVPair( nv.getName(), nv.getValue() );
565             pairs[i] = pair;
566         }
567         return pairs;
568     }
569
570     // TODO change to Http client cookies?
571
private static Cookie JavaDoc[] getCookies( NameValueType[] nvArray ) {
572         Cookie JavaDoc[] cookies = new Cookie JavaDoc[nvArray.length];
573         Cookie JavaDoc cookie = null;
574         NameValueType nv = null;
575         for ( int i = 0; i < nvArray.length; i++ ) {
576             nv = nvArray[i];
577             cookie = new Cookie JavaDoc( nv.getName(), nv.getValue() );
578             cookies[i] = cookie;
579         }
580         return cookies;
581     }
582
583     private static ResponseData getResponseData( ResponseType responseType, RequestData request ) {
584         ResponseData response = new ResponseData( request.getHost(), request.getPort() );
585         response.setStatusCode( responseType.getStatusCode() );
586         response.setReason( responseType.getReason() );
587         response.setBody( responseType.getResponseBody() );
588         return response;
589     }
590
591     public static TestDefinitionsDocument createTestDefDocument( Set JavaDoc tests, Set JavaDoc categories ) {
592         TestDefinitionsDocument doc = TestDefinitionsDocument.Factory.newInstance();
593         org.apache.beehive.netui.tools.testrecorder.x2004.TestDefinitionsDocument.TestDefinitions defs =
594                 doc.addNewTestDefinitions();
595         CategoriesType catsType = defs.addNewCategories();
596         Category category = null;
597         CategoryType catType = null;
598         for ( Iterator JavaDoc it = categories.iterator(); it.hasNext(); ) {
599             category = (Category) it.next();
600             catType = catsType.addNewCategory();
601             populateCategory( catType, category );
602         }
603         TestsType testsType = defs.addNewTests();
604         TestDefinition testDef = null;
605         TestType testType = null;
606         for ( Iterator JavaDoc it = tests.iterator(); it.hasNext(); ) {
607             testDef = (TestDefinition) it.next();
608             testType = testsType.addNewTest();
609             populateTest( testType, testDef );
610         }
611         return doc;
612     }
613
614     private static CategoryType populateCategory( CategoryType type, Category category ) {
615         type.setName( category.getName() );
616         type.setDescription( category.getDescription() );
617         return type;
618     }
619
620     private static TestType populateTest( TestType type, TestDefinition def ) {
621         type.setName( def.getName() );
622         type.setDescription( def.getDescription() );
623         type.setWebapp( def.getWebapp().getName() );
624         if ( def.getCategories().size() > 0 ) {
625             TestCategoriesType catType = type.addNewCategories();
626             populateTestCategories( catType, def );
627             type.setCategories( catType );
628         }
629         else {
630             if ( log.isWarnEnabled() ) {
631                 log.warn( "WARNING: no categories for test( " + def.getName() + " ), size( " +
632                         def.getCategories().size() +
633                         " )" );
634             }
635         }
636         return type;
637     }
638
639     private static TestCategoriesType populateTestCategories( TestCategoriesType type, TestDefinition def ) {
640         List JavaDoc categories = def.getCategories();
641         for ( int i = 0; i < categories.size(); i++ ) {
642             Category category = (Category) categories.get( i );
643             type.addCategory( category.getName() );
644         }
645         return type;
646     }
647
648     public static TestDefinitions getTestDefinitionsInstance( ClassLoader JavaDoc loader ) {
649         InputStream JavaDoc is = loader.getResourceAsStream( Constants.CONFIG_FILE );
650         if ( is == null ) {
651             throw new RuntimeConfigException( "ERROR: unable to obtain the resource stream for resource( " +
652                     Constants.CONFIG_FILE + " )" );
653         }
654         Config config = null;
655         try {
656             config = getConfig( is, Constants.CONFIG_FILE );
657         }
658         catch ( ConfigException e ) {
659             throw new RuntimeException JavaDoc( e.getMessage(), e );
660         }
661         catch ( IOException JavaDoc e ) {
662             log.fatal( "ERROR: encountered IOException processing resource( " + Constants.CONFIG_FILE + " )", e );
663             throw new RuntimeConfigException(
664                     "ERROR: encountered IOException processing resource( " + Constants.CONFIG_FILE + " )", e );
665         }
666         finally {
667             try {
668                 is.close();
669             }
670             catch ( IOException JavaDoc e ) {
671             }
672         }
673         if ( log.isInfoEnabled() ) {
674             log.info( "config( " + config + " )" );
675         }
676
677         is = loader.getResourceAsStream( Constants.WEBAPPS_FILE );
678         if ( is == null ) {
679             throw new RuntimeConfigException( "ERROR: unable to obtain the resource stream for resource( " +
680                     Constants.WEBAPPS_FILE + " )" );
681         }
682         Webapps webapps = null;
683         try {
684             webapps = XMLHelper.getWebapps( is, Constants.WEBAPPS_FILE, config );
685         }
686         catch ( ConfigException e ) {
687             throw new RuntimeConfigException( e.getMessage(), e );
688         }
689         catch ( IOException JavaDoc e ) {
690             log.fatal( "ERROR: encountered IOException processing resource( " + Constants.WEBAPPS_FILE + " )", e );
691             throw new RuntimeConfigException( "ERROR: encountered IOException processing resource( " +
692                     Constants.WEBAPPS_FILE + " ), message( " + e.getMessage(), e );
693         }
694         finally {
695             try {
696                 is.close();
697             }
698             catch ( IOException JavaDoc e ) {
699             }
700         }
701         if ( log.isInfoEnabled() ) {
702             log.info( "webapps( " + webapps + " )" );
703         }
704
705         is = loader.getResourceAsStream( Constants.TESTS_FILE );
706         if ( is == null ) {
707             throw new RuntimeConfigException( "ERROR: unable to obtain the resource stream for resource( " +
708                     Constants.TESTS_FILE + " )" );
709         }
710         TestDefinitions testDefinitions = null;
711         try {
712             testDefinitions = XMLHelper.getTestDefinitionsInstance( is, Constants.TESTS_FILE, webapps,
713                     config.getBaseDirectory().getAbsolutePath() );
714         }
715         catch ( ConfigException e ) {
716             throw new RuntimeConfigException( e.getMessage(), e );
717         }
718         catch ( IOException JavaDoc e ) {
719             log.fatal( "ERROR: encountered IOException processing resource( " + Constants.TESTS_FILE + " )", e );
720             throw new RuntimeConfigException( "ERROR: encountered IOException processing resource( " +
721                     Constants.TESTS_FILE + " ), message( " + e.getMessage(), e );
722         }
723         finally {
724             try {
725                 is.close();
726             }
727             catch ( IOException JavaDoc e ) {
728             }
729         }
730         if ( log.isDebugEnabled() ) {
731 // log.debug( "testDefinitions( " + testDefinitions + " )" );
732
}
733         return testDefinitions;
734     }
735
736     public static Config getConfig( File JavaDoc file ) throws ConfigException, IOException JavaDoc {
737         log.info( "file( " + file.getAbsolutePath() + " )" );
738         InputStream JavaDoc is = new FileInputStream JavaDoc( file );
739         return getConfig( is, file.getAbsolutePath() );
740     }
741
742     public static Config getConfig( InputStream JavaDoc is, String JavaDoc resourceIdentifier ) throws ConfigException,
743             IOException JavaDoc {
744         ConfigDocument doc = null;
745         try {
746             XmlOptions loadOptions = new XmlOptions();
747             loadOptions.setLoadLineNumbers();
748             doc = ConfigDocument.Factory.parse( is, loadOptions );
749         }
750         catch ( XmlException e ) {
751             log.fatal( "test recorder parse exception", e );
752             ConfigException ce = new ConfigException( "ERROR: failed parsing test recorder default server configuration XML, file( " +
753                     resourceIdentifier + " )", e );
754             log.fatal( ce );
755             throw ce;
756         }
757         finally {
758             if ( is != null ) {
759                 is.close();
760             }
761         }
762
763         assert doc != null;
764         // may throw ConfigException
765
validate( doc, resourceIdentifier,
766                 "ERROR: test recorder default server config document is not valid against the schema" );
767         Config config = getConfig( doc );
768         return config;
769     }
770
771     public static Webapps getWebapps( File JavaDoc file, Config config ) throws ConfigException, IOException JavaDoc {
772         log.info( "file( " + file.getAbsolutePath() + " )" );
773         InputStream JavaDoc is = new FileInputStream JavaDoc( file );
774         return getWebapps( is, file.getAbsolutePath(), config );
775     }
776
777     public static Webapps getWebapps( InputStream JavaDoc is, String JavaDoc resourceIdentifier, Config config )
778             throws ConfigException, IOException JavaDoc {
779         ServerDocument doc = null;
780         try {
781             XmlOptions loadOptions = new XmlOptions();
782             loadOptions.setLoadLineNumbers();
783             doc = ServerDocument.Factory.parse( is, loadOptions );
784         }
785         catch ( XmlException e ) {
786             log.fatal( "test recorder parse error", e );
787             ConfigException ce = new ConfigException( "ERROR: failed parsing test recorder webapp configuration XML, file( "
788                     + resourceIdentifier + " )", e );
789             log.fatal( ce );
790             throw ce;
791         }
792         finally {
793             if ( is != null ) {
794                 is.close();
795             }
796         }
797
798         assert doc != null;
799         // may throw ConfigException
800
validate( doc, resourceIdentifier,
801                 "ERROR: test recorder webapp config document is not valid against the schema" );
802
803         ServerDocument.Server serverXML = doc.getServer();
804         ServerConfig server = new ServerConfig( serverXML.getName(), serverXML.getHostname(), serverXML.getPort() );
805         List JavaDoc webappList = new ArrayList JavaDoc();
806         webappList = getWebappList( serverXML.getWebapps().getWebappArray(), webappList, server, config );
807         return new Webapps( webappList );
808     }
809
810     public static TestDefinitions getTestDefinitionsInstance( File JavaDoc file, Webapps webapps, String JavaDoc baseDirPath )
811             throws ConfigException, IOException JavaDoc {
812         InputStream JavaDoc is = new FileInputStream JavaDoc( file );
813         return getTestDefinitionsInstance( is, file.getAbsolutePath(), webapps, baseDirPath );
814     }
815
816     public static TestDefinitions getTestDefinitionsInstance( InputStream JavaDoc is, String JavaDoc resourceIdentifier,
817             Webapps webapps, String JavaDoc baseDirPath )
818             throws ConfigException, IOException JavaDoc {
819         TestDefinitionsDocument doc = null;
820         try {
821             XmlOptions loadOptions = new XmlOptions();
822             loadOptions.setLoadLineNumbers();
823             doc = TestDefinitionsDocument.Factory.parse( is, loadOptions );
824         }
825         catch ( XmlException e ) {
826             log.fatal( "test recorder parse exception", e );
827             ConfigException ce = new ConfigException( "ERROR: parsing of test recorder test document failed, file( " +
828                     resourceIdentifier + " )", e );
829             log.fatal( ce );
830             throw ce;
831         }
832         finally {
833             if ( is != null ) {
834                 is.close();
835             }
836         }
837
838         assert doc != null;
839         // may throw ConfigException
840
validate( doc, resourceIdentifier,
841                 "ERROR: test recorder test definitions document is not valid against the schema" );
842         return getTestDefinitionsInstance( doc, webapps, baseDirPath );
843     }
844
845     private static Config getConfig( ConfigDocument document ) {
846         Config config = null;
847         config = new Config( document.getConfig().getSuffixList().getSuffixArray(),
848                 document.getConfig().getServletURI(), document.getConfig().getBaseDirectory() );
849         return config;
850     }
851
852     private static TestDefinitions getTestDefinitionsInstance( TestDefinitionsDocument document, Webapps webapps,
853             String JavaDoc baseDirPath ) throws ConfigException {
854         CategoryType[] categoryTypes = document.getTestDefinitions().getCategories().getCategoryArray();
855         Categories categories = getCategoriesInstance( categoryTypes, baseDirPath );
856         TestType[] testTypes = document.getTestDefinitions().getTests().getTestArray();
857         TestDefinitions tests = getTestDefinitionsInstance( testTypes, categories, webapps );
858         return tests;
859     }
860
861
862     private static List JavaDoc getWebappList( WebappType[] webappTypes, List JavaDoc webappList, ServerConfig server,
863             Config defaultConfig ) {
864         WebappType webappType = null;
865         WebappConfig webapp = null;
866         for ( int i = 0; i < webappTypes.length; i++ ) {
867             webappType = webappTypes[i];
868             webapp = getWebapp( webappType, server, defaultConfig );
869             webappList.add( webapp );
870         }
871         return webappList;
872     }
873
874     private static WebappConfig getWebapp( WebappType webappType, ServerConfig server,
875             Config defaultConfig ) {
876         Config config = getConfig( webappType, defaultConfig );
877         if ( config == null ) {
878             config = defaultConfig;
879         }
880         WebappConfig webapp = new WebappConfig( webappType.getName().trim(),
881                 webappType.getDescription().trim(),
882                 server,
883                 webappType.getTestMode(),
884                 webappType.getContextRoot().trim(),
885                 webappType.getTestDefinitionsDirectory().trim(),
886                 config );
887         return webapp;
888     }
889
890     private static Config getConfig( WebappType webappType, Config defaultConfig ) {
891         // values not specified do not override default config so return null
892
if ( webappType.getOverrideDefaultConfig() == null ) {
893             return null;
894         }
895         Config config = null;
896         String JavaDoc[] suffixes = null;
897         String JavaDoc servletURI = null;
898         if ( webappType.getOverrideDefaultConfig().getSuffixList() != null ) {
899             suffixes = webappType.getOverrideDefaultConfig().getSuffixList().getSuffixArray();
900             servletURI = webappType.getOverrideDefaultConfig().getServletURI();
901         }
902         config = new Config( suffixes, servletURI, defaultConfig.getBaseDirectory().getAbsolutePath() );
903         return config;
904     }
905
906     private static Categories getCategoriesInstance( CategoryType[] categoryTypes, String JavaDoc baseDirPath )
907             throws ConfigException {
908         List JavaDoc list = new ArrayList JavaDoc();
909         Category category = null;
910         CategoryType type = null;
911         for ( int i = 0; i < categoryTypes.length; i++ ) {
912             type = categoryTypes[i];
913             category = new Category( type.getName().trim(), type.getDescription().trim(), baseDirPath );
914             list.add( category );
915         }
916         Categories categories = new Categories( (Category[]) list.toArray( new Category[list.size()] ) );
917         return ( categories );
918     }
919
920     private static TestDefinitions getTestDefinitionsInstance( TestType[] testTypes, Categories categories,
921             Webapps webapps )
922             throws ConfigException {
923         List JavaDoc list = new ArrayList JavaDoc();
924         TestDefinition testDef = null;
925         TestType type = null;
926         String JavaDoc[] testCategoryStrings = null;
927         List JavaDoc testCategories = null;
928         WebappConfig webapp = null;
929         for ( int i = 0; i < testTypes.length; i++ ) {
930             type = testTypes[i];
931             if ( type.getCategories() != null ) {
932                 testCategoryStrings = type.getCategories().getCategoryArray();
933                 testCategories = getCategories( testCategoryStrings, categories );
934             }
935             else {
936                 testCategories = new ArrayList JavaDoc();
937             }
938             webapp = webapps.getWebapp( type.getWebapp() );
939             if ( webapp == null ) {
940                 ConfigException ce = new ConfigException( "ERROR: unable to find test recorder webapp with name( " +
941                         type.getWebapp() +
942                         " ) referenced in test definition( " + type.getName() + " )" );
943                 log.fatal( ce );
944                 throw ce;
945             }
946             testDef =
947                     new TestDefinition( type.getName().trim(), type.getDescription().trim(), webapp,
948                             testCategories );
949             categories.addTest( testDef );
950             list.add( testDef );
951         }
952         TestDefinitions defs = new TestDefinitions( list, categories, webapps );
953         return ( defs );
954     }
955
956     private static List JavaDoc getCategories( String JavaDoc[] names, Categories categories ) throws ConfigException {
957         List JavaDoc list = new ArrayList JavaDoc();
958         String JavaDoc name = null;
959         Category category = null;
960         for ( int i = 0; i < names.length; i++ ) {
961             name = names[i];
962             category = categories.getCategory( name );
963             if ( category == null ) {
964                 ConfigException ce = new ConfigException(
965                         "ERROR: unable to determine test recorder category for name( " + name + " )" );
966                 log.fatal( ce );
967                 throw ce;
968             }
969             list.add( category );
970         }
971         return list;
972     }
973
974     private static void validate( XmlObject doc, String JavaDoc resourceIdentifier, String JavaDoc errorMsg )
975             throws ConfigException {
976         XmlOptions validateOptions = new XmlOptions();
977         validateOptions.setLoadLineNumbers();
978         ArrayList JavaDoc errorList = new ArrayList JavaDoc();
979         validateOptions.setErrorListener( errorList );
980         boolean isValid = doc.validate( validateOptions );
981         if ( !isValid ) {
982             ConfigException ce = new ConfigException( errorMsg + ", resource (" +
983                     resourceIdentifier + " ), errors( " + StringHelper.toString( errorList, "\n", "\n\t" ) + " )" );
984             log.error( ce );
985             throw ce;
986         }
987     }
988
989 }
990
Popular Tags