Example usage for org.dom4j.dom DOMDocument DOMDocument

List of usage examples for org.dom4j.dom DOMDocument DOMDocument

Introduction

In this page you can find the example usage for org.dom4j.dom DOMDocument DOMDocument.

Prototype

public DOMDocument() 

Source Link

Usage

From source file:com.devoteam.srit.xmlloader.genscript.genscriptCmd.java

License:Open Source License

/**
 * @param args the command line arguments
 *//*  w  w  w .  j  a v  a 2 s  .com*/
public static void main(String[] args) {

    // Initialisation de MTS core
    ExceptionHandlerSingleton.setInstance(new TextExceptionHandler());
    SingletonFSInterface.setInstance(new LocalFSInterface());
    TextListenerProviderRegistry.instance().register(new FileTextListenerProvider());
    // set the storage location to FILE for logging
    PropertiesEnhanced properties = new PropertiesEnhanced();
    properties.addPropertiesEnhancedComplete("logs.STORAGE_LOCATION", "FILE");
    Config.overrideProperties("tester.properties", properties);

    // S'il n'y a pas d'arguments, on affiche la syntaxe  utiliser
    if (args.length < 3) {
        System.out.println("ERROR => At least two arguments are required : filtre and capture file");
        System.out.println("Usage : genscript <protocol>:<host>:<port> <capturefile> <generatedfile>");
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE,
                "ERROR => At least two arguments are required : filtre and capture file");
        System.exit(-1);
    }
    // Si le nombre d'argument est bon, on lance la convertion
    System.out.println("-------- GENSCRIPT -------------------------------------------------------");
    System.out.println("START => capture file: " + args[args.length - 2]);
    GlobalLogger.instance().getApplicationLogger().info(TextEvent.Topic.CORE,
            "START => capture file: " + args[args.length - 2]);

    List<FiltreGenerator> listeFiltre = new ArrayList<FiltreGenerator>();
    List<Probe> listeProbe = new ArrayList<Probe>();

    String src = "";
    URI srcURI = null;
    String out = "";
    URI outURI = null;
    String nomPcap = "";

    // Pour chaque lment pass en paramtre
    for (int i = 0; i < args.length; i++) {

        // Si l'argument est un filtre
        if (args[i].matches("[a-zA-Z0-9]+:[a-zA-Z0-9.]+:[0-9]+")) {
            String[] filtre = args[i].split(":");
            listeFiltre.add(new FiltreGenerator(filtre[0], filtre[1], Integer.parseInt(filtre[2])));
        }
    }

    // Cration des URI  partir des paramtres
    // URI du fichier pcap source
    src = args[args.length - 2];
    srcURI = new File(src).toURI();

    // URI du fichier de test  gnrer
    out = args[args.length - 1];
    outURI = new File(out).toURI();

    // On rcupre le nom du fichier pcap
    String[] nomPcapPath = args[args.length - 2].split("/");
    nomPcap = nomPcapPath[nomPcapPath.length - 1].replaceAll("[.]([0-9A-Za-z])+", "");

    // Creation du generateur de script
    ScriptGenerator generator = new ScriptGenerator(outURI);
    generator.setTestcaseName(nomPcap);

    try {
        // Chaque filtre est enregistr dans le gnrateur de script de test
        for (FiltreGenerator fg : listeFiltre) {
            generator.addFiltre(fg);
        }

        // Generation des fichiers de test
        //generator.generateTestFile();
        generator.generateTest();

        // Pour chaque filtre on crer l'objet Probe
        for (FiltreGenerator fg : listeFiltre) {
            System.out.println("CAPTURE filter: => " + fg);
            GlobalLogger.instance().getApplicationLogger().info(TextEvent.Topic.CORE,
                    "CAPTURE filter: => " + fg);
            // Cration de la stack du protocole que l'on souhaite filtrer
            Stack stack = StackFactory.getStack(fg.getProtocole());
            DOMDocument docProbe = new DOMDocument();
            Element root = docProbe.addElement("root");
            root.addAttribute("filename", src);
            // String captureFilter = "host " + fg.getHostName() + " and port " + fg.getHostPort().toString();
            String captureFilter = "host " + fg.getHostName() + " and (port " + fg.getHostPort().toString()
                    + " or not (ip[6:2] & 0x1FFF = 0)) and ip";
            root.addAttribute("captureFilter", captureFilter);

            // Cration de l'objet Probe
            Probe probe = new Probe(stack, root);
            listeProbe.add(probe);

            // On configure le probe pour la gnration de script
            probe.genScript(generator);

            stack.createProbe(probe, fg.getProtocole());
        }

        // Attente de la fin de la capture  partir du fichier
        while (!listeProbe.get(0).getProbeJpcapThread().getStopPossible()) {
        }

        generator.closeTest();

        System.out.println("END => test file: " + args[args.length - 1] + "(See application.log)");
        GlobalLogger.instance().getApplicationLogger().info(TextEvent.Topic.CORE,
                "END => test file: " + args[args.length - 1] + "(See application.log)");

        // On ferme proprement le programme                                      
        System.exit(0);
    } catch (Exception e) {
        System.out.println("EXCEPTION => " + e);
        e.printStackTrace();
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE, e, "EXCEPTION => ");
        System.exit(-10);
    }
}

From source file:com.jboss.transaction.txinterop.test.XMLResultsServlet.java

License:LGPL

public void doStatus(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");

    HttpSession session = request.getSession();
    final FullTestResult testResult = (FullTestResult) session
            .getAttribute(TestConstants.ATTRIBUTE_TEST_RESULT);

    DOMDocument report = new DOMDocument();
    DOMElement testsuite = new DOMElement("testsuite");
    report.setRootElement(testsuite);//w  ww .  j a va 2s. co m

    if (testResult == null) {
        // No JUnit test results generated.
    } else {
        List passedTests = testResult.getPassedTests();
        List failedTests = testResult.getFailedTests();
        List errorTests = testResult.getErrorTests();

        final int runCount = testResult.runCount();
        final int errorCount = testResult.errorCount();
        final int failureCount = testResult.failureCount();

        testsuite.addAttribute("name", "com.jboss.transaction.txinterop.interop.InteropTestSuite");
        testsuite.addAttribute("errors", Integer.toString(errorCount));
        testsuite.addAttribute("failures", Integer.toString(failureCount));
        testsuite.addAttribute("hostname", request.getServerName());
        testsuite.addAttribute("tests", Integer.toString(runCount));
        testsuite.addAttribute("timestamp", new Date().toString());

        DOMElement properties = new DOMElement("properties");
        testsuite.add(properties);
        DOMElement status = newPropertyDOMElement("status");
        properties.add(status);
        status.addAttribute("value", "finished");

        long totalDuration = 0;

        if (!passedTests.isEmpty()) {
            Iterator passedTestsIterator = passedTests.iterator();
            while (passedTestsIterator.hasNext()) {
                FullTestResult.PassedTest passedTest = (FullTestResult.PassedTest) passedTestsIterator.next();
                totalDuration += passedTest.duration;

                final String name = passedTest.test.toString();
                final String description = (String) TestConstants.DESCRIPTIONS.get(name);

                testsuite.add(newTestcase(passedTest.test.getClass().getName(), name + ": " + description,
                        passedTest.duration));
            }
        }

        if (!failedTests.isEmpty()) {
            Iterator failedTestsIterator = failedTests.iterator();
            while (failedTestsIterator.hasNext()) {
                FullTestResult.FailedTest failedTest = (FullTestResult.FailedTest) failedTestsIterator.next();
                totalDuration += failedTest.duration;

                final String name = failedTest.test.toString();
                final String description = (String) TestConstants.DESCRIPTIONS.get(name);
                CharArrayWriter charArrayWriter = new CharArrayWriter();
                PrintWriter printWriter = new PrintWriter(charArrayWriter, true);
                failedTest.assertionFailedError.printStackTrace(printWriter);
                printWriter.close();
                charArrayWriter.close();

                testsuite.add(newFailedTestcase(failedTest.test.getClass().getName(), name + ": " + description,
                        failedTest.duration, failedTest.assertionFailedError.getMessage(),
                        charArrayWriter.toString()));
            }
        }

        if (!errorTests.isEmpty()) {
            Iterator errorTestsIterator = errorTests.iterator();
            while (errorTestsIterator.hasNext()) {
                FullTestResult.ErrorTest errorTest = (FullTestResult.ErrorTest) errorTestsIterator.next();
                totalDuration += errorTest.duration;

                final String name = errorTest.test.toString();
                final String description = (String) TestConstants.DESCRIPTIONS.get(name);
                CharArrayWriter charArrayWriter = new CharArrayWriter();
                PrintWriter printWriter = new PrintWriter(charArrayWriter, true);
                errorTest.throwable.printStackTrace(printWriter);
                printWriter.close();
                charArrayWriter.close();

                System.out.println("charArrayWriter.toString()=" + charArrayWriter.toString());
                testsuite.add(newErrorTestcase(errorTest.test.getClass().getName(), name + ": " + description,
                        errorTest.duration, errorTest.throwable.getMessage(), charArrayWriter.toString()));
            }
        }

        // total time of all tests
        testsuite.addAttribute("time", Float.toString(totalDuration / 1000f));
    }

    String logContent = null;
    final String logName = (String) session.getAttribute(TestConstants.ATTRIBUTE_LOG_NAME);
    if (logName != null) {
        try {
            logContent = TestLogController.readLog(logName);
        } catch (final Throwable th) {
            log("Error reading log file", th);
        }
    }

    testsuite.add(new DOMElement("system-out").addCDATA((logContent != null) ? logContent : ""));
    testsuite.add(new DOMElement("system-err").addCDATA(""));

    XMLWriter outputter = new XMLWriter(response.getWriter(), OutputFormat.createPrettyPrint());
    try {
        outputter.write(testsuite);
        outputter.close();
    } catch (IOException e) {
        throw new ServletException(e);
    }
}

From source file:com.jboss.transaction.wstf.test.XMLResultsServlet.java

License:LGPL

public void doStatus(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");

    HttpSession session = request.getSession();
    final FullTestResult testResult = (FullTestResult) session
            .getAttribute(TestConstants.ATTRIBUTE_TEST_RESULT);

    DOMDocument report = new DOMDocument();
    DOMElement testsuite = new DOMElement("testsuite");
    report.setRootElement(testsuite);/*from  w  w w.  ja  v  a 2  s .c o  m*/

    if (testResult == null) {
        // No JUnit test results generated.
    } else {
        List passedTests = testResult.getPassedTests();
        List failedTests = testResult.getFailedTests();
        List errorTests = testResult.getErrorTests();

        final int runCount = testResult.runCount();
        final int errorCount = testResult.errorCount();
        final int failureCount = testResult.failureCount();

        testsuite.addAttribute("name", "com.jboss.transaction.wstf.interop.InteropTestSuite");
        testsuite.addAttribute("errors", Integer.toString(errorCount));
        testsuite.addAttribute("failures", Integer.toString(failureCount));
        testsuite.addAttribute("hostname", request.getServerName());
        testsuite.addAttribute("tests", Integer.toString(runCount));
        testsuite.addAttribute("timestamp", new Date().toString());

        DOMElement properties = new DOMElement("properties");
        testsuite.add(properties);
        DOMElement status = newPropertyDOMElement("status");
        properties.add(status);
        status.addAttribute("value", "finished");

        long totalDuration = 0;

        if (!passedTests.isEmpty()) {
            Iterator passedTestsIterator = passedTests.iterator();
            while (passedTestsIterator.hasNext()) {
                FullTestResult.PassedTest passedTest = (FullTestResult.PassedTest) passedTestsIterator.next();
                totalDuration += passedTest.duration;

                final String name = passedTest.test.toString();
                final String description = (String) TestConstants.DESCRIPTIONS.get(name);

                testsuite.add(newTestcase(passedTest.test.getClass().getName(), name + ": " + description,
                        passedTest.duration));
            }
        }

        if (!failedTests.isEmpty()) {
            Iterator failedTestsIterator = failedTests.iterator();
            while (failedTestsIterator.hasNext()) {
                FullTestResult.FailedTest failedTest = (FullTestResult.FailedTest) failedTestsIterator.next();
                totalDuration += failedTest.duration;

                final String name = failedTest.test.toString();
                final String description = (String) TestConstants.DESCRIPTIONS.get(name);
                CharArrayWriter charArrayWriter = new CharArrayWriter();
                PrintWriter printWriter = new PrintWriter(charArrayWriter, true);
                failedTest.assertionFailedError.printStackTrace(printWriter);
                printWriter.close();
                charArrayWriter.close();

                testsuite.add(newFailedTestcase(failedTest.test.getClass().getName(), name + ": " + description,
                        failedTest.duration, failedTest.assertionFailedError.getMessage(),
                        charArrayWriter.toString()));
            }
        }

        if (!errorTests.isEmpty()) {
            Iterator errorTestsIterator = errorTests.iterator();
            while (errorTestsIterator.hasNext()) {
                FullTestResult.ErrorTest errorTest = (FullTestResult.ErrorTest) errorTestsIterator.next();
                totalDuration += errorTest.duration;

                final String name = errorTest.test.toString();
                final String description = (String) TestConstants.DESCRIPTIONS.get(name);
                CharArrayWriter charArrayWriter = new CharArrayWriter();
                PrintWriter printWriter = new PrintWriter(charArrayWriter, true);
                errorTest.throwable.printStackTrace(printWriter);
                printWriter.close();
                charArrayWriter.close();

                System.out.println("charArrayWriter.toString()=" + charArrayWriter.toString());
                testsuite.add(newErrorTestcase(errorTest.test.getClass().getName(), name + ": " + description,
                        errorTest.duration, errorTest.throwable.getMessage(), charArrayWriter.toString()));
            }
        }

        // total time of all tests
        testsuite.addAttribute("time", Float.toString(totalDuration / 1000f));
    }

    String logContent = null;
    final String logName = (String) session.getAttribute(TestConstants.ATTRIBUTE_LOG_NAME);
    if (logName != null) {
        try {
            logContent = TestLogController.readLog(logName);
        } catch (final Throwable th) {
            log("Error reading log file", th);
        }
    }

    testsuite.add(new DOMElement("system-out").addCDATA((logContent != null) ? logContent : ""));
    testsuite.add(new DOMElement("system-err").addCDATA(""));

    XMLWriter outputter = new XMLWriter(response.getWriter(), OutputFormat.createPrettyPrint());
    try {
        outputter.write(testsuite);
        outputter.close();
    } catch (IOException e) {
        throw new ServletException(e);
    }
}

From source file:com.thoughtworks.go.server.domain.xml.UsersXmlViewModel.java

License:Apache License

public Document toXml(XmlWriterContext writerContext) throws DocumentException, IOException {
    Document document = new DOMDocument();
    document.add(rootUsersNodeWithChildNodesFor(users));
    return document;
}

From source file:com.xpn.xwiki.doc.XWikiAttachment.java

License:Open Source License

/**
 * Retrieve an attachment as an XML string. You should prefer
 * {@link #toXML(com.xpn.xwiki.internal.xml.XMLWriter, boolean, boolean, com.xpn.xwiki.XWikiContext)
 * to avoid memory loads when appropriate.
 *
 * @param bWithAttachmentContent if true, binary content of the attachment is included (base64 encoded)
 * @param bWithVersions if true, all archived versions are also included
 * @param context current XWikiContext//  ww w. ja va2  s . c  om
 * @return a string containing an XML representation of the attachment
 * @throws XWikiException when an error occurs during wiki operations
 */
public String toStringXML(boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context)
        throws XWikiException {
    // This is very bad. baos holds the entire attachment on the heap, then it makes a copy when toByteArray
    // is called, then String forces us to make a copy when we construct a new String.
    // Unfortunately this can't be fixed because jrcs demands the content as a String.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        XMLWriter wr = new XMLWriter(baos, new OutputFormat("", true, context.getWiki().getEncoding()));
        Document doc = new DOMDocument();
        wr.writeDocumentStart(doc);
        toXML(wr, bWithAttachmentContent, bWithVersions, context);
        wr.writeDocumentEnd(doc);
        byte[] array = baos.toByteArray();
        baos = null;
        return new String(array, context.getWiki().getEncoding());
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}

From source file:com.xpn.xwiki.doc.XWikiAttachment.java

License:Open Source License

/**
 * Retrieve XML representation of attachment's metadata into an {@link Element}. You should prefer
 * {@link #toXML(com.xpn.xwiki.internal.xml.XMLWriter, boolean, boolean, com.xpn.xwiki.XWikiContext)
 * to avoid memory loads when appropriate.
 *
 * @param bWithAttachmentContent if true, binary content of the attachment is included (base64 encoded)
 * @param bWithVersions if true, all archived versions are also included
 * @param context current XWikiContext/*  w w w .j  a v  a2  s .  c om*/
 * @return an {@link Element} containing an XML representation of the attachment
 * @throws XWikiException when an error occurs during wiki operations
 * @since 2.3M2
 */
public Element toXML(boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context)
        throws XWikiException {
    Document doc = new DOMDocument();
    DOMXMLWriter wr = new DOMXMLWriter(doc, new OutputFormat("", true, context.getWiki().getEncoding()));

    try {
        toXML(wr, bWithAttachmentContent, bWithVersions, context);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return doc.getRootElement();
}

From source file:com.xpn.xwiki.doc.XWikiDocument.java

License:Open Source License

/**
 * Serialize the document to an XML {@link DOMDocument}. You should prefer
 * {@link #toXML(OutputStream, boolean, boolean, boolean, boolean, XWikiContext)} or
 * {@link #toXML(com.xpn.xwiki.internal.xml.XMLWriter, boolean, boolean, boolean, boolean, XWikiContext)} when
 * possible to reduce memory load./*from   www  .  j  a v a2 s . c o  m*/
 * 
 * @param bWithObjects include XObjects
 * @param bWithRendering include the rendered content
 * @param bWithAttachmentContent include attachments content
 * @param bWithVersions include archived versions
 * @param context current XWikiContext
 * @return a {@link DOMDocument} containing the serialized document.
 * @throws XWikiException when an errors occurs during wiki operations
 */
public Document toXMLDocument(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent,
        boolean bWithVersions, XWikiContext context) throws XWikiException {
    Document doc = new DOMDocument();
    DOMXMLWriter wr = new DOMXMLWriter(doc, new OutputFormat("", true, context.getWiki().getEncoding()));

    try {
        toXML(wr, bWithObjects, bWithRendering, bWithAttachmentContent, bWithVersions, context);
        return doc;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.xpn.xwiki.doc.XWikiDocument.java

License:Open Source License

/**
 * Serialize the document to an OutputStream.
 * //from w w w .  j  a  v a2  s. c  om
 * @param bWithObjects include XObjects
 * @param bWithRendering include the rendered content
 * @param bWithAttachmentContent include attachments content
 * @param bWithVersions include archived versions
 * @param context current XWikiContext
 * @throws XWikiException when an errors occurs during wiki operations
 * @throws IOException when an errors occurs during streaming operations
 * @since 2.3M2
 */
public void toXML(OutputStream out, boolean bWithObjects, boolean bWithRendering,
        boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context)
        throws XWikiException, IOException {
    XMLWriter wr = new XMLWriter(out, new OutputFormat("", true, context.getWiki().getEncoding()));

    Document doc = new DOMDocument();
    wr.writeDocumentStart(doc);
    toXML(wr, bWithObjects, bWithRendering, bWithAttachmentContent, bWithVersions, context);
    wr.writeDocumentEnd(doc);
}

From source file:com.xpn.xwiki.objects.BaseCollection.java

License:Open Source License

public String toXMLString() {
    Document doc = new DOMDocument();
    doc.setRootElement(toXML(null));//ww  w.  j  a v  a2  s .  c o  m
    OutputFormat outputFormat = new OutputFormat("", true);
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, outputFormat);
    try {
        writer.write(doc);
        return out.toString();
    } catch (IOException e) {
        e.printStackTrace();

        return "";
    }
}

From source file:com.xpn.xwiki.objects.BaseProperty.java

License:Open Source License

public String toXMLString() {
    Document doc = new DOMDocument();
    doc.setRootElement(toXML());/*from w w w .  j a v a  2  s.  c  o m*/
    OutputFormat outputFormat = new OutputFormat("", true);
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, outputFormat);
    try {
        writer.write(doc);

        return out.toString();
    } catch (IOException e) {
        e.printStackTrace();

        return "";
    }
}