Package org.apache.beehive.netui.tools.testrecorder.shared.xmlbeans

Source Code of org.apache.beehive.netui.tools.testrecorder.shared.xmlbeans.XMLHelper

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

package org.apache.beehive.netui.tools.testrecorder.shared.xmlbeans;

import org.apache.beehive.netui.tools.testrecorder.x2004.*;
import org.apache.beehive.netui.tools.testrecorder.x2004.TestsType;
import org.apache.beehive.netui.tools.testrecorder.x2004.TestType;
import org.apache.beehive.netui.tools.testrecorder.x2004.server.ServerDefinitionDocument;
import org.apache.beehive.netui.tools.testrecorder.x2004.server.WebappDefType;
import org.apache.beehive.netui.tools.testrecorder.x2004.diffsession.RecorderDiffDocument;
import org.apache.beehive.netui.tools.testrecorder.x2004.diffsession.TestDiffType;
import org.apache.beehive.netui.tools.testrecorder.x2004.session.*;

import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.Iterator;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import java.text.ParseException;

import org.apache.beehive.netui.tools.testrecorder.shared.util.StringHelper;
import org.apache.beehive.netui.tools.testrecorder.shared.config.*;
import org.apache.beehive.netui.tools.testrecorder.shared.*;

import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.XmlObject;

import javax.servlet.http.Cookie;

/**
*/
public class XMLHelper {

    private static final Logger log = Logger.getInstance( XMLHelper.class );

    public static ServerDefinition getServerDefinition( File file ) throws ConfigException, IOException {
        if ( log.isInfoEnabled() ) {
            log.info( "file( " + file.getAbsolutePath() + " )" );
        }
        InputStream is = new FileInputStream( file );
        return getServerDefinition( is, file.getAbsolutePath() );
    }

    public static ServerDefinition getServerDefinition( InputStream is, String resourceIdentifier )
            throws ConfigException, IOException {
        ServerDefinitionDocument doc = null;

        StringBuffer inputStr = new StringBuffer();
        try {
            // First read the response into a buffer; that way, we can print it on error.
            int c;
            while ( ( c = is.read() ) != -1 )
            {
                inputStr.append( ( char ) c );
            }
           
            XmlOptions loadOptions = new XmlOptions();
            loadOptions.setLoadLineNumbers();
            doc = ServerDefinitionDocument.Factory.parse( inputStr.toString(), loadOptions );
        }
        catch ( XmlException e ) {
            log.fatal( "test recorder parse exception while parsing this document: " + inputStr.toString(), e );
            ConfigException ex = new ConfigException( "ERROR: failed parsing test recorder server definition XML, file( " +
                    resourceIdentifier + " )", e );
            log.fatal( ex );
            throw ex;
        }
        finally {
            if ( is != null ) {
                try {
                    is.close();
                }
                catch ( IOException e ) {
                    log.error( "ERROR: failed to close stream for file( " + resourceIdentifier + " )" );
                }
            }
        }

        assert doc != null;
        try {
            validate( doc, resourceIdentifier,
                    "ERROR: test recorder server definition XML document is not valid against the schema" );
        }
        catch ( ConfigException e ) {
            log.fatal( "test recorder failed validating server definition file( " + resourceIdentifier + " )", e );
            throw e;
        }
        ServerDefinition server = new ServerDefinition( doc.getServerDefinition().getName(),
                doc.getServerDefinition().getHostname(), doc.getServerDefinition().getPort() );
        populateServerDefinition( server, doc );
        return server;
    }

    public static void populateServerDefinition( final ServerDefinition server, final ServerDefinitionDocument doc ) {
        int cnt = doc.getServerDefinition().getWebapps().sizeOfWebappArray();
        WebappDefType webappType = null;
        WebappDefinition webapp = null;
        for ( int i = 0; i < cnt; i++ ) {
            webappType = doc.getServerDefinition().getWebapps().getWebappArray( i );
            webapp = new WebappDefinition( webappType.getName(), webappType.getDescription(),
                    webappType.getContextRoot(), webappType.getServletURI() );
            server.addWebapp( webapp );
        }
        return;
    }

    public static RecordSessionBean getRecordSessionBean( File file ) throws SessionXMLException, IOException {
        if ( log.isInfoEnabled() ) {
            log.info( "file( " + file.getAbsolutePath() + " )" );
        }
        InputStream is = new FileInputStream( file );
        return getRecordSessionBean( is, file.getAbsolutePath() );
    }

    public static RecordSessionBean getRecordSessionBean( InputStream is, String resourceIdentifier )
            throws SessionXMLException, IOException {
        RecorderSessionDocument doc = null;
        try {
            XmlOptions loadOptions = new XmlOptions();
            loadOptions.setLoadLineNumbers();
            doc = RecorderSessionDocument.Factory.parse( is, loadOptions );
        }
        catch ( XmlException e ) {
            log.fatal( "test recorder parse exception", e );
            SessionXMLException ex = new SessionXMLException( "ERROR: failed parsing test recorder record session XML, file( " +
                    resourceIdentifier + " )", e );
            log.fatal( ex );
            throw ex;
        }
        finally {
            if ( is != null ) {
                try {
                    is.close();
                }
                catch ( IOException e ) {
                    log.error( "ERROR: failed to close stream for file( " + resourceIdentifier + " )" );
                }
            }
        }

        assert doc != null;
        try {
            validate( doc, resourceIdentifier,
                    "ERROR: test recorder record session XML document is not valid against the schema" );
        }
        catch ( ConfigException e ) {
            throw new SessionXMLException( e.getMessage(), e );
        }
        RecorderSessionDocument.RecorderSession xmlSession = doc.getRecorderSession();
        RecordSessionBean bean = new RecordSessionBean( xmlSession.getSessionName() );
        bean = getRecordSessionBean( bean, doc );
        return bean;
    }

    public static PlaybackSessionBean getPlaybackSessionBean( File file ) throws SessionXMLException, IOException {
        if ( log.isInfoEnabled() ) {
            log.info( "file( " + file.getAbsolutePath() + " )" );
        }
        InputStream is = new FileInputStream( file );
        return getPlaybackSessionBean( is, file.getAbsolutePath() );
    }

    public static PlaybackSessionBean getPlaybackSessionBean( InputStream is, String resourceIdentifier )
            throws SessionXMLException, IOException {
        RecorderSessionDocument doc = null;
        try {
            XmlOptions loadOptions = new XmlOptions();
            loadOptions.setLoadLineNumbers();
            doc = RecorderSessionDocument.Factory.parse( is, loadOptions );
        }
        catch ( XmlException e ) {
            log.fatal( "test recorder parse exception", e );
            SessionXMLException ex = new SessionXMLException( "ERROR: failed parsing test recorder playback session XML, file( " +
                    resourceIdentifier + " )", e );
            log.fatal( ex );
            throw ex;
        }
        finally {
            if ( is != null ) {
                try {
                    is.close();
                }
                catch ( IOException e ) {
                    log.error( "ERROR: failed to close stream for file( " + resourceIdentifier + " )" );
                }
            }
        }

        assert doc != null;
        try {
            validate( doc, resourceIdentifier,
                    "ERROR: test recorder playback session XML document is not valid against the schema" );
        }
        catch ( ConfigException e ) {
            throw new SessionXMLException( e.getMessage(), e );
        }
        PlaybackSessionBean bean = getPlaybackSessionBean( doc );
        return bean;
    }

    public static List getDiffResults( File file ) throws SessionXMLException, IOException {
        if ( log.isInfoEnabled() ) {
            log.info( "file( " + file.getAbsolutePath() + " )" );
        }
        InputStream is = new FileInputStream( file );
        return getDiffResults( is, file.getAbsolutePath() );
    }

    public static List getDiffResults( InputStream is, String resourceIdentifier )
            throws SessionXMLException, IOException {
        RecorderDiffDocument doc = null;
        try {
            XmlOptions loadOptions = new XmlOptions();
            loadOptions.setLoadLineNumbers();
            doc = RecorderDiffDocument.Factory.parse( is, loadOptions );
        }
        catch ( XmlException e ) {
            log.fatal( "test recorder parse exception", e );
            SessionXMLException ex = new SessionXMLException( "ERROR: failed parsing test recorder diff XML, file( " +
                    resourceIdentifier + " )", e );
            log.fatal( ex );
            throw ex;
        }
        finally {
            if ( is != null ) {
                try {
                    is.close();
                }
                catch ( IOException e ) {
                    log.error( "ERROR: failed to close stream for file( " + resourceIdentifier + " )" );
                }
            }
        }

        assert doc != null;
        try {
            validate( doc, resourceIdentifier,
                    "ERROR: test recorder diff XML document is not valid against the schema" );
        }
        catch ( ConfigException e ) {
            throw new SessionXMLException( e.getMessage(), e );
        }
        List list = getDiffResults( doc );
        return list;
    }

    public static void createRecordFile( File recordFile, RecordSessionBean bean ) throws IOException {
        XmlOptions xmlOptions = new XmlOptions();
        xmlOptions.setSavePrettyPrint();
        xmlOptions.setSavePrettyPrintIndent( 3 );
        RecorderSessionDocument doc = createRecorderSessionDocument( bean, xmlOptions );
        doc.save( recordFile, xmlOptions );
    }

    public static void createPlaybackFile( File playbackFile, PlaybackSessionBean bean ) throws IOException {
        XmlOptions xmlOptions = new XmlOptions();
        xmlOptions.setSavePrettyPrint();
        xmlOptions.setSavePrettyPrintIndent( 3 );
        RecorderSessionDocument doc = createPlaybackSessionDocument( bean, xmlOptions );
        doc.save( playbackFile, xmlOptions );
    }

    public static void createDiffFile( File diffFile, PlaybackSessionBean bean ) throws IOException {
        XmlOptions xmlOptions = new XmlOptions();
        xmlOptions.setSavePrettyPrint();
        xmlOptions.setSavePrettyPrintIndent( 3 );
        RecorderDiffDocument doc = createDiffSessionDocument( bean, xmlOptions );
        doc.save( diffFile, xmlOptions );
    }

    private static RecorderDiffDocument createDiffSessionDocument( PlaybackSessionBean bean, XmlOptions options ) {
        RecorderDiffDocument doc = RecorderDiffDocument.Factory.newInstance( options );
        RecorderDiffDocument.RecorderDiff diff = doc.addNewRecorderDiff();
        TestResults results = null;
        RequestData request = null;
        for ( int i = 0; i < bean.getTestCount(); i++ ) {
            results = bean.getTestResults( i );
            if ( results.isTestPassed() ) {
                continue;
            }
            // failure, persist diff data
            request = bean.getRequestData( i );
            populateTestDiffType( diff.addNewRequest(), results, request );
        }
        return doc;
    }

    private static RecorderSessionDocument createPlaybackSessionDocument( PlaybackSessionBean bean,
            XmlOptions options ) {
        RecorderSessionDocument doc = createRecorderSessionDocument( (RecordSessionBean) bean, options );
        RecorderSessionDocument.RecorderSession session = doc.getRecorderSession();
        addTestResults( doc, bean );
        session.setSessionStatus( StatusType.Enum.forString( bean.getStatus().toLowerCase() ) );
        session.setPassedCount( bean.getPassedCount() );
        session.setFailedCount( bean.getFailedCount() );
        session.setTestCount( bean.getTestCount() );
        return doc;
    }

    private static RecorderSessionDocument createRecorderSessionDocument( RecordSessionBean bean,
            XmlOptions options ) {
        RecorderSessionDocument doc = createRecorderSessionDocument( (SessionBean) bean, options );
        RecorderSessionDocument.RecorderSession session = doc.getRecorderSession();
        session.setTestCount( bean.getTestCount() );
        // TODO add for record
        //        session.setSessionStatus( );
        addTests( doc, bean );
        return doc;
    }

    private static RecorderSessionDocument createRecorderSessionDocument( SessionBean bean, XmlOptions options ) {
        RecorderSessionDocument doc = RecorderSessionDocument.Factory.newInstance( options );
        RecorderSessionDocument.RecorderSession session = doc.addNewRecorderSession();
        session.setSessionName( bean.getSessionName() );
        session.setTester( bean.getTester() );
        session.setDescription( bean.getDescription() );
        session.setStartDate( bean.getStartDateString() );
        session.setEndDate( bean.getEndDateString() );
        return doc;
    }

    private static void addTests( RecorderSessionDocument doc, RecordSessionBean bean ) {
        org.apache.beehive.netui.tools.testrecorder.x2004.session.TestsType tests = doc.getRecorderSession()
                .addNewTests();
        org.apache.beehive.netui.tools.testrecorder.x2004.session.TestType test = null;
        for ( int i = 0; i < bean.getTestCount(); i++ ) {
            test = tests.addNewTest();
            test.setTestNumber( i + 1 );
            populateRequestType( test.addNewRequest(), bean.getRequestData( i ) );
            populateResponseType( test.addNewResponse(), bean.getResponseData( i ) );
        }
        return;
    }

    private static void addTestResults( RecorderSessionDocument doc, PlaybackSessionBean bean ) {
        int count = doc.getRecorderSession().getTests().sizeOfTestArray();
        org.apache.beehive.netui.tools.testrecorder.x2004.session.TestsType tests = doc.getRecorderSession()
                .getTests();
        org.apache.beehive.netui.tools.testrecorder.x2004.session.TestType test = null;
        for ( int i = 0; i < count; i++ ) {
            test = tests.getTestArray( i );
            populateTestResultsType( test.addNewTestResults(), bean.getTestResults( i ) );
        }
        return;
    }

    /**
     * @param requestType
     * @param data       
     * @return
     */
    private static RequestType populateRequestType( final RequestType requestType, final RequestData data ) {
        requestType.setProtocol( ProtocolType.Enum.forString( data.getProtocol() ) );
        requestType.setProtocolVersion( data.getProtocolVersion() );
        requestType.setHost( data.getHost() );
        requestType.setPort( data.getPort() );
        requestType.setUri( data.getPath() );
        requestType.setMethod( MethodType.Enum.forString( data.getMethod() ) );
        populateParametersType( requestType.addNewParameters(), data );
        populateCookiesType( requestType.addNewCookies(), data );
        populateHeadersType( requestType.addNewHeaders(), data );
        return requestType;
    }

    private static ResponseType populateResponseType( final ResponseType responseType, final ResponseData data ) {
        responseType.setStatusCode( data.getStatusCode() );
        responseType.setReason( data.getReason() );
        responseType.setResponseBody( data.getBody() );
        return responseType;
    }

    private static TestResultsType populateTestResultsType( final TestResultsType testResultsType,
            final TestResults data ) {
        testResultsType.setTestStatus( StatusType.Enum.forString( data.getStatus().toLowerCase() ) );
        return testResultsType;
    }

    private static TestDiffType populateTestDiffType( final TestDiffType diffType,
            final TestResults results, final RequestData request ) {
        diffType.setTestNumber( results.getTestNumber() );
        diffType.setUri( request.getPath() );
        diffType.setDiffResults( getDiffString( results ) );
        return diffType;
    }

    private static String getDiffString( TestResults results ) {
        List list = results.getDiffResults();
        StringBuffer sb = new StringBuffer( 64 * list.size() );
        sb.append( "\n" );
        for ( int i = 0; i < list.size(); i++ ) {
            sb.append( (String) list.get( i ) + "\n" );
        }
        return sb.toString();
    }

    private static ParametersType populateParametersType( final ParametersType paramsType, final RequestData data ) {
        NameValueType param = null;
        for ( int i = 0; i < data.getParamCount(); i++ ) {
            param = paramsType.addNewParameter();
            param.setName( data.getParamName( i ) );
            param.setValue( data.getParamValue( i ) );
        }
        return paramsType;
    }

    private static CookiesType populateCookiesType( final CookiesType cookies, final RequestData data ) {
        NameValueType cookie = null;
        for ( int i = 0; i < data.getCookieCount(); i++ ) {
            cookie = cookies.addNewCookie();
            cookie.setName( data.getCookieName( i ) );
            cookie.setValue( data.getCookieValue( i ) );
        }
        return cookies;
    }

    private static HeadersType populateHeadersType( final HeadersType headersType, final RequestData data ) {
        NameValueType header = null;
        for ( int i = 0; i < data.getHeaderCount(); i++ ) {
            header = headersType.addNewHeader();
            header.setName( data.getHeaderName( i ) );
            header.setValue( data.getHeaderValue( i ) );
        }
        return headersType;
    }

    /**
     * returns a List of TestResults objects.
     *
     * @param document
     * @return
     * @throws SessionXMLException
     */
    private static List getDiffResults( RecorderDiffDocument document ) throws SessionXMLException {
        RecorderDiffDocument.RecorderDiff diff = document.getRecorderDiff();
        List list = new ArrayList( diff.sizeOfRequestArray() );
        TestDiffType diffType = null;
        TestResults results = null;
        for ( int i = 0; i < diff.sizeOfRequestArray(); i++ ) {
            diffType = diff.getRequestArray( i );
            results = new TestResults( diffType.getTestNumber(), diffType.getUri(), false, false );
            results.addDiffResult( diffType.getDiffResults() );
            list.add( results );
        }
        return list;
    }

    private static PlaybackSessionBean getPlaybackSessionBean( RecorderSessionDocument document )
            throws SessionXMLException {
        RecorderSessionDocument.RecorderSession xmlSession = document.getRecorderSession();
        boolean error = true;
        String status = null;
        status = xmlSession.getSessionStatus().toString();
        if ( Constants.ERROR.equals( status ) ) {
            error = true;
        }
        PlaybackSessionBean bean = new PlaybackSessionBean( xmlSession.getSessionName(), error );
        bean = (PlaybackSessionBean) getRecordSessionBean( bean, document );
        org.apache.beehive.netui.tools.testrecorder.x2004.session.TestsType tests = xmlSession.getTests();
        org.apache.beehive.netui.tools.testrecorder.x2004.session.TestType testType = null;
        boolean passed = false;
        for ( int i = 0; i < tests.sizeOfTestArray(); i++ ) {
            testType = tests.getTestArray( i );
            status = testType.getTestResults().getTestStatus().toString();
            if ( Constants.ERROR.equals( status ) ) {
                error = true;
                passed = false;
            }
            else if ( Constants.PASS.equals( status ) ) {
                error = false;
                passed = true;
            }
            else {
                error = false;
                passed = false;
            }
            bean.addTestResults(
                    new TestResults( testType.getTestNumber(), testType.getRequest().getUri(), error, passed ) );
        }
        // TODO add recorded count to XML populate bean with data.
        bean.setRecordedTestCount( xmlSession.getTestCount() );
        return bean;
    }

    // doc -> object
    private static RecordSessionBean getRecordSessionBean( RecordSessionBean bean,
            RecorderSessionDocument document ) throws SessionXMLException {
        RecorderSessionDocument.RecorderSession xmlSession = document.getRecorderSession();
        bean.setTester( xmlSession.getTester() );
        bean.setDescription( xmlSession.getDescription() );
        try {
            bean.setStartDate( xmlSession.getStartDate() );
        }
        catch ( ParseException e ) {
            String msg = "ERROR: failed parsing start date( " + xmlSession.getStartDate() + " )";
            log.error( msg );
            throw new SessionXMLException( msg, e );
        }
        try {
            bean.setEndDate( xmlSession.getEndDate() );
        }
        catch ( ParseException e ) {
            String msg = "ERROR: failed parsing end date( " + xmlSession.getEndDate() + " )";
            log.error( msg );
            throw new SessionXMLException( msg, e );
        }
        org.apache.beehive.netui.tools.testrecorder.x2004.session.TestsType tests = xmlSession.getTests();
        org.apache.beehive.netui.tools.testrecorder.x2004.session.TestType[] testArray = tests.getTestArray();
        org.apache.beehive.netui.tools.testrecorder.x2004.session.TestType testType = null;
        RequestType requestType = null;
        ResponseType responseType = null;
        RequestData request = null;
        ResponseData response = null;
        for ( int i = 0; i < testArray.length; i++ ) {
            testType = testArray[i];
            requestType = testType.getRequest();
            request = getRequestData( requestType );
            responseType = testType.getResponse();
            response = getResponseData( responseType, request );
            bean.addRequestResponseData( request, response );
        }
        return bean;
    }

    private static RequestData getRequestData( RequestType requestType ) {
        RequestData request = new RequestData();
        request.setProtocol( requestType.getProtocol().toString() );
        request.setProtocolVersion( requestType.getProtocolVersion() );
        request.setHost( requestType.getHost() );
        request.setPort( requestType.getPort() );
        request.setPath( requestType.getUri() );
        request.setMethod( requestType.getMethod().toString() );
        request.setParameters( getNVPairs( requestType.getParameters().getParameterArray() ) );
        request.setHeaders( getNVPairs( requestType.getHeaders().getHeaderArray() ) );
        request.setCookies( getCookies( requestType.getCookies().getCookieArray() ) );
        return request;
    }

    private static NVPair[] getNVPairs( NameValueType[] nvArray ) {
        NVPair[] pairs = new NVPair[nvArray.length];
        NVPair pair = null;
        NameValueType nv = null;
        for ( int i = 0; i < nvArray.length; i++ ) {
            nv = nvArray[i];
            pair = new NVPair( nv.getName(), nv.getValue() );
            pairs[i] = pair;
        }
        return pairs;
    }

    // TODO change to Http client cookies?
    private static Cookie[] getCookies( NameValueType[] nvArray ) {
        Cookie[] cookies = new Cookie[nvArray.length];
        Cookie cookie = null;
        NameValueType nv = null;
        for ( int i = 0; i < nvArray.length; i++ ) {
            nv = nvArray[i];
            cookie = new Cookie( nv.getName(), nv.getValue() );
            cookies[i] = cookie;
        }
        return cookies;
    }

    private static ResponseData getResponseData( ResponseType responseType, RequestData request ) {
        ResponseData response = new ResponseData( request.getHost(), request.getPort() );
        response.setStatusCode( responseType.getStatusCode() );
        response.setReason( responseType.getReason() );
        response.setBody( responseType.getResponseBody() );
        return response;
    }

    public static TestDefinitionsDocument createTestDefDocument( Set tests, Set categories ) {
        TestDefinitionsDocument doc = TestDefinitionsDocument.Factory.newInstance();
        org.apache.beehive.netui.tools.testrecorder.x2004.TestDefinitionsDocument.TestDefinitions defs =
                doc.addNewTestDefinitions();
        CategoriesType catsType = defs.addNewCategories();
        Category category = null;
        CategoryType catType = null;
        for ( Iterator it = categories.iterator(); it.hasNext(); ) {
            category = (Category) it.next();
            catType = catsType.addNewCategory();
            populateCategory( catType, category );
        }
        TestsType testsType = defs.addNewTests();
        TestDefinition testDef = null;
        TestType testType = null;
        for ( Iterator it = tests.iterator(); it.hasNext(); ) {
            testDef = (TestDefinition) it.next();
            testType = testsType.addNewTest();
            populateTest( testType, testDef );
        }
        return doc;
    }

    private static CategoryType populateCategory( CategoryType type, Category category ) {
        type.setName( category.getName() );
        type.setDescription( category.getDescription() );
        return type;
    }

    private static TestType populateTest( TestType type, TestDefinition def ) {
        type.setName( def.getName() );
        type.setDescription( def.getDescription() );
        type.setWebapp( def.getWebapp().getName() );
        if ( def.getCategories().size() > 0 ) {
            TestCategoriesType catType = type.addNewCategories();
            populateTestCategories( catType, def );
            type.setCategories( catType );
        }
        else {
            if ( log.isWarnEnabled() ) {
                log.warn( "WARNING: no categories for test( " + def.getName() + " ), size( " +
                        def.getCategories().size() +
                        " )" );
            }
        }
        return type;
    }

    private static TestCategoriesType populateTestCategories( TestCategoriesType type, TestDefinition def ) {
        List categories = def.getCategories();
        for ( int i = 0; i < categories.size(); i++ ) {
            Category category = (Category) categories.get( i );
            type.addCategory( category.getName() );
        }
        return type;
    }

    public static TestDefinitions getTestDefinitionsInstance( ClassLoader loader ) {
        InputStream is = loader.getResourceAsStream( Constants.CONFIG_FILE );
        if ( is == null ) {
            throw new RuntimeConfigException( "ERROR: unable to obtain the resource stream for resource( " +
                    Constants.CONFIG_FILE + " )" );
        }
        Config config = null;
        try {
            config = getConfig( is, Constants.CONFIG_FILE );
        }
        catch ( ConfigException e ) {
            throw new RuntimeException( e.getMessage(), e );
        }
        catch ( IOException e ) {
            log.fatal( "ERROR: encountered IOException processing resource( " + Constants.CONFIG_FILE + " )", e );
            throw new RuntimeConfigException(
                    "ERROR: encountered IOException processing resource( " + Constants.CONFIG_FILE + " )", e );
        }
        finally {
            try {
                is.close();
            }
            catch ( IOException e ) {
            }
        }
        if ( log.isInfoEnabled() ) {
            log.info( "config( " + config + " )" );
        }

        is = loader.getResourceAsStream( Constants.WEBAPPS_FILE );
        if ( is == null ) {
            throw new RuntimeConfigException( "ERROR: unable to obtain the resource stream for resource( " +
                    Constants.WEBAPPS_FILE + " )" );
        }
        Webapps webapps = null;
        try {
            webapps = XMLHelper.getWebapps( is, Constants.WEBAPPS_FILE, config );
        }
        catch ( ConfigException e ) {
            throw new RuntimeConfigException( e.getMessage(), e );
        }
        catch ( IOException e ) {
            log.fatal( "ERROR: encountered IOException processing resource( " + Constants.WEBAPPS_FILE + " )", e );
            throw new RuntimeConfigException( "ERROR: encountered IOException processing resource( " +
                    Constants.WEBAPPS_FILE + " ), message( " + e.getMessage(), e );
        }
        finally {
            try {
                is.close();
            }
            catch ( IOException e ) {
            }
        }
        if ( log.isInfoEnabled() ) {
            log.info( "webapps( " + webapps + " )" );
        }

        is = loader.getResourceAsStream( Constants.TESTS_FILE );
        if ( is == null ) {
            throw new RuntimeConfigException( "ERROR: unable to obtain the resource stream for resource( " +
                    Constants.TESTS_FILE + " )" );
        }
        TestDefinitions testDefinitions = null;
        try {
            testDefinitions = XMLHelper.getTestDefinitionsInstance( is, Constants.TESTS_FILE, webapps,
                    config.getBaseDirectory().getAbsolutePath() );
        }
        catch ( ConfigException e ) {
            throw new RuntimeConfigException( e.getMessage(), e );
        }
        catch ( IOException e ) {
            log.fatal( "ERROR: encountered IOException processing resource( " + Constants.TESTS_FILE + " )", e );
            throw new RuntimeConfigException( "ERROR: encountered IOException processing resource( " +
                    Constants.TESTS_FILE + " ), message( " + e.getMessage(), e );
        }
        finally {
            try {
                is.close();
            }
            catch ( IOException e ) {
            }
        }
        if ( log.isDebugEnabled() ) {
//            log.debug( "testDefinitions( " + testDefinitions + " )" );
        }
        return testDefinitions;
    }

    public static Config getConfig( File file ) throws ConfigException, IOException {
        log.info( "file( " + file.getAbsolutePath() + " )" );
        InputStream is = new FileInputStream( file );
        return getConfig( is, file.getAbsolutePath() );
    }

    public static Config getConfig( InputStream is, String resourceIdentifier ) throws ConfigException,
            IOException {
        ConfigDocument doc = null;
        try {
            XmlOptions loadOptions = new XmlOptions();
            loadOptions.setLoadLineNumbers();
            doc = ConfigDocument.Factory.parse( is, loadOptions );
        }
        catch ( XmlException e ) {
            log.fatal( "test recorder parse exception", e );
            ConfigException ce = new ConfigException( "ERROR: failed parsing test recorder default server configuration XML, file( " +
                    resourceIdentifier + " )", e );
            log.fatal( ce );
            throw ce;
        }
        finally {
            if ( is != null ) {
                is.close();
            }
        }

        assert doc != null;
        // may throw ConfigException
        validate( doc, resourceIdentifier,
                "ERROR: test recorder default server config document is not valid against the schema" );
        Config config = getConfig( doc );
        return config;
    }

    public static Webapps getWebapps( File file, Config config ) throws ConfigException, IOException {
        log.info( "file( " + file.getAbsolutePath() + " )" );
        InputStream is = new FileInputStream( file );
        return getWebapps( is, file.getAbsolutePath(), config );
    }

    public static Webapps getWebapps( InputStream is, String resourceIdentifier, Config config )
            throws ConfigException, IOException {
        ServerDocument doc = null;
        try {
            XmlOptions loadOptions = new XmlOptions();
            loadOptions.setLoadLineNumbers();
            doc = ServerDocument.Factory.parse( is, loadOptions );
        }
        catch ( XmlException e ) {
            log.fatal( "test recorder parse error", e );
            ConfigException ce = new ConfigException( "ERROR: failed parsing test recorder webapp configuration XML, file( "
                    + resourceIdentifier + " )", e );
            log.fatal( ce );
            throw ce;
        }
        finally {
            if ( is != null ) {
                is.close();
            }
        }

        assert doc != null;
        // may throw ConfigException
        validate( doc, resourceIdentifier,
                "ERROR: test recorder webapp config document is not valid against the schema" );

        ServerDocument.Server serverXML = doc.getServer();
        ServerConfig server = new ServerConfig( serverXML.getName(), serverXML.getHostname(), serverXML.getPort() );
        List webappList = new ArrayList();
        webappList = getWebappList( serverXML.getWebapps().getWebappArray(), webappList, server, config );
        return new Webapps( webappList );
    }

    public static TestDefinitions getTestDefinitionsInstance( File file, Webapps webapps, String baseDirPath )
            throws ConfigException, IOException {
        InputStream is = new FileInputStream( file );
        return getTestDefinitionsInstance( is, file.getAbsolutePath(), webapps, baseDirPath );
    }

    public static TestDefinitions getTestDefinitionsInstance( InputStream is, String resourceIdentifier,
            Webapps webapps, String baseDirPath )
            throws ConfigException, IOException {
        TestDefinitionsDocument doc = null;
        try {
            XmlOptions loadOptions = new XmlOptions();
            loadOptions.setLoadLineNumbers();
            doc = TestDefinitionsDocument.Factory.parse( is, loadOptions );
        }
        catch ( XmlException e ) {
            log.fatal( "test recorder parse exception", e );
            ConfigException ce = new ConfigException( "ERROR: parsing of test recorder test document failed, file( " +
                    resourceIdentifier + " )", e );
            log.fatal( ce );
            throw ce;
        }
        finally {
            if ( is != null ) {
                is.close();
            }
        }

        assert doc != null;
        // may throw ConfigException
        validate( doc, resourceIdentifier,
                "ERROR: test recorder test definitions document is not valid against the schema" );
        return getTestDefinitionsInstance( doc, webapps, baseDirPath );
    }

    private static Config getConfig( ConfigDocument document ) {
        Config config = null;
        config = new Config( document.getConfig().getSuffixList().getSuffixArray(),
                document.getConfig().getServletURI(), document.getConfig().getBaseDirectory() );
        return config;
    }

    private static TestDefinitions getTestDefinitionsInstance( TestDefinitionsDocument document, Webapps webapps,
            String baseDirPath ) throws ConfigException {
        CategoryType[] categoryTypes = document.getTestDefinitions().getCategories().getCategoryArray();
        Categories categories = getCategoriesInstance( categoryTypes, baseDirPath );
        TestType[] testTypes = document.getTestDefinitions().getTests().getTestArray();
        TestDefinitions tests = getTestDefinitionsInstance( testTypes, categories, webapps );
        return tests;
    }


    private static List getWebappList( WebappType[] webappTypes, List webappList, ServerConfig server,
            Config defaultConfig ) {
        WebappType webappType = null;
        WebappConfig webapp = null;
        for ( int i = 0; i < webappTypes.length; i++ ) {
            webappType = webappTypes[i];
            webapp = getWebapp( webappType, server, defaultConfig );
            webappList.add( webapp );
        }
        return webappList;
    }

    private static WebappConfig getWebapp( WebappType webappType, ServerConfig server,
            Config defaultConfig ) {
        Config config = getConfig( webappType, defaultConfig );
        if ( config == null ) {
            config = defaultConfig;
        }
        WebappConfig webapp = new WebappConfig( webappType.getName().trim(),
                webappType.getDescription().trim(),
                server,
                webappType.getTestMode(),
                webappType.getContextRoot().trim(),
                webappType.getTestDefinitionsDirectory().trim(),
                config );
        return webapp;
    }

    private static Config getConfig( WebappType webappType, Config defaultConfig ) {
        // values not specified do not override default config so return null
        if ( webappType.getOverrideDefaultConfig() == null ) {
            return null;
        }
        Config config = null;
        String[] suffixes = null;
        String servletURI = null;
        if ( webappType.getOverrideDefaultConfig().getSuffixList() != null ) {
            suffixes = webappType.getOverrideDefaultConfig().getSuffixList().getSuffixArray();
            servletURI = webappType.getOverrideDefaultConfig().getServletURI();
        }
        config = new Config( suffixes, servletURI, defaultConfig.getBaseDirectory().getAbsolutePath() );
        return config;
    }

    private static Categories getCategoriesInstance( CategoryType[] categoryTypes, String baseDirPath )
            throws ConfigException {
        List list = new ArrayList();
        Category category = null;
        CategoryType type = null;
        for ( int i = 0; i < categoryTypes.length; i++ ) {
            type = categoryTypes[i];
            category = new Category( type.getName().trim(), type.getDescription().trim(), baseDirPath );
            list.add( category );
        }
        Categories categories = new Categories( (Category[]) list.toArray( new Category[list.size()] ) );
        return ( categories );
    }

    private static TestDefinitions getTestDefinitionsInstance( TestType[] testTypes, Categories categories,
            Webapps webapps )
            throws ConfigException {
        List list = new ArrayList();
        TestDefinition testDef = null;
        TestType type = null;
        String[] testCategoryStrings = null;
        List testCategories = null;
        WebappConfig webapp = null;
        for ( int i = 0; i < testTypes.length; i++ ) {
            type = testTypes[i];
            if ( type.getCategories() != null ) {
                testCategoryStrings = type.getCategories().getCategoryArray();
                testCategories = getCategories( testCategoryStrings, categories );
            }
            else {
                testCategories = new ArrayList();
            }
            webapp = webapps.getWebapp( type.getWebapp() );
            if ( webapp == null ) {
                ConfigException ce = new ConfigException( "ERROR: unable to find test recorder webapp with name( " +
                        type.getWebapp() +
                        " ) referenced in test definition( " + type.getName() + " )" );
                log.fatal( ce );
                throw ce;
            }
            testDef =
                    new TestDefinition( type.getName().trim(), type.getDescription().trim(), webapp,
                            testCategories );
            categories.addTest( testDef );
            list.add( testDef );
        }
        TestDefinitions defs = new TestDefinitions( list, categories, webapps );
        return ( defs );
    }

    private static List getCategories( String[] names, Categories categories ) throws ConfigException {
        List list = new ArrayList();
        String name = null;
        Category category = null;
        for ( int i = 0; i < names.length; i++ ) {
            name = names[i];
            category = categories.getCategory( name );
            if ( category == null ) {
                ConfigException ce = new ConfigException(
                        "ERROR: unable to determine test recorder category for name( " + name + " )" );
                log.fatal( ce );
                throw ce;
            }
            list.add( category );
        }
        return list;
    }

    private static void validate( XmlObject doc, String resourceIdentifier, String errorMsg )
            throws ConfigException {
        XmlOptions validateOptions = new XmlOptions();
        validateOptions.setLoadLineNumbers();
        ArrayList errorList = new ArrayList();
        validateOptions.setErrorListener( errorList );
        boolean isValid = doc.validate( validateOptions );
        if ( !isValid ) {
            ConfigException ce = new ConfigException( errorMsg + ", resource (" +
                    resourceIdentifier + " ), errors( " + StringHelper.toString( errorList, "\n", "\n\t" ) + " )" );
            log.error( ce );
            throw ce;
        }
    }

}
TOP

Related Classes of org.apache.beehive.netui.tools.testrecorder.shared.xmlbeans.XMLHelper

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.