Example usage for javax.xml.parsers ParserConfigurationException printStackTrace

List of usage examples for javax.xml.parsers ParserConfigurationException printStackTrace

Introduction

In this page you can find the example usage for javax.xml.parsers ParserConfigurationException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.ut.biolab.medsavant.shared.util.VersionSettings.java

public static boolean isCompatible(URL url, String queryVersion, String hostVersion, boolean exactMatchByPass)
        throws SAXException, SocketTimeoutException, IOException {

    LOG.info("Checking compatibility between " + queryVersion + " and host: " + hostVersion);

    if (exactMatchByPass) {
        if (hostVersion.equals(queryVersion)) {
            LOG.info("Client and server versions match exactly");
            return true;
        }/*w w w . j a  v  a2  s  .com*/
    }

    LOG.info("Client and server versions aren't an exact match, looking up compatibility...");

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        ex.printStackTrace();
        return false;
    }
    Document doc = null;

    try {
        doc = dBuilder.parse(NetworkUtils.openStream(url, timeoutVal, timeoutVal));
    } catch (SocketTimeoutException sto) {
        LOG.info("Timed out after " + timeoutVal + " seconds");
        timeoutVal = SUBSEQUENT_TIMEOUT;
        throw sto;
    }
    timeoutVal = FIRST_TIMEOUT;

    doc.getDocumentElement().normalize();
    System.out.println("Document element normalized");
    Map<String, Set<String>> versionMap = new HashMap<String, Set<String>>();
    String nodeName = "host"; //(isServer ? "server" : "client");
    NodeList nodes = doc.getElementsByTagName(nodeName);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node n = nodes.item(i);
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            Element e = (Element) n;
            String versionNum = e.getAttribute("name");
            if (versionNum != null && !versionNum.equals("")) {
                versionMap.put(versionNum, MiscUtils.getTagValues(e, "compatible"));
            }
        }
    }

    return versionMap.containsKey(hostVersion) && versionMap.get(hostVersion).contains(queryVersion);

}

From source file:org.webtestingexplorer.state.CustomizedPropertiesElementsState.java

private Map<WebElementIdentifier, Map<String, String>> parseXML(String xmlString) {
    Map<WebElementIdentifier, Map<String, String>> elementProperties = new HashMap<WebElementIdentifier, Map<String, String>>();
    XpathWebElementIdentifier identifier;
    Map<String, String> attributeMap;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document doc = null;/*from www. jav a 2  s .  c o  m*/

    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xmlString));

        doc = db.parse(is);
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (SAXException se) {
        se.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    if (doc == null) {
        return elementProperties;
    }

    NodeList nl = doc.getElementsByTagName("element");
    if (nl != null && nl.getLength() > 0) {
        // Loop through all elements
        for (int i = 0; i < nl.getLength(); ++i) {
            identifier = null;
            attributeMap = null;
            Element el = (Element) nl.item(i);

            // Get xpath
            NodeList xpaths = el.getElementsByTagName("xpath");
            Element xpathElement = (Element) xpaths.item(0);
            String xpath = getCharacterDataFromElement(xpathElement);
            identifier = new XpathWebElementIdentifier(xpath);

            NodeList attributes = el.getElementsByTagName("attribute");
            if (attributes != null && attributes.getLength() > 0) {
                // Loop through all attributes
                attributeMap = new HashMap<String, String>();
                for (int j = 0; j < attributes.getLength(); ++j) {
                    Element attributeElement = (Element) attributes.item(j);
                    NamedNodeMap attributeNodeMap = attributeElement.getAttributes();
                    for (int m = 0; m < attributeNodeMap.getLength(); ++m) {
                        Node attributeNode = attributeNodeMap.item(m);
                        attributeMap.put(attributeNode.getNodeName(), attributeNode.getNodeValue());
                    }
                } // for
            }

            if (identifier != null && attributeMap != null) {
                elementProperties.put(identifier, attributeMap);
            }
        } // for
    }
    return elementProperties;
}

From source file:org.wso2.carbon.event.simulator.core.internal.ds.CarbonEventSimulator.java

@Override
public void createConfigurationXMLForDataSource(String dataSourceConfigAndEventStreamInfo,
        AxisConfiguration axisConfiguration) throws AxisFault {

    String repo = axisConfiguration.getRepository().getPath();
    String path = repo + EventSimulatorConstant.DATA_SOURCE_DEPLOY_DIRECTORY_PATH;

    try {//from  w  ww  . j a  v a 2s. c o m
        JSONObject jsonConvertedInfo = new JSONObject(dataSourceConfigAndEventStreamInfo);
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        String fileName = jsonConvertedInfo.getString(EventSimulatorConstant.CONFIGURATION_NAME);

        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement(EventSimulatorConstant.ROOT_ELEMENT_NAME);
        rootElement.setAttribute("type", "database");
        rootElement.setAttribute("name",
                jsonConvertedInfo.getString(EventSimulatorConstant.CONFIGURATION_NAME));
        doc.appendChild(rootElement);

        Element dataSourceName = doc.createElement(EventSimulatorConstant.DATA_SOURCE_NAME);
        dataSourceName.appendChild(
                doc.createTextNode(jsonConvertedInfo.getString(EventSimulatorConstant.DATA_SOURCE_NAME)));
        rootElement.appendChild(dataSourceName);

        Element tableName = doc.createElement(EventSimulatorConstant.TABLE_NAME);
        tableName.appendChild(
                doc.createTextNode(jsonConvertedInfo.getString(EventSimulatorConstant.TABLE_NAME)));
        rootElement.appendChild(tableName);

        Element streamNameID = doc.createElement(EventSimulatorConstant.EVENT_STREAM_ID);
        streamNameID.appendChild(
                doc.createTextNode(jsonConvertedInfo.getString(EventSimulatorConstant.EVENT_STREAM_ID)));
        rootElement.appendChild(streamNameID);

        Element columnMappings = doc.createElement("columnMappings");

        JSONArray databaseColumnAndStreamAttributeInfo1 = jsonConvertedInfo
                .getJSONArray(EventSimulatorConstant.DATABASE_COLUMNS_AND_STREAM_ATTRIBUTE_INFO);
        for (int i = 0; i < databaseColumnAndStreamAttributeInfo1.length(); i++) {
            JSONObject temp = databaseColumnAndStreamAttributeInfo1.getJSONObject(i);

            Element columnMapping = doc.createElement("columnMapping");
            columnMapping.setAttribute(EventSimulatorConstant.COLUMN_NAME,
                    temp.getString(EventSimulatorConstant.COLUMN_NAME));
            columnMapping.setAttribute(EventSimulatorConstant.STREAM_ATTRIBUTE_NAME,
                    temp.getString(EventSimulatorConstant.STREAM_ATTRIBUTE_NAME));

            columnMappings.appendChild(columnMapping);
        }

        rootElement.appendChild(columnMappings);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);

        String absolutePath = path + File.separator + fileName
                + EventSimulatorConstant.DATA_SOURCE_CONFIGURATION_XML_PREFIX;

        StreamResult result = new StreamResult(new File(absolutePath));

        uploadXMLFile(axisConfiguration);

        transformer.transform(source, result);

        //addEventMappingDBConfiguration(fileName, streamId, separateChar);

    } catch (ParserConfigurationException e) {
        log.error(e);
    } catch (TransformerException e) {
        log.error(e);
    } catch (JSONException e) {
        log.error(e);
        e.printStackTrace();
    }

}

From source file:org.wso2.carbon.sample.tfl.traffic.TrafficPollingTask.java

public void run() {
    try {//w ww  . j a  va 2s.  co m
        URL obj = new URL(streamURL);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        ArrayList<Disruption> disruptionsList = new ArrayList<Disruption>();
        try {
            // optional default is GET
            con.setRequestMethod("GET");
            int responseCode = con.getResponseCode();
            log.info("Sending 'GET' request to URL : " + streamURL);
            log.info("Response Code : " + responseCode);

            double t = System.currentTimeMillis();
            // Get SAX Parser Factory
            SAXParserFactory factory = SAXParserFactory.newInstance();
            // Turn on validation, and turn off namespaces
            factory.setValidating(true);
            factory.setNamespaceAware(false);
            SAXParser parser = factory.newSAXParser();
            parser.parse(con.getInputStream(), new TrafficXMLHandler(disruptionsList));
            log.info("Number of Disruptions added to the list: " + disruptionsList.size());
            log.info("Time taken for parsing: " + (System.currentTimeMillis() - t));
        } catch (ParserConfigurationException e) {
            log.info("The underlying parser does not support " + " the requested features.");
        } catch (FactoryConfigurationError e) {
            log.info("Error occurred obtaining SAX Parser Factory.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            con.disconnect();
        }

        ArrayList<String> list = new ArrayList<String>();
        int count = 0;
        for (Disruption disruption : disruptionsList) {
            if (disruption.getState().contains("Active")) {
                list.add(disruption.toJson());
            }
            count++;
        }
        TflStream.writeToFile("tfl-traffic-data.out", list, true);
    } catch (IOException e) {
        log.error("Error occurred while getting traffic data: " + e.getMessage(), e);
    }

}

From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java

public static org.w3c.dom.Document ConvertStringToDocument(String Doc) {

    org.w3c.dom.Document document = null;

    try {/*from   w  w w .  j  av a 2 s  . c o m*/
        DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder DocBuild = Factory.newDocumentBuilder();

        StringBuffer Buffer = new StringBuffer(Doc);
        ByteArrayInputStream DocArray = new ByteArrayInputStream(Buffer.toString().getBytes("UTF-8"));
        document = DocBuild.parse(DocArray);

    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
        System.exit(0);
    } catch (org.xml.sax.SAXException se) {
        se.printStackTrace();
        System.exit(0);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(0);
    }
    return document;

}

From source file:org.yehongyu.fckeditor.connector.ConnectorServlet.java

/**
 * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br><br>
 * It execute the command and then return the results to the client in XML format.
 *
 *///from  w  ww  .ja va  2 s .c  o  m
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOGET ---");

    response.setContentType("text/xml; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + typeStr + currentFolderStr;
    //add by yehy Session
    UserSession us = CommonBean.getUserSession(request);
    if (us != null) {
        currentPath = baseDir + us.getUserName() + "/" + typeStr + currentFolderStr;
    }
    //end add
    String currentDirPath = getServletContext().getRealPath(currentPath);

    File currentDir = new File(currentDirPath);
    if (!currentDir.exists()) {
        currentDir.mkdir();
    }

    Document document = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.newDocument();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    }

    Node root = CreateCommonXml(document, commandStr, typeStr, currentFolderStr,
            request.getContextPath() + currentPath);

    if (debug)
        System.out.println("Command = " + commandStr);

    if (commandStr.equals("GetFolders")) {
        getFolders(currentDir, root, document);
    } else if (commandStr.equals("GetFoldersAndFiles")) {
        getFolders(currentDir, root, document);
        getFiles(currentDir, root, document);
    } else if (commandStr.equals("CreateFolder")) {
        String newFolderStr = request.getParameter("NewFolderName");

        File newFolder = new File(currentDir, newFolderStr);
        String retValue = "110";
        if (us == null) {
            retValue = "405"; //
        } else {
            if (newFolder.exists()) {
                retValue = "101";
            } else {
                try {
                    boolean dirCreated = newFolder.mkdir();
                    if (dirCreated)
                        retValue = "0";
                    else
                        retValue = "102";
                } catch (SecurityException sex) {
                    retValue = "103";
                }

            }
        }
        setCreateFolderResponse(retValue, root, document);
    }
    //add by yehy for delete
    else if (commandStr.equals("Delete")) {
        String retValue = "110";
        if (us == null) {
            retValue = "406"; //
        } else {
            String deleteName = request.getParameter("deleteName");
            String absname = this.getServletContext().getRealPath(baseDir + typeStr + deleteName);
            FileUtils.delDirAndFile(absname);
            retValue = "0";
        }
        setCreateFolderResponse(retValue, root, document);
    }
    //end add

    document.getDocumentElement().normalize();
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();

        DOMSource source = new DOMSource(document);

        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);

        if (debug) {
            StreamResult dbgResult = new StreamResult(System.out);
            transformer.transform(source, dbgResult);
            System.out.println("");
            System.out.println("--- END DOGET ---");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    out.flush();
    out.close();
}

From source file:perflab.LoadrunnerWrapper.java

/**
 * @param transactions - ArrayList of LoadRunnerTransaction objects
 * @param summaryFile  - location of xml summary file to be generated out of transaction objects in jUnit format
 * @return//ww  w.  ja v a 2s. c o  m
 */
private void generatejUnitReport(ArrayList<LoadRunnerTransaction> transactions, String summaryFile) {

    getLog().info("Transformation to jUnit XML started ...");

    String stringReport = "";

    try {
        /*
         * http://llg.cubic.org/docs/junit/
         <testsuite tests="3" time="42.5">
           <testcase classname="ZZZ_1" name="ZZZ_1" time="10.1"/>
           <testcase classname="ZZZ_2" name="ZZZ_2" time="11.7"/>
           <testcase classname="ZZZ_3" name="ZZZ_3" time="12.2">
            <!--failure type="NotEnoughFoo"> too slow </failure-->
           </testcase>
        </testsuite>
         */

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        org.w3c.dom.Document doc = (org.w3c.dom.Document) docBuilder.newDocument();
        org.w3c.dom.Element testsuiteElement = (org.w3c.dom.Element) doc.createElement("testsuite");
        testsuiteElement.setAttribute("tests", String.valueOf(transactions.size()));
        //testsuiteElement.setAttribute("time", "total test duration");
        doc.appendChild(testsuiteElement);

        ////////////////////////////////////////////////////////////////////////////

        for (LoadRunnerTransaction tr : this.transactions) {

            getLog().info("Dump " + tr.getName());

            org.w3c.dom.Element testcaseElement = doc.createElement("testcase");
            testcaseElement.setAttribute("classname", "load.ResponseTime");
            testcaseElement.setAttribute("name", tr.getName());
            testcaseElement.setAttribute("time", String.valueOf(tr.getAvgRT()));

            testsuiteElement.appendChild(testcaseElement);
        }

        ////////////////////////////////////////////////////////////////////////////
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        DOMSource source = new DOMSource(doc);

        File lr_report = new File(summaryFile);
        StreamResult result = new StreamResult(lr_report);

        transformer.transform(source, result);

        getLog().info("File saved in " + lr_report.getAbsolutePath());

    } catch (ParserConfigurationException pce) {
        getLog().error(pce.getMessage());
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        getLog().error(tfe.getMessage());
        tfe.printStackTrace();
    }
}

From source file:perflab.LoadrunnerWrapper.java

/**
 * @param transactions - ArrayList of LoadRunnerTransaction objects
 * @return//from w w w  .j av  a2 s. co m
 */
private void generatePerfPublisherReport(ArrayList<LoadRunnerTransaction> transactions, String xmlFile) {
    getLog().info("Transformation to XML started ...");
    try {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        org.w3c.dom.Document doc = (org.w3c.dom.Document) docBuilder.newDocument();
        org.w3c.dom.Element reportElement = (org.w3c.dom.Element) doc.createElement("report");
        doc.appendChild(reportElement);

        ////////////////////////////////////////////////////////////////////////////

        //<categories>
        //   <category name="memory" scale="mb">
        //       <observations>
        //           <observation name="Server 1">100</observation>
        //           <observation name="Server 2">200</observation>
        //       </observations>
        //   </category>

        //   <category name="disk" scale="gb">
        //       <observations>
        //           <observation name="Server 1">41</observation>
        //           <observation name="Server 2">58</observation>
        //       </observations>
        //   </category>
        //</categories>

        // start element
        org.w3c.dom.Element startElement = (org.w3c.dom.Element) doc.createElement("start");
        reportElement.appendChild(startElement);

        // date element
        org.w3c.dom.Element date = (org.w3c.dom.Element) doc.createElement("date");
        startElement.appendChild(date);

        date.setAttribute("format", "YYYYMMDD");
        date.setAttribute("val", "20100922");

        // time element
        org.w3c.dom.Element time = (org.w3c.dom.Element) doc.createElement("date");
        startElement.appendChild(time);

        time.setAttribute("format", "HHMMSS");
        time.setAttribute("val", "215935");

        ////////////////////////////////////////////////////////////////////////////

        //<test name="Smoke test" executed="yes" categ="Smoke test">

        //<description>Tests if ATE LAN socket and communication works.</description>

        //<result>
        //   <success passed="yes" state ="100" hasTimedOut="no" />
        //   <compiletime unit="s" mesure="0" isRelevant="yes" />
        //   <performance unit="%" mesure="0" isRelevant="yes" />
        //   <executiontime unit="s" mesure="12" isRelevant="yes" />
        //   <metrics>
        //      <006_My_Benefits unit="sec" mesure="0.115" isRelevant="yes"/>
        //      <007_My_Timesheet unit="sec" mesure="1.247" isRelevant="yes"/>
        //   </metrics>
        //</result>
        //</test>
        //</report>

        ////////////////////////////////////////////////////////////////////////////
        // test element
        org.w3c.dom.Element testElement = doc.createElement("test");
        reportElement.appendChild(testElement);

        testElement.setAttribute("name", "Smoke test");
        testElement.setAttribute("executed", "yes");
        testElement.setAttribute("categ", "Smoke test");

        // description element
        org.w3c.dom.Element descriptionElement = doc.createElement("description");
        descriptionElement.appendChild(doc.createTextNode("This is the best Load test ever executed..."));
        reportElement.appendChild(descriptionElement);

        ////////////////////////////////////////////////////////////////////////////
        // result
        org.w3c.dom.Element resultElement = doc.createElement("result");
        reportElement.appendChild(resultElement);

        org.w3c.dom.Element successElement = doc.createElement("success");
        resultElement.appendChild(successElement);

        org.w3c.dom.Element compiletimeElement = doc.createElement("compiletime");
        resultElement.appendChild(compiletimeElement);

        org.w3c.dom.Element performanceElement = doc.createElement("performance");
        resultElement.appendChild(performanceElement);

        org.w3c.dom.Element executiontimeElement = doc.createElement("executiontime");
        resultElement.appendChild(executiontimeElement);

        org.w3c.dom.Element metricsElement = doc.createElement("metrics");
        resultElement.appendChild(metricsElement);

        ////////////////////////////////////////////////////////////////////////////

        for (LoadRunnerTransaction tr : this.transactions) {
            //<006_My_Benefits unit="sec" mesure="0.115" isRelevant="yes"/>
            String trName = "tr_" + tr.getName();
            getLog().info("Dump " + trName);

            org.w3c.dom.Element trElement = doc.createElement(trName);
            trElement.setAttribute("unit", "sec");
            trElement.setAttribute("mesure", String.valueOf(tr.getAvgRT()));
            trElement.setAttribute("isRelevant", "yes");
            metricsElement.appendChild(trElement);
        }

        ////////////////////////////////////////////////////////////////////////////
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        DOMSource source = new DOMSource(doc);

        File lr_report = new File(xmlFile);
        StreamResult result = new StreamResult(lr_report);

        transformer.transform(source, result);

        getLog().info("File saved in " + lr_report.getAbsolutePath());

    } catch (ParserConfigurationException pce) {
        getLog().error(pce.getMessage());
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        getLog().error(tfe.getMessage());
        tfe.printStackTrace();
    }
}

From source file:perflab.loadrunnerwrapperjenkins.LoadRunnerWrapper.java

/**
 * @param transactions - ArrayList of LoadRunnerTransaction objects
 * @return/*  ww  w  .  j  a  v a 2s  . c  o  m*/
 */
private String generatejUnitReport(ArrayList<LoadRunnerTransaction> transactions) {
    String stringReport = "";
    logger.println("Transformation to jUnit XML started ...");
    try {
        /*
         * http://llg.cubic.org/docs/junit/
         *<testsuite tests="3" time="42.5"> 
         *    <testcase classname="ZZZ_1" name="ZZZ_1" time="10.1"/>
         *  <testcase classname="ZZZ_2" name="ZZZ_2" time="11.7"/>
         *  <testcase classname="ZZZ_3" name="ZZZ_3" time="12.2">
         *  <!--failure type="NotEnoughFoo"> too slow </failure-->
         *  </testcase> 
         *</testsuite>
         */

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        org.w3c.dom.Document doc = (org.w3c.dom.Document) docBuilder.newDocument();
        org.w3c.dom.Element testsuiteElement = (org.w3c.dom.Element) doc.createElement("testsuite");
        testsuiteElement.setAttribute("tests", String.valueOf(transactions.size()));
        // testsuiteElement.setAttribute("time", "total test duration");
        doc.appendChild(testsuiteElement);

        // //////////////////////////////////////////////////////////////////////////

        for (LoadRunnerTransaction tr : this.transactions) {

            logger.println("Dump " + tr.getName());

            org.w3c.dom.Element testcaseElement = doc.createElement("testcase");
            //testcaseElement.setAttribute("classname", tr.getName());
            testcaseElement.setAttribute("classname",
                    "load." + new File(this.loadRunnerScenario).getName().replace(".lrs", ""));
            testcaseElement.setAttribute("name", tr.getName());
            testcaseElement.setAttribute("time", String.valueOf(tr.getAvgRT()));

            testsuiteElement.appendChild(testcaseElement);
        }

        // //////////////////////////////////////////////////////////////////////////
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        stringReport = this.getStringFromDoc(doc);

    } catch (ParserConfigurationException pce) {
        logger.println(pce.getMessage());
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        logger.println(tfe.getMessage());
        tfe.printStackTrace();
    }
    return stringReport;
}

From source file:perflab.loadrunnerwrapperjenkins.LoadRunnerWrapper.java

/**
 * @param transactions - ArrayList of LoadRunnerTransaction objects
 * //@param summaryFile  - location of SCV summary file to be generated out of
 *                     transaction objects in PerfPublisher Report format
 * @return/*from  w w  w  .j  av a 2  s  .  c  o m*/
 */
private String generatePerfPublisherReport(ArrayList<LoadRunnerTransaction> transactions) {

    logger.println("Transformation to XML started ...");
    String stringReport = "";
    try {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        org.w3c.dom.Document doc = (org.w3c.dom.Document) docBuilder.newDocument();
        org.w3c.dom.Element reportElement = (org.w3c.dom.Element) doc.createElement("report");
        doc.appendChild(reportElement);

        // //////////////////////////////////////////////////////////////////////////

        // <categories>
        // <category name="memory" scale="mb">
        // <observations>
        // <observation name="Server 1">100</observation>
        // <observation name="Server 2">200</observation>
        // </observations>
        // </category>

        // <category name="disk" scale="gb">
        // <observations>
        // <observation name="Server 1">41</observation>
        // <observation name="Server 2">58</observation>
        // </observations>
        // </category>
        // </categories>

        // start element
        org.w3c.dom.Element startElement = (org.w3c.dom.Element) doc.createElement("start");
        reportElement.appendChild(startElement);

        // date element
        org.w3c.dom.Element date = (org.w3c.dom.Element) doc.createElement("date");
        startElement.appendChild(date);

        date.setAttribute("format", "YYYYMMDD");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMdd");
        date.setAttribute("val", sdf.format(startTime));

        // time element
        org.w3c.dom.Element time = (org.w3c.dom.Element) doc.createElement("date");
        startElement.appendChild(time);

        time.setAttribute("format", "HHMMSS");
        SimpleDateFormat stf = new SimpleDateFormat("hhmmss");
        time.setAttribute("val", stf.format(startTime));

        // //////////////////////////////////////////////////////////////////////////

        // <test name="Smoke test" executed="yes" categ="Smoke test">

        // <description>Tests if ATE LAN socket and communication
        // works.</description>

        // <result>
        // <success passed="yes" state ="100" hasTimedOut="no" />
        // <compiletime unit="s" mesure="0" isRelevant="yes" />
        // <performance unit="%" mesure="0" isRelevant="yes" />
        // <executiontime unit="s" mesure="12" isRelevant="yes" />
        // <metrics>
        // <006_My_Benefits unit="sec" mesure="0.115" isRelevant="yes"/>
        // <007_My_Timesheet unit="sec" mesure="1.247" isRelevant="yes"/>
        // </metrics>
        // </result>
        // </test>
        // </report>

        // //////////////////////////////////////////////////////////////////////////
        // test element
        org.w3c.dom.Element testElement = doc.createElement("test");
        reportElement.appendChild(testElement);

        testElement.setAttribute("name", "Load test");
        testElement.setAttribute("executed", "yes");
        testElement.setAttribute("categ", "Load test");

        // description element
        org.w3c.dom.Element descriptionElement = doc.createElement("description");
        descriptionElement.appendChild(doc.createTextNode("This is the best Load test ever executed..."));
        reportElement.appendChild(descriptionElement);

        // //////////////////////////////////////////////////////////////////////////
        // result
        org.w3c.dom.Element resultElement = doc.createElement("result");
        reportElement.appendChild(resultElement);

        org.w3c.dom.Element successElement = doc.createElement("success");
        resultElement.appendChild(successElement);

        org.w3c.dom.Element compiletimeElement = doc.createElement("compiletime");
        resultElement.appendChild(compiletimeElement);

        org.w3c.dom.Element performanceElement = doc.createElement("performance");
        resultElement.appendChild(performanceElement);

        org.w3c.dom.Element executiontimeElement = doc.createElement("executiontime");
        resultElement.appendChild(executiontimeElement);

        org.w3c.dom.Element metricsElement = doc.createElement("metrics");
        resultElement.appendChild(metricsElement);

        // //////////////////////////////////////////////////////////////////////////

        for (LoadRunnerTransaction tr : this.transactions) {
            // <006_My_Benefits unit="sec" mesure="0.115" isRelevant="yes"/>
            String trName = "tr_" + tr.getName();
            logger.println("Dump " + trName);

            org.w3c.dom.Element trElement = doc.createElement(trName);
            trElement.setAttribute("unit", "sec");
            trElement.setAttribute("mesure", String.valueOf(tr.getAvgRT()));
            trElement.setAttribute("isRelevant", "yes");
            metricsElement.appendChild(trElement);
        }

        // //////////////////////////////////////////////////////////////////////////
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        stringReport = this.getStringFromDoc(doc);

    } catch (ParserConfigurationException pce) {
        logger.println(pce.getMessage());
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        logger.println(tfe.getMessage());
        tfe.printStackTrace();
    }
    return stringReport;
}