You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@beehive.apache.org by ek...@apache.org on 2005/10/26 19:10:12 UTC
svn commit: r328684 [2/2] - in /beehive/trunk/netui:
src/testRecorder/org/apache/beehive/netui/tools/testrecorder/shared/
src/testRecorder/org/apache/beehive/netui/tools/testrecorder/shared/schemas/
src/testRecorder/org/apache/beehive/netui/tools/testr...
Modified: beehive/trunk/netui/src/testRecorder/org/apache/beehive/netui/tools/testrecorder/shared/xmlbeans/XMLHelper.java
URL: http://svn.apache.org/viewcvs/beehive/trunk/netui/src/testRecorder/org/apache/beehive/netui/tools/testrecorder/shared/xmlbeans/XMLHelper.java?rev=328684&r1=328683&r2=328684&view=diff
==============================================================================
--- beehive/trunk/netui/src/testRecorder/org/apache/beehive/netui/tools/testrecorder/shared/xmlbeans/XMLHelper.java (original)
+++ beehive/trunk/netui/src/testRecorder/org/apache/beehive/netui/tools/testrecorder/shared/xmlbeans/XMLHelper.java Wed Oct 26 10:09:59 2005
@@ -1,4 +1,4 @@
-/*
+ /*
* Copyright 2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -24,6 +24,8 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
+import java.io.Writer;
+import java.io.FileWriter;
import java.text.ParseException;
import javax.servlet.http.Cookie;
import javax.xml.parsers.DocumentBuilderFactory;
@@ -54,8 +56,6 @@
import org.apache.beehive.netui.tools.testrecorder.shared.config.Categories;
import org.apache.beehive.netui.tools.testrecorder.shared.config.Category;
import org.apache.beehive.netui.tools.testrecorder.shared.config.TestDefinition;
-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.RecorderSessionDocument;
import org.apache.beehive.netui.tools.testrecorder.x2004.session.RequestType;
import org.apache.beehive.netui.tools.testrecorder.x2004.session.NameValueType;
@@ -79,711 +79,771 @@
import org.xml.sax.ErrorHandler;
import org.xml.sax.EntityResolver;
-/**
- */
-public final class XMLHelper {
-
- private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
- private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
- private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
- private static final Logger LOGGER = Logger.getInstance(XMLHelper.class);
-
- public static ServerDefinition getServerDefinition(final InputStream xmlInputStream, final String xmlResourcePath) {
-
- Document document = null;
- final String xsdResourcePath = Constants.SCHEMA_LOCATION + "/" + Constants.SERVER_SCHEMA_NAME;
- InputStream xsdInputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
- try {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setValidating(true);
- dbf.setNamespaceAware(true);
- dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
- dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream);
-
- DocumentBuilder db = dbf.newDocumentBuilder();
- db.setErrorHandler(new ErrorHandler() {
- public void warning(SAXParseException exception) {
- if(LOGGER.isInfoEnabled())
- LOGGER.info("Validation warning validating config file \"" + xmlResourcePath +
- "\" against XML Schema \"" + xsdResourcePath);
- }
-
- public void error(SAXParseException exception) {
- throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
- xmlResourcePath + "\". Cause: " + exception, exception);
- }
-
- public void fatalError(SAXParseException exception) {
- throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
- xmlResourcePath + "\". Cause: " + exception, exception);
- }
- });
-
- db.setEntityResolver(new EntityResolver() {
- public InputSource resolveEntity(String publicId, String systemId) {
- if(systemId.endsWith(Constants.SERVER_SCHEMA_NAME)) {
- InputStream inputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
- return new InputSource(inputStream);
- }
- else return null;
- }
- });
-
- document = db.parse(xmlInputStream);
- }
- catch(Exception e) {
- assert e instanceof ParserConfigurationException;
- throw new IllegalStateException("Exception occurred parsing document. Cause: " + e, e);
- }
-
- String name = DomUtils.getChildElementText(document.getDocumentElement(), "name");
- String hostname = DomUtils.getChildElementText(document.getDocumentElement(), "hostname");
- String portString = DomUtils.getChildElementText(document.getDocumentElement(), "port");
- int port = Integer.parseInt(portString);
-
- ServerDefinition server = new ServerDefinition(name, hostname, port);
-
- Element elem = DomUtils.getChildElementByName(document.getDocumentElement(), "webapps");
- NodeList webappList = elem.getElementsByTagName("webapp");
- for(int i = 0; i < webappList.getLength(); i++) {
- Element webappElem = (Element)webappList.item(i);
- WebappDefinition webapp = new WebappDefinition(
- DomUtils.getChildElementText(webappElem, "name"),
- DomUtils.getChildElementText(webappElem, "description"),
- DomUtils.getChildElementText(webappElem, "contextRoot"),
- DomUtils.getChildElementText(webappElem, "servletURI")
- );
- server.addWebapp(webapp);
- }
-
- return server;
- }
-
- public static RecordSessionBean getRecordSessionBean(File file)
- throws SessionXMLException, IOException {
- if (LOGGER.isInfoEnabled())
- LOGGER.info("file( " + file.getAbsolutePath() + " )");
-
- String resourceIdentifier = file.getAbsolutePath();
- InputStream is = new FileInputStream(file);
-
- RecorderSessionDocument doc = null;
- try {
- XmlOptions loadOptions = new XmlOptions();
- loadOptions.setLoadLineNumbers();
- doc = RecorderSessionDocument.Factory.parse(is, loadOptions);
- }
- catch (XmlException e) {
- LOGGER.fatal("test recorder parse exception", e);
- SessionXMLException ex = new SessionXMLException("ERROR: failed parsing test recorder record session XML, file( " +
- resourceIdentifier + " )", e);
- LOGGER.fatal(ex);
- throw ex;
- }
- finally {
- if (is != null) {
- try {
- is.close();
- }
- catch (IOException e) {
- LOGGER.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.setTester(xmlSession.getTester());
- bean.setDescription(xmlSession.getDescription());
- try {
- bean.setStartDate(xmlSession.getStartDate());
- }
- catch (ParseException e) {
- String msg = "ERROR: failed parsing start date( " + xmlSession.getStartDate() + " )";
- LOGGER.error(msg);
- throw new SessionXMLException(msg, e);
- }
- try {
- bean.setEndDate(xmlSession.getEndDate());
- }
- catch (ParseException e) {
- String msg = "ERROR: failed parsing end date( " + xmlSession.getEndDate() + " )";
- LOGGER.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;
- for (int i = 0; i < testArray.length; i++) {
- testType = testArray[i];
- requestType = testType.getRequest();
- 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()));
-
- NameValueType[] nvArray = requestType.getCookies().getCookieArray();
- Cookie[] cookies = new Cookie[nvArray.length];
- Cookie cookie = null;
- NameValueType nv = null;
- for (int k = 0; k < nvArray.length; k++) {
- nv = nvArray[k];
- cookie = new Cookie(nv.getName(), nv.getValue());
- cookies[k] = cookie;
- }
-
- request.setCookies(cookies);
-
- responseType = testType.getResponse();
-
- ResponseData response = new ResponseData(request.getHost(), request.getPort());
- response.setStatusCode(responseType.getStatusCode());
- response.setReason(responseType.getReason());
- response.setBody(responseType.getResponseBody());
-
- bean.addRequestResponseData(request, response);
- }
- return bean;
- }
-
- public static List getDiffResults(File file) throws SessionXMLException, IOException {
- if (LOGGER.isInfoEnabled()) {
- LOGGER.info("file( " + file.getAbsolutePath() + " )");
- }
- String resourceIdentifier = file.getAbsolutePath();
- InputStream is = new FileInputStream(file);
- RecorderDiffDocument doc = null;
- try {
- XmlOptions loadOptions = new XmlOptions();
- loadOptions.setLoadLineNumbers();
- doc = RecorderDiffDocument.Factory.parse(is, loadOptions);
- }
- catch (XmlException e) {
- LOGGER.fatal("test recorder parse exception", e);
- SessionXMLException ex = new SessionXMLException("ERROR: failed parsing test recorder diff XML, file( " +
- resourceIdentifier + " )", e);
- LOGGER.fatal(ex);
- throw ex;
- }
- finally {
- if (is != null)
- is.close();
- }
-
- 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);
- }
-
- RecorderDiffDocument.RecorderDiff diff = doc.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;
- }
-
- 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 = createRecorderSessionDocument(bean, xmlOptions);
- RecorderSessionDocument.RecorderSession session = doc.getRecorderSession();
- 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);
- TestResultsType testResultsType = test.addNewTestResults();
- TestResults testResults = bean.getTestResults(i);
- testResultsType.setTestStatus(StatusType.Enum.forString(testResults.getStatus().toLowerCase()));
- }
- session.setSessionStatus(StatusType.Enum.forString(bean.getStatus().toLowerCase()));
- session.setPassedCount(bean.getPassedCount());
- session.setFailedCount(bean.getFailedCount());
- session.setTestCount(bean.getTestCount());
- 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 = RecorderDiffDocument.Factory.newInstance(xmlOptions);
- 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
- List list = results.getDiffResults();
- StringBuffer sb = new StringBuffer(64 * list.size());
- sb.append("\n");
- for (int j = 0; j < list.size(); j++) {
- sb.append(list.get(j) + "\n");
- }
- String diffString = sb.toString();
-
- request = bean.getRequestData(i);
- TestDiffType diffType = diff.addNewRequest();
- diffType.setTestNumber(results.getTestNumber());
- diffType.setUri(request.getPath());
- diffType.setDiffResults(diffString);
- }
- doc.save(diffFile, xmlOptions);
- }
-
- 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 */
- 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);
- RequestType requestType = test.addNewRequest();
- RequestData data = bean.getRequestData(i);
- 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()));
-
- ParametersType paramsType = requestType.addNewParameters();
- NameValueType param = null;
- for (int k = 0; k < data.getParamCount(); k++) {
- param = paramsType.addNewParameter();
- param.setName(data.getParamName(k));
- param.setValue(data.getParamValue(k));
- }
- {
- CookiesType cookies = requestType.addNewCookies();
- NameValueType cookie = null;
- for (int m = 0; m < data.getCookieCount(); m++) {
- cookie = cookies.addNewCookie();
- cookie.setName(data.getCookieName(m));
- cookie.setValue(data.getCookieValue(m));
- }
- }
- {
- HeadersType headersType = requestType.addNewHeaders();
- NameValueType header = null;
- for (int n = 0; n < data.getHeaderCount(); n++) {
- header = headersType.addNewHeader();
- header.setName(data.getHeaderName(n));
- header.setValue(data.getHeaderValue(n));
- }
- }
-
- ResponseType responseType = test.addNewResponse();
- ResponseData responseData = bean.getResponseData(i);
- responseType.setStatusCode(responseData.getStatusCode());
- responseType.setReason(responseData.getReason());
- responseType.setResponseBody(responseData.getBody());
-
- }
- 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 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;
- }
-
- 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);
- }
- finally {
- try{is.close();}catch(IOException ignore) {}
- }
-
- LOGGER.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 = getWebapps(is, Constants.WEBAPPS_FILE, config);
- }
- finally {
- try{if(is != null)is.close();}catch(IOException ignore) {}
- }
-
- if (LOGGER.isInfoEnabled())
- LOGGER.info("webapps( " + webapps + " )");
-
- is = loader.getResourceAsStream(Constants.TESTS_FILE);
- if (is == null)
- throw new RuntimeConfigException("Unable to obtain the resource stream for resource(" + Constants.TESTS_FILE + ")");
-
- TestDefinitions testDefinitions = null;
- try {
- testDefinitions = getTestDefinitionsInstance(is,
- Constants.TESTS_FILE,
- webapps,
- config.getBaseDirectory().getAbsolutePath());
- }
- catch (ConfigException e) {
- throw new RuntimeConfigException(e.getMessage(), e);
- }
- finally {
- try {is.close();} catch (IOException e) {}
- }
- return testDefinitions;
- }
-
- public static Config getConfig(final InputStream xmlInputStream, final String xmlResourcePath) {
-
- Document document = null;
- final String xsdResourcePath = Constants.SCHEMA_LOCATION + "/" + Constants.CONFIG_SCHEMA_NAME;
- InputStream xsdInputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
- try {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setValidating(true);
- dbf.setNamespaceAware(true);
- dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
- dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream);
-
- DocumentBuilder db = dbf.newDocumentBuilder();
- db.setErrorHandler(new ErrorHandler() {
- public void warning(SAXParseException exception) {
- if(LOGGER.isInfoEnabled())
- LOGGER.info("Validation warning validating config file \"" + xmlResourcePath +
- "\" against XML Schema \"" + xsdResourcePath);
- }
-
- public void error(SAXParseException exception) {
- throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
- xmlResourcePath + "\". Cause: " + exception, exception);
- }
-
- public void fatalError(SAXParseException exception) {
- throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
- xmlResourcePath + "\". Cause: " + exception, exception);
- }
- });
-
- db.setEntityResolver(new EntityResolver() {
- public InputSource resolveEntity(String publicId, String systemId) {
- if(systemId.endsWith(Constants.CONFIG_SCHEMA_NAME)) {
- InputStream inputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
- return new InputSource(inputStream);
- }
- else return null;
- }
- });
-
- document = db.parse(xmlInputStream);
- }
- catch(Exception e) {
- assert e instanceof ParserConfigurationException;
- throw new IllegalStateException("Exception occurred parsing document. Cause: " + e, e);
- }
-
- String servletUri = DomUtils.getChildElementText(document.getDocumentElement(), "servletURI");
- String baseDirectory = DomUtils.getChildElementText(document.getDocumentElement(), "baseDirectory");
- Element elem = DomUtils.getChildElementByName(document.getDocumentElement(), "suffixList");
-
- NodeList suffixList = elem.getElementsByTagName("suffix");
- LinkedList list = new LinkedList();
- for(int i = 0; i < suffixList.getLength(); i++) {
- list.add(DomUtils.getElementText((Element)suffixList.item(i)));
- }
-
- Config config = new Config(list, servletUri, baseDirectory);
- return config;
- }
-
- public static Webapps getWebapps(final InputStream xmlInputStream, final String xmlResourcePath, Config config) {
-
- Document document = null;
- final String xsdResourcePath = Constants.SCHEMA_LOCATION + "/" + Constants.WEBAPPS_SCHEMA_NAME;
- InputStream xsdInputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
- try {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setValidating(true);
- dbf.setNamespaceAware(true);
- dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
- dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream);
-
- DocumentBuilder db = dbf.newDocumentBuilder();
- db.setErrorHandler(new ErrorHandler() {
- public void warning(SAXParseException exception) {
- if(LOGGER.isInfoEnabled())
- LOGGER.info("Validation warning validating config file \"" + xmlResourcePath +
- "\" against XML Schema \"" + xsdResourcePath);
- }
-
- public void error(SAXParseException exception) {
- throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
- xmlResourcePath + "\". Cause: " + exception, exception);
- }
-
- public void fatalError(SAXParseException exception) {
- throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
- xmlResourcePath + "\". Cause: " + exception, exception);
- }
- });
-
- db.setEntityResolver(new EntityResolver() {
- public InputSource resolveEntity(String publicId, String systemId) {
- if(systemId.endsWith(Constants.SERVER_SCHEMA_NAME)) {
- InputStream inputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
- return new InputSource(inputStream);
- }
- else return null;
- }
- });
-
- document = db.parse(xmlInputStream);
- }
- catch(Exception e) {
- assert e instanceof ParserConfigurationException;
- throw new IllegalStateException("Exception occurred parsing document. Cause: " + e, e);
- }
-
- Element elem = document.getDocumentElement();
- String name = DomUtils.getChildElementText(document.getDocumentElement(), "name");
- String hostname = DomUtils.getChildElementText(document.getDocumentElement(), "hostname");
- String portString = DomUtils.getChildElementText(document.getDocumentElement(), "port");
- int port = Integer.parseInt(portString);
-
- ServerConfig server = new ServerConfig(name, hostname, port);
-
- ArrayList webappList = new ArrayList();
- Config defaultConfig = config;
- elem = DomUtils.getChildElementByName(elem, "webapps");
- NodeList webappElements = elem.getElementsByTagName("webapp");
- for(int i = 0; i < webappElements.getLength(); i++) {
- Element webappElem = (Element)webappElements.item(i);
-
- Config webappConfig = null;
- Element overrideDefaultConfig = DomUtils.getChildElementByName(webappElem, "overrideDefaultConfig");
- if (overrideDefaultConfig == null)
- webappConfig = defaultConfig;
- else {
- String[] suffixes = null;
- String servletURI = null;
- Element suffixListElem = DomUtils.getChildElementByName(overrideDefaultConfig, "suffixListElem");
-
- if (suffixListElem != null && suffixListElem.getElementsByTagName("suffix").getLength() > 0) {
- NodeList suffixList = suffixListElem.getElementsByTagName("suffix");
- suffixes = new String[suffixList.getLength()];
- for(int j = 0; j < suffixes.length; j++) {
- suffixes[j] = DomUtils.getElementText((Element)suffixList.item(i));
- }
- servletURI = DomUtils.getChildElementText(overrideDefaultConfig, "servletURI");
- }
-
- webappConfig = new Config(suffixes, servletURI, defaultConfig.getBaseDirectory().getAbsolutePath());
- }
-
- String testModeString = DomUtils.getChildElementText(webappElem, "testMode");
- boolean testMode = Boolean.parseBoolean(testModeString);
-
- WebappConfig webapp = new WebappConfig(
- DomUtils.getChildElementText(webappElem, "name"),
- DomUtils.getChildElementText(webappElem, "description"),
- server,
- testMode,
- DomUtils.getChildElementText(webappElem, "contextRoot"),
- DomUtils.getChildElementText(webappElem, "testDefinitionsDirectory"),
- webappConfig);
-
- webappList.add(webapp);
- }
-
- return new Webapps(webappList);
- }
-
- public static TestDefinitions getTestDefinitionsInstance(final InputStream xmlInputStream,
- final String xmlResourcePath,
- Webapps webapps,
- String baseDirPath)
- throws ConfigException {
-
- Document document = null;
- final String xsdResourcePath = Constants.SCHEMA_LOCATION + "/" + Constants.TESTS_SCHEMA_NAME;
- InputStream xsdInputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
- try {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setValidating(true);
- dbf.setNamespaceAware(true);
- dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
- dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream);
-
- DocumentBuilder db = dbf.newDocumentBuilder();
- db.setErrorHandler(new ErrorHandler() {
- public void warning(SAXParseException exception) {
- if(LOGGER.isInfoEnabled())
- LOGGER.info("Validation warning validating config file \"" + xmlResourcePath +
- "\" against XML Schema \"" + xsdResourcePath);
- }
-
- public void error(SAXParseException exception) {
- throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
- xmlResourcePath + "\". Cause: " + exception, exception);
- }
-
- public void fatalError(SAXParseException exception) {
- throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
- xmlResourcePath + "\". Cause: " + exception, exception);
- }
- });
-
- db.setEntityResolver(new EntityResolver() {
- public InputSource resolveEntity(String publicId, String systemId) {
- if(systemId.endsWith(Constants.TESTS_SCHEMA_NAME)) {
- InputStream inputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
- return new InputSource(inputStream);
- }
- else return null;
- }
- });
-
- document = db.parse(xmlInputStream);
- }
- catch(Exception e) {
- assert e instanceof ParserConfigurationException;
- throw new IllegalStateException("Exception occurred parsing document. Cause: " + e, e);
- }
-
- Element rootElement = document.getDocumentElement();
- Element categoriesElement = DomUtils.getChildElementByName(rootElement, "categories");
- NodeList categoryNodes = categoriesElement.getElementsByTagName("category");
-
- LinkedList testDefinitions = new LinkedList();
- Category[] categoryArray = new Category[categoryNodes.getLength()];
- for(int i = 0; i < categoryNodes.getLength(); i++) {
- Element category = (Element)categoryNodes.item(i);
-
- String name = DomUtils.getChildElementText(category, "name");
- String description = DomUtils.getChildElementText(category, "description");
-
- categoryArray[i] = new Category(name, description, baseDirPath);
- }
- Categories categories = new Categories(categoryArray);
-
- Element testsElement = DomUtils.getChildElementByName(rootElement, "tests");
- NodeList testNodes = testsElement.getElementsByTagName("test");
- for(int j = 0; j < testNodes.getLength(); j++) {
- Element testElement = (Element)testNodes.item(j);
-
- String testName = DomUtils.getChildElementText(testElement, "name");
- String testWebapp = DomUtils.getChildElementText(testElement, "webapp");
- String testDescription = DomUtils.getChildElementText(testElement, "description");
-
- LinkedList testCategories = new LinkedList();
- Element testCategoriesElement = DomUtils.getChildElementByName(testElement, "categories");
- if(testCategoriesElement != null) {
- NodeList categoriesNodes = testCategoriesElement.getElementsByTagName("category");
- for(int i = 0; i < categoriesNodes.getLength(); i++) {
- Element category = (Element)categoriesNodes.item(i);
-
- String categoryName = DomUtils.getElementText(category);
- Category testCategory = categories.getCategory(categoryName);
-
- if(testCategory == null)
- throw new ConfigException("Invalid test category name \"" + categoryName + "\" for test named \"" + testName + "\"");
-
- testCategories.add(testCategory);
- }
- }
-
- WebappConfig webapp = webapps.getWebapp(testWebapp);
- if (webapp == null)
- throw new ConfigException("Invalid test webapp name \"" + testWebapp + "\" referenced for test \"" + testName + "\"");
-
- TestDefinition testDef = new TestDefinition(testName, testDescription, webapp, testCategories);
- categories.addTest(testDef);
- testDefinitions.add(testDef);
- }
- return new TestDefinitions(testDefinitions, categories, webapps);
- }
-
- 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") + " )");
- LOGGER.error(ce);
- throw ce;
- }
- }
-}
+ /**
+ */
+ public final class XMLHelper {
+
+ private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
+ private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
+ private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
+ private static final Logger LOGGER = Logger.getInstance(XMLHelper.class);
+
+ public static ServerDefinition getServerDefinition(final InputStream xmlInputStream, final String xmlResourcePath) {
+
+ Document document = null;
+ final String xsdResourcePath = Constants.SCHEMA_LOCATION + "/" + Constants.SERVER_SCHEMA_NAME;
+ InputStream xsdInputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
+ try {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setValidating(true);
+ dbf.setNamespaceAware(true);
+ dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
+ dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream);
+
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ db.setErrorHandler(new ErrorHandler() {
+ public void warning(SAXParseException exception) {
+ if(LOGGER.isInfoEnabled())
+ LOGGER.info("Validation warning validating config file \"" + xmlResourcePath +
+ "\" against XML Schema \"" + xsdResourcePath);
+ }
+
+ public void error(SAXParseException exception) {
+ throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
+ xmlResourcePath + "\". Cause: " + exception, exception);
+ }
+
+ public void fatalError(SAXParseException exception) {
+ throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
+ xmlResourcePath + "\". Cause: " + exception, exception);
+ }
+ });
+
+ db.setEntityResolver(new EntityResolver() {
+ public InputSource resolveEntity(String publicId, String systemId) {
+ if(systemId.endsWith(Constants.SERVER_SCHEMA_NAME)) {
+ InputStream inputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
+ return new InputSource(inputStream);
+ }
+ else return null;
+ }
+ });
+
+ document = db.parse(xmlInputStream);
+ }
+ catch(Exception e) {
+ assert e instanceof ParserConfigurationException;
+ throw new IllegalStateException("Exception occurred parsing document. Cause: " + e, e);
+ }
+
+ String name = DomUtils.getChildElementText(document.getDocumentElement(), "name");
+ String hostname = DomUtils.getChildElementText(document.getDocumentElement(), "hostname");
+ String portString = DomUtils.getChildElementText(document.getDocumentElement(), "port");
+ int port = Integer.parseInt(portString);
+
+ ServerDefinition server = new ServerDefinition(name, hostname, port);
+
+ Element elem = DomUtils.getChildElementByName(document.getDocumentElement(), "webapps");
+ NodeList webappList = elem.getElementsByTagName("webapp");
+ for(int i = 0; i < webappList.getLength(); i++) {
+ Element webappElem = (Element)webappList.item(i);
+ WebappDefinition webapp = new WebappDefinition(
+ DomUtils.getChildElementText(webappElem, "name"),
+ DomUtils.getChildElementText(webappElem, "description"),
+ DomUtils.getChildElementText(webappElem, "contextRoot"),
+ DomUtils.getChildElementText(webappElem, "servletURI")
+ );
+ server.addWebapp(webapp);
+ }
+
+ return server;
+ }
+
+ public static RecordSessionBean getRecordSessionBean(File file)
+ throws SessionXMLException, IOException {
+ if (LOGGER.isInfoEnabled())
+ LOGGER.info("file( " + file.getAbsolutePath() + " )");
+
+ String resourceIdentifier = file.getAbsolutePath();
+ InputStream is = new FileInputStream(file);
+
+ RecorderSessionDocument doc = null;
+ try {
+ XmlOptions loadOptions = new XmlOptions();
+ loadOptions.setLoadLineNumbers();
+ doc = RecorderSessionDocument.Factory.parse(is, loadOptions);
+ }
+ catch (XmlException e) {
+ LOGGER.fatal("test recorder parse exception", e);
+ SessionXMLException ex = new SessionXMLException("ERROR: failed parsing test recorder record session XML, file( " +
+ resourceIdentifier + " )", e);
+ LOGGER.fatal(ex);
+ throw ex;
+ }
+ finally {
+ if (is != null) {
+ try {
+ is.close();
+ }
+ catch (IOException e) {
+ LOGGER.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.setTester(xmlSession.getTester());
+ bean.setDescription(xmlSession.getDescription());
+ try {
+ bean.setStartDate(xmlSession.getStartDate());
+ }
+ catch (ParseException e) {
+ String msg = "ERROR: failed parsing start date( " + xmlSession.getStartDate() + " )";
+ LOGGER.error(msg);
+ throw new SessionXMLException(msg, e);
+ }
+ try {
+ bean.setEndDate(xmlSession.getEndDate());
+ }
+ catch (ParseException e) {
+ String msg = "ERROR: failed parsing end date( " + xmlSession.getEndDate() + " )";
+ LOGGER.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;
+ for (int i = 0; i < testArray.length; i++) {
+ testType = testArray[i];
+ requestType = testType.getRequest();
+ 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()));
+
+ NameValueType[] nvArray = requestType.getCookies().getCookieArray();
+ Cookie[] cookies = new Cookie[nvArray.length];
+ Cookie cookie = null;
+ NameValueType nv = null;
+ for (int k = 0; k < nvArray.length; k++) {
+ nv = nvArray[k];
+ cookie = new Cookie(nv.getName(), nv.getValue());
+ cookies[k] = cookie;
+ }
+
+ request.setCookies(cookies);
+
+ responseType = testType.getResponse();
+
+ ResponseData response = new ResponseData(request.getHost(), request.getPort());
+ response.setStatusCode(responseType.getStatusCode());
+ response.setReason(responseType.getReason());
+ response.setBody(responseType.getResponseBody());
+
+ bean.addRequestResponseData(request, response);
+ }
+ return bean;
+ }
+
+ public static List getDiffResults(File file)
+ throws IOException {
+
+ if (LOGGER.isInfoEnabled())
+ LOGGER.info("file( " + file.getAbsolutePath() + " )");
+
+ final String xmlResourcePath = file.getAbsolutePath();
+ final InputStream xmlInputStream = new FileInputStream(file);
+
+ Document document = null;
+ final String xsdResourcePath = Constants.SCHEMA_LOCATION + "/" + Constants.DIFF_SESSION_SCHEMA_NAME;
+ InputStream xsdInputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
+ try {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setValidating(true);
+ dbf.setNamespaceAware(true);
+ dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
+ dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream);
+
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ db.setErrorHandler(new ErrorHandler() {
+ public void warning(SAXParseException exception) {
+ if(LOGGER.isInfoEnabled())
+ LOGGER.info("Validation warning validating config file \"" + xmlResourcePath +
+ "\" against XML Schema \"" + xsdResourcePath);
+ }
+
+ public void error(SAXParseException exception) {
+ throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
+ xmlResourcePath + "\". Cause: " + exception, exception);
+ }
+
+ public void fatalError(SAXParseException exception) {
+ throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
+ xmlResourcePath + "\". Cause: " + exception, exception);
+ }
+ });
+
+ db.setEntityResolver(new EntityResolver() {
+ public InputSource resolveEntity(String publicId, String systemId) {
+ if(systemId.endsWith(Constants.DIFF_SESSION_SCHEMA_NAME)) {
+ InputStream inputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
+ return new InputSource(inputStream);
+ }
+ else return null;
+ }
+ });
+
+ document = db.parse(xmlInputStream);
+ }
+ catch(Exception e) {
+ throw new IllegalStateException("Exception occurred parsing document. Cause: " + e, e);
+ }
+
+ LinkedList requestList = new LinkedList();
+ Element rootElement = document.getDocumentElement();
+
+ NodeList requestNodeList = rootElement.getElementsByTagName("request");
+ for(int i = 0; i < requestNodeList.getLength(); i++) {
+ Element requestElement = (Element)requestNodeList.item(i);
+ String testNumberStr = DomUtils.getChildElementText(requestElement, "testNumber");
+ int testNumber = Integer.parseInt(testNumberStr);
+ String uri = DomUtils.getChildElementText(requestElement, "uri");
+ String diffResults = DomUtils.getChildElementText(requestElement, "diffResults");
+
+ TestResults results = new TestResults(testNumber, uri, false, false);
+ results.addDiffResult(diffResults);
+ requestList.add(results);
+ }
+
+ return requestList;
+ }
+
+ 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 = createRecorderSessionDocument(bean, xmlOptions);
+ RecorderSessionDocument.RecorderSession session = doc.getRecorderSession();
+ 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);
+ TestResultsType testResultsType = test.addNewTestResults();
+ TestResults testResults = bean.getTestResults(i);
+ testResultsType.setTestStatus(StatusType.Enum.forString(testResults.getStatus().toLowerCase()));
+ }
+ session.setSessionStatus(StatusType.Enum.forString(bean.getStatus().toLowerCase()));
+ session.setPassedCount(bean.getPassedCount());
+ session.setFailedCount(bean.getFailedCount());
+ session.setTestCount(bean.getTestCount());
+ doc.save(playbackFile, xmlOptions);
+ }
+
+ public static void createDiffFile(File diffFile, PlaybackSessionBean bean) {
+ /*
+ note, I'd love to use the javax.xml.* infrastructure to write out the XML document here, but
+ due to configuration differences between Tomcat 5.0 and Java 5.0, this isn't possible without
+ taking additional dependencies on JARs like Xalan...
+
+ <sigh/>
+
+ So, we're just going to print XML by hand.
+ */
+
+ StringBuffer buf = new StringBuffer();
+ buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+ buf.append("<recorderDiff xmlns=\"http://beehive.apache.org/netui/tools/testrecorder/2004/diffsession\">\n");
+ for(int i = 0; i < bean.getTestCount(); i++) {
+ TestResults results = bean.getTestResults(i);
+ if(results.isTestPassed())
+ continue;
+
+ /* otherwise, the test failed, start building the XML */
+ RequestData request = bean.getRequestData(i);
+
+ buf.append("<request>\n");
+ buf.append("<testNumber>\n");
+ buf.append(results.getTestNumber());
+ buf.append("\n");
+ buf.append("</testNumber>\n");
+
+ buf.append("<uri>\n");
+ buf.append(results.getUri());
+ buf.append("\n");
+ buf.append("</uri>\n");
+
+ List list = results.getDiffResults();
+ StringBuffer sb = new StringBuffer(64 * list.size());
+ sb.append("\n");
+ for (int j = 0; j < list.size(); j++)
+ sb.append(list.get(j)).append("\n");
+
+ String diffString = sb.toString();
+
+ buf.append("<diffResults>\n");
+ buf.append("<![CDATA[\n");
+ buf.append(diffString);
+ buf.append("\n");
+ buf.append("]]>\n");
+ buf.append("</diffResults>\n");
+
+ buf.append("</request>\n");
+ }
+
+ buf.append("</recorderDiff>\n");
+
+ Writer writer = null;
+ try {
+ writer = new FileWriter(diffFile);
+ writer.append(buf.toString());
+ writer.flush();
+ }
+ catch(Exception e) {
+ throw new IllegalStateException("Exception occurred writing XML diff document \"" + diffFile.getAbsolutePath() + "\"");
+ }
+ finally{
+ try {if(writer != null) writer.close();}catch(Exception ignore) {}
+ }
+ }
+
+ 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 */
+ 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);
+ RequestType requestType = test.addNewRequest();
+ RequestData data = bean.getRequestData(i);
+ 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()));
+
+ ParametersType paramsType = requestType.addNewParameters();
+ NameValueType param = null;
+ for (int k = 0; k < data.getParamCount(); k++) {
+ param = paramsType.addNewParameter();
+ param.setName(data.getParamName(k));
+ param.setValue(data.getParamValue(k));
+ }
+ {
+ CookiesType cookies = requestType.addNewCookies();
+ NameValueType cookie = null;
+ for (int m = 0; m < data.getCookieCount(); m++) {
+ cookie = cookies.addNewCookie();
+ cookie.setName(data.getCookieName(m));
+ cookie.setValue(data.getCookieValue(m));
+ }
+ }
+ {
+ HeadersType headersType = requestType.addNewHeaders();
+ NameValueType header = null;
+ for (int n = 0; n < data.getHeaderCount(); n++) {
+ header = headersType.addNewHeader();
+ header.setName(data.getHeaderName(n));
+ header.setValue(data.getHeaderValue(n));
+ }
+ }
+
+ ResponseType responseType = test.addNewResponse();
+ ResponseData responseData = bean.getResponseData(i);
+ responseType.setStatusCode(responseData.getStatusCode());
+ responseType.setReason(responseData.getReason());
+ responseType.setResponseBody(responseData.getBody());
+
+ }
+ 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 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;
+ }
+
+ 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);
+ }
+ finally {
+ try{is.close();}catch(IOException ignore) {}
+ }
+
+ LOGGER.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 = getWebapps(is, Constants.WEBAPPS_FILE, config);
+ }
+ finally {
+ try{if(is != null)is.close();}catch(IOException ignore) {}
+ }
+
+ if (LOGGER.isInfoEnabled())
+ LOGGER.info("webapps( " + webapps + " )");
+
+ is = loader.getResourceAsStream(Constants.TESTS_FILE);
+ if (is == null)
+ throw new RuntimeConfigException("Unable to obtain the resource stream for resource(" + Constants.TESTS_FILE + ")");
+
+ TestDefinitions testDefinitions = null;
+ try {
+ testDefinitions = getTestDefinitionsInstance(is,
+ Constants.TESTS_FILE,
+ webapps,
+ config.getBaseDirectory().getAbsolutePath());
+ }
+ catch (ConfigException e) {
+ throw new RuntimeConfigException(e.getMessage(), e);
+ }
+ finally {
+ try {is.close();} catch (IOException e) {}
+ }
+ return testDefinitions;
+ }
+
+ public static Config getConfig(final InputStream xmlInputStream, final String xmlResourcePath) {
+
+ Document document = null;
+ final String xsdResourcePath = Constants.SCHEMA_LOCATION + "/" + Constants.CONFIG_SCHEMA_NAME;
+ InputStream xsdInputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
+ try {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setValidating(true);
+ dbf.setNamespaceAware(true);
+ dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
+ dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream);
+
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ db.setErrorHandler(new ErrorHandler() {
+ public void warning(SAXParseException exception) {
+ if(LOGGER.isInfoEnabled())
+ LOGGER.info("Validation warning validating config file \"" + xmlResourcePath +
+ "\" against XML Schema \"" + xsdResourcePath);
+ }
+
+ public void error(SAXParseException exception) {
+ throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
+ xmlResourcePath + "\". Cause: " + exception, exception);
+ }
+
+ public void fatalError(SAXParseException exception) {
+ throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
+ xmlResourcePath + "\". Cause: " + exception, exception);
+ }
+ });
+
+ db.setEntityResolver(new EntityResolver() {
+ public InputSource resolveEntity(String publicId, String systemId) {
+ if(systemId.endsWith(Constants.CONFIG_SCHEMA_NAME)) {
+ InputStream inputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
+ return new InputSource(inputStream);
+ }
+ else return null;
+ }
+ });
+
+ document = db.parse(xmlInputStream);
+ }
+ catch(Exception e) {
+ assert e instanceof ParserConfigurationException;
+ throw new IllegalStateException("Exception occurred parsing document. Cause: " + e, e);
+ }
+
+ String servletUri = DomUtils.getChildElementText(document.getDocumentElement(), "servletURI");
+ String baseDirectory = DomUtils.getChildElementText(document.getDocumentElement(), "baseDirectory");
+ Element elem = DomUtils.getChildElementByName(document.getDocumentElement(), "suffixList");
+
+ NodeList suffixList = elem.getElementsByTagName("suffix");
+ LinkedList list = new LinkedList();
+ for(int i = 0; i < suffixList.getLength(); i++) {
+ list.add(DomUtils.getElementText((Element)suffixList.item(i)));
+ }
+
+ Config config = new Config(list, servletUri, baseDirectory);
+ return config;
+ }
+
+ public static Webapps getWebapps(final InputStream xmlInputStream, final String xmlResourcePath, Config config) {
+
+ Document document = null;
+ final String xsdResourcePath = Constants.SCHEMA_LOCATION + "/" + Constants.WEBAPPS_SCHEMA_NAME;
+ InputStream xsdInputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
+ try {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setValidating(true);
+ dbf.setNamespaceAware(true);
+ dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
+ dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream);
+
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ db.setErrorHandler(new ErrorHandler() {
+ public void warning(SAXParseException exception) {
+ if(LOGGER.isInfoEnabled())
+ LOGGER.info("Validation warning validating config file \"" + xmlResourcePath +
+ "\" against XML Schema \"" + xsdResourcePath);
+ }
+
+ public void error(SAXParseException exception) {
+ throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
+ xmlResourcePath + "\". Cause: " + exception, exception);
+ }
+
+ public void fatalError(SAXParseException exception) {
+ throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
+ xmlResourcePath + "\". Cause: " + exception, exception);
+ }
+ });
+
+ db.setEntityResolver(new EntityResolver() {
+ public InputSource resolveEntity(String publicId, String systemId) {
+ if(systemId.endsWith(Constants.SERVER_SCHEMA_NAME)) {
+ InputStream inputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
+ return new InputSource(inputStream);
+ }
+ else return null;
+ }
+ });
+
+ document = db.parse(xmlInputStream);
+ }
+ catch(Exception e) {
+ assert e instanceof ParserConfigurationException;
+ throw new IllegalStateException("Exception occurred parsing document. Cause: " + e, e);
+ }
+
+ Element elem = document.getDocumentElement();
+ String name = DomUtils.getChildElementText(document.getDocumentElement(), "name");
+ String hostname = DomUtils.getChildElementText(document.getDocumentElement(), "hostname");
+ String portString = DomUtils.getChildElementText(document.getDocumentElement(), "port");
+ int port = Integer.parseInt(portString);
+
+ ServerConfig server = new ServerConfig(name, hostname, port);
+
+ ArrayList webappList = new ArrayList();
+ Config defaultConfig = config;
+ elem = DomUtils.getChildElementByName(elem, "webapps");
+ NodeList webappElements = elem.getElementsByTagName("webapp");
+ for(int i = 0; i < webappElements.getLength(); i++) {
+ Element webappElem = (Element)webappElements.item(i);
+
+ Config webappConfig = null;
+ Element overrideDefaultConfig = DomUtils.getChildElementByName(webappElem, "overrideDefaultConfig");
+ if (overrideDefaultConfig == null)
+ webappConfig = defaultConfig;
+ else {
+ String[] suffixes = null;
+ String servletURI = null;
+ Element suffixListElem = DomUtils.getChildElementByName(overrideDefaultConfig, "suffixListElem");
+
+ if (suffixListElem != null && suffixListElem.getElementsByTagName("suffix").getLength() > 0) {
+ NodeList suffixList = suffixListElem.getElementsByTagName("suffix");
+ suffixes = new String[suffixList.getLength()];
+ for(int j = 0; j < suffixes.length; j++) {
+ suffixes[j] = DomUtils.getElementText((Element)suffixList.item(i));
+ }
+ servletURI = DomUtils.getChildElementText(overrideDefaultConfig, "servletURI");
+ }
+
+ webappConfig = new Config(suffixes, servletURI, defaultConfig.getBaseDirectory().getAbsolutePath());
+ }
+
+ String testModeString = DomUtils.getChildElementText(webappElem, "testMode");
+ boolean testMode = Boolean.parseBoolean(testModeString);
+
+ WebappConfig webapp = new WebappConfig(
+ DomUtils.getChildElementText(webappElem, "name"),
+ DomUtils.getChildElementText(webappElem, "description"),
+ server,
+ testMode,
+ DomUtils.getChildElementText(webappElem, "contextRoot"),
+ DomUtils.getChildElementText(webappElem, "testDefinitionsDirectory"),
+ webappConfig);
+
+ webappList.add(webapp);
+ }
+
+ return new Webapps(webappList);
+ }
+
+ public static TestDefinitions getTestDefinitionsInstance(final InputStream xmlInputStream,
+ final String xmlResourcePath,
+ Webapps webapps,
+ String baseDirPath)
+ throws ConfigException {
+
+ Document document = null;
+ final String xsdResourcePath = Constants.SCHEMA_LOCATION + "/" + Constants.TESTS_SCHEMA_NAME;
+ InputStream xsdInputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
+ try {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ dbf.setValidating(true);
+ dbf.setNamespaceAware(true);
+ dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
+ dbf.setAttribute(JAXP_SCHEMA_SOURCE, xsdInputStream);
+
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ db.setErrorHandler(new ErrorHandler() {
+ public void warning(SAXParseException exception) {
+ if(LOGGER.isInfoEnabled())
+ LOGGER.info("Validation warning validating config file \"" + xmlResourcePath +
+ "\" against XML Schema \"" + xsdResourcePath);
+ }
+
+ public void error(SAXParseException exception) {
+ throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
+ xmlResourcePath + "\". Cause: " + exception, exception);
+ }
+
+ public void fatalError(SAXParseException exception) {
+ throw new IllegalStateException("Validation errors occurred parsing the config file \"" +
+ xmlResourcePath + "\". Cause: " + exception, exception);
+ }
+ });
+
+ db.setEntityResolver(new EntityResolver() {
+ public InputSource resolveEntity(String publicId, String systemId) {
+ if(systemId.endsWith(Constants.TESTS_SCHEMA_NAME)) {
+ InputStream inputStream = XMLHelper.class.getClassLoader().getResourceAsStream(xsdResourcePath);
+ return new InputSource(inputStream);
+ }
+ else return null;
+ }
+ });
+
+ document = db.parse(xmlInputStream);
+ }
+ catch(Exception e) {
+ assert e instanceof ParserConfigurationException;
+ throw new IllegalStateException("Exception occurred parsing document. Cause: " + e, e);
+ }
+
+ Element rootElement = document.getDocumentElement();
+ Element categoriesElement = DomUtils.getChildElementByName(rootElement, "categories");
+ NodeList categoryNodes = categoriesElement.getElementsByTagName("category");
+
+ LinkedList testDefinitions = new LinkedList();
+ Category[] categoryArray = new Category[categoryNodes.getLength()];
+ for(int i = 0; i < categoryNodes.getLength(); i++) {
+ Element category = (Element)categoryNodes.item(i);
+
+ String name = DomUtils.getChildElementText(category, "name");
+ String description = DomUtils.getChildElementText(category, "description");
+
+ categoryArray[i] = new Category(name, description, baseDirPath);
+ }
+ Categories categories = new Categories(categoryArray);
+
+ Element testsElement = DomUtils.getChildElementByName(rootElement, "tests");
+ NodeList testNodes = testsElement.getElementsByTagName("test");
+ for(int j = 0; j < testNodes.getLength(); j++) {
+ Element testElement = (Element)testNodes.item(j);
+
+ String testName = DomUtils.getChildElementText(testElement, "name");
+ String testWebapp = DomUtils.getChildElementText(testElement, "webapp");
+ String testDescription = DomUtils.getChildElementText(testElement, "description");
+
+ LinkedList testCategories = new LinkedList();
+ Element testCategoriesElement = DomUtils.getChildElementByName(testElement, "categories");
+ if(testCategoriesElement != null) {
+ NodeList categoriesNodes = testCategoriesElement.getElementsByTagName("category");
+ for(int i = 0; i < categoriesNodes.getLength(); i++) {
+ Element category = (Element)categoriesNodes.item(i);
+
+ String categoryName = DomUtils.getElementText(category);
+ Category testCategory = categories.getCategory(categoryName);
+
+ if(testCategory == null)
+ throw new ConfigException("Invalid test category name \"" + categoryName + "\" for test named \"" + testName + "\"");
+
+ testCategories.add(testCategory);
+ }
+ }
+
+ WebappConfig webapp = webapps.getWebapp(testWebapp);
+ if (webapp == null)
+ throw new ConfigException("Invalid test webapp name \"" + testWebapp + "\" referenced for test \"" + testName + "\"");
+
+ TestDefinition testDef = new TestDefinition(testName, testDescription, webapp, testCategories);
+ categories.addTest(testDef);
+ testDefinitions.add(testDef);
+ }
+ return new TestDefinitions(testDefinitions, categories, webapps);
+ }
+
+ 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") + " )");
+ LOGGER.error(ce);
+ throw ce;
+ }
+ }
+ }
Modified: beehive/trunk/netui/test/webapps/drt/build.xml
URL: http://svn.apache.org/viewcvs/beehive/trunk/netui/test/webapps/drt/build.xml?rev=328684&r1=328683&r2=328684&view=diff
==============================================================================
--- beehive/trunk/netui/test/webapps/drt/build.xml (original)
+++ beehive/trunk/netui/test/webapps/drt/build.xml Wed Oct 26 10:09:59 2005
@@ -83,7 +83,7 @@
</copy>
</target>
- <target name="clean" description="Clean webapp">
+ <target name="clean" description="Clean webapp" unless="nobuild">
<echo message="--------------------------------------------------"/>
<echo message="| NetUI coreWeb DRT webapp clean starting |"/>
<echo message="--------------------------------------------------"/>