Example usage for org.dom4j.io XMLWriter close

List of usage examples for org.dom4j.io XMLWriter close

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes the underlying Writer

Usage

From source file:org.apache.isis.core.runtime.services.memento.Dom4jUtil.java

License:Apache License

static String asString(final Document doc) {
    XMLWriter writer = null;
    final StringWriter sw = new StringWriter();
    try {//w w  w  .  j a v a2s  . c  om
        // previously this code used pretty print.
        // however, that tripped up on strings with double spaces in them; the double space was normalized 
        // to a single space!
        // OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        // writer = new XMLWriter(sw, outputFormat);
        writer = new XMLWriter(sw);
        writer.write(doc);
        return sw.toString();
    } catch (IOException e) {
        throw new IsisException(e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:org.apache.isis.core.runtime.services.viewmodelsupport.Dom4jUtil.java

License:Apache License

static String asString(final Document doc) {
    XMLWriter writer = null;
    final StringWriter sw = new StringWriter();
    try {/*w  w  w . ja  va 2 s .  c  o  m*/
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        writer = new XMLWriter(sw, outputFormat);
        writer.write(doc);
        return sw.toString();
    } catch (IOException e) {
        throw new IsisException(e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:org.apache.maven.plugin.idea.AbstractIdeaMojo.java

License:Apache License

protected void writeXmlDocument(File file, Document document) throws IOException {
    XMLWriter writer = new IdeaXmlWriter(file);
    writer.write(document);//from   ww  w  . j  a  va 2 s  . com
    writer.close();
}

From source file:org.apache.openmeetings.core.documents.CreateLibraryPresentation.java

License:Apache License

public static ConverterProcessResult generateXMLDocument(File targetDirectory, String originalDocument,
        String pdfDocument, String swfDocument) {
    ConverterProcessResult returnMap = new ConverterProcessResult();
    returnMap.setProcess("generateXMLDocument");
    try {//ww w .  ja  v  a2 s.  c o m
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("presentation");

        File file = new File(targetDirectory, originalDocument);
        root.addElement("originalDocument").addAttribute("lastmod", (new Long(file.lastModified())).toString())
                .addAttribute("size", (new Long(file.length())).toString()).addText(originalDocument);

        if (pdfDocument != null) {
            File pdfDocumentFile = new File(targetDirectory, pdfDocument);
            root.addElement("pdfDocument")
                    .addAttribute("lastmod", (new Long(pdfDocumentFile.lastModified())).toString())
                    .addAttribute("size", (new Long(pdfDocumentFile.length())).toString()).addText(pdfDocument);
        }

        if (swfDocument != null) {
            File swfDocumentFile = new File(targetDirectory, originalDocument);
            root.addElement("swfDocument")
                    .addAttribute("lastmod", (new Long(swfDocumentFile.lastModified())).toString())
                    .addAttribute("size", (new Long(swfDocumentFile.length())).toString()).addText(swfDocument);
        }

        Element thumbs = root.addElement("thumbs");

        //Second get all Files of this Folder
        FilenameFilter ff = new FilenameFilter() {
            @Override
            public boolean accept(File b, String name) {
                File f = new File(b, name);
                return f.isFile();
            }
        };

        String[] allfiles = targetDirectory.list(ff);
        if (allfiles != null) {
            Arrays.sort(allfiles);
            for (int i = 0; i < allfiles.length; i++) {
                File thumbfile = new File(targetDirectory, allfiles[i]);
                if (allfiles[i].startsWith(thumbImagePrefix)) {
                    thumbs.addElement("thumb")
                            .addAttribute("lastmod", (new Long(thumbfile.lastModified())).toString())
                            .addAttribute("size", (new Long(thumbfile.length())).toString())
                            .addText(allfiles[i]);
                }
            }
        }

        // lets write to a file
        XMLWriter writer = new XMLWriter(
                new FileOutputStream(new File(targetDirectory, OmFileHelper.libraryFileName)));
        writer.write(document);
        writer.close();

        returnMap.setExitValue("0");

        return returnMap;
    } catch (Exception err) {
        log.error("Error while generateXMLDocument", err);
        returnMap.setError(err.getMessage());
        returnMap.setExitValue("-1");
        return returnMap;
    }
}

From source file:org.apache.openmeetings.documents.CreateLibraryPresentation.java

License:Apache License

public static ConverterProcessResult generateXMLDocument(File targetDirectory, String originalDocument,
        String pdfDocument, String swfDocument) {
    ConverterProcessResult returnMap = new ConverterProcessResult();
    returnMap.setProcess("generateXMLDocument");
    try {//w  w  w. j  ava  2 s. c  o m

        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("presentation");

        File file = new File(targetDirectory, originalDocument);
        root.addElement("originalDocument").addAttribute("lastmod", (new Long(file.lastModified())).toString())
                .addAttribute("size", (new Long(file.length())).toString()).addText(originalDocument);

        if (pdfDocument != null) {
            File pdfDocumentFile = new File(targetDirectory, pdfDocument);
            root.addElement("pdfDocument")
                    .addAttribute("lastmod", (new Long(pdfDocumentFile.lastModified())).toString())
                    .addAttribute("size", (new Long(pdfDocumentFile.length())).toString()).addText(pdfDocument);
        }

        if (swfDocument != null) {
            File swfDocumentFile = new File(targetDirectory, originalDocument);
            root.addElement("swfDocument")
                    .addAttribute("lastmod", (new Long(swfDocumentFile.lastModified())).toString())
                    .addAttribute("size", (new Long(swfDocumentFile.length())).toString()).addText(swfDocument);
        }

        Element thumbs = root.addElement("thumbs");

        //Secoond get all Files of this Folder
        FilenameFilter ff = new FilenameFilter() {
            public boolean accept(File b, String name) {
                File f = new File(b, name);
                return f.isFile();
            }
        };

        String[] allfiles = targetDirectory.list(ff);
        if (allfiles != null) {
            Arrays.sort(allfiles);
            for (int i = 0; i < allfiles.length; i++) {
                File thumbfile = new File(targetDirectory, allfiles[i]);
                if (allfiles[i].startsWith("_thumb_")) {
                    thumbs.addElement("thumb")
                            .addAttribute("lastmod", (new Long(thumbfile.lastModified())).toString())
                            .addAttribute("size", (new Long(thumbfile.length())).toString())
                            .addText(allfiles[i]);
                }
            }
        }

        // lets write to a file
        XMLWriter writer = new XMLWriter(
                new FileOutputStream(new File(targetDirectory, OmFileHelper.libraryFileName)));
        writer.write(document);
        writer.close();

        returnMap.setExitValue("0");

        return returnMap;
    } catch (Exception err) {
        err.printStackTrace();
        returnMap.setError(err.getMessage());
        returnMap.setExitValue("-1");
        return returnMap;
    }
}

From source file:org.apache.openmeetings.documents.InstallationDocumentHandler.java

License:Apache License

public static void createDocument(Integer stepNo) throws Exception {

    Document document = DocumentHelper.createDocument();

    Element root = document.addElement("install");
    Element step = root.addElement("step");

    step.addElement("stepnumber").addText(stepNo.toString());
    step.addElement("stepname").addText("Step " + stepNo);

    XMLWriter writer = new XMLWriter(new FileWriter(OmFileHelper.getInstallFile()));
    writer.write(document);//from   www  . j  a v  a2  s  .c om
    writer.close();

}

From source file:org.apache.openmeetings.installation.InstallationDocumentHandler.java

License:Apache License

public static void createDocument(int stepNo) throws Exception {
    Document document = DocumentHelper.createDocument();

    Element root = document.addElement("install");
    Element step = root.addElement("step");

    step.addElement("stepnumber").addText("" + stepNo);
    step.addElement("stepname").addText("Step " + stepNo);

    try (OutputStream os = new FileOutputStream(OmFileHelper.getInstallFile())) {
        XMLWriter writer = new XMLWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
        writer.write(document);//from  w w  w.  ja v a 2s  .  c  o m
        writer.close();
    }
}

From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java

License:Apache License

private org.dom4j.Element getExportLayoutDom(IPerson person, IUserProfile profile) {
    if (!this.layoutExistsForUser(person)) {
        return null;
    }/*from   w  w  w  .  ja  v a2s . co m*/

    org.dom4j.Document layoutDoc = null;
    try {
        final Document layoutDom = this._safeGetUserLayout(person, profile);
        person.setAttribute(Constants.PLF, layoutDom);
        layoutDoc = this.reader.get().read(layoutDom);
    } catch (final Throwable t) {
        final String msg = "Unable to obtain layout & profile for user '" + person.getUserName()
                + "', profileId " + profile.getProfileId();
        throw new RuntimeException(msg, t);
    }

    if (logger.isDebugEnabled()) {
        // Write out this version of the layout to the log for dev purposes...
        final StringWriter str = new StringWriter();
        final XMLWriter xml = new XMLWriter(str, new OutputFormat("  ", true));
        try {
            xml.write(layoutDoc);
            xml.close();
        } catch (final Throwable t) {
            throw new RuntimeException(
                    "Failed to write the layout for user '" + person.getUserName() + "' to the DEBUG log", t);
        }
        logger.debug("Layout for user: {}\n{}", person.getUserName(), str.getBuffer().toString());
    }

    /*
     * Attempt to detect a corrupted layout; return null in such cases
     */

    if (isLayoutCorrupt(layoutDoc)) {
        logger.warn("Layout for user: {} is corrupt; layout structures will not be exported.",
                person.getUserName());
        return null;
    }

    /*
     * Clean up the DOM for export.
     */

    // (1) Add structure & theme attributes...
    final int structureStylesheetId = profile.getStructureStylesheetId();
    this.addStylesheetUserPreferencesAttributes(person, profile, layoutDoc, structureStylesheetId, "structure");

    final int themeStylesheetId = profile.getThemeStylesheetId();
    this.addStylesheetUserPreferencesAttributes(person, profile, layoutDoc, themeStylesheetId, "theme");

    // (2) Remove locale info...
    final Iterator<org.dom4j.Attribute> locale = (Iterator<org.dom4j.Attribute>) layoutDoc
            .selectNodes("//@locale").iterator();
    while (locale.hasNext()) {
        final org.dom4j.Attribute loc = locale.next();
        loc.getParent().remove(loc);
    }

    // (3) Scrub unnecessary channel information...
    for (final Iterator<org.dom4j.Element> orphanedChannels = (Iterator<org.dom4j.Element>) layoutDoc
            .selectNodes("//channel[@fname = '']").iterator(); orphanedChannels.hasNext();) {
        // These elements represent UP_LAYOUT_STRUCT rows where the
        // CHAN_ID field was not recognized by ChannelRegistryStore;
        // best thing to do is remove the elements...
        final org.dom4j.Element ch = orphanedChannels.next();
        ch.getParent().remove(ch);
    }
    final List<String> channelAttributeWhitelist = Arrays.asList(new String[] { "fname", "unremovable",
            "hidden", "immutable", "ID", "dlm:plfID", "dlm:moveAllowed", "dlm:deleteAllowed" });
    final Iterator<org.dom4j.Element> channels = (Iterator<org.dom4j.Element>) layoutDoc
            .selectNodes("//channel").iterator();
    while (channels.hasNext()) {
        final org.dom4j.Element oldCh = channels.next();
        final org.dom4j.Element parent = oldCh.getParent();
        final org.dom4j.Element newCh = this.fac.createElement("channel");
        for (final String aName : channelAttributeWhitelist) {
            final org.dom4j.Attribute a = (org.dom4j.Attribute) oldCh.selectSingleNode("@" + aName);
            if (a != null) {
                newCh.addAttribute(a.getQName(), a.getValue());
            }
        }
        parent.elements().add(parent.elements().indexOf(oldCh), newCh);
        parent.remove(oldCh);
    }

    // (4) Convert internal DLM noderefs to external form (pathrefs)...
    for (final Iterator<org.dom4j.Attribute> origins = (Iterator<org.dom4j.Attribute>) layoutDoc
            .selectNodes("//@dlm:origin").iterator(); origins.hasNext();) {
        final org.dom4j.Attribute org = origins.next();
        final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef(
                (String) person.getAttribute(IPerson.USERNAME), org.getValue(), layoutDoc.getRootElement());
        if (dlmPathref != null) {
            // Change the value only if we have a valid pathref...
            org.setValue(dlmPathref.toString());
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'",
                        org.getUniquePath(), person.getAttribute(IPerson.USERNAME), org.getValue());
            }
        }
    }
    for (final Iterator<org.dom4j.Attribute> it = (Iterator<org.dom4j.Attribute>) layoutDoc
            .selectNodes("//@dlm:target").iterator(); it.hasNext();) {
        final org.dom4j.Attribute target = it.next();
        final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef(
                (String) person.getAttribute(IPerson.USERNAME), target.getValue(), layoutDoc.getRootElement());
        if (dlmPathref != null) {
            // Change the value only if we have a valid pathref...
            target.setValue(dlmPathref.toString());
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'",
                        target.getUniquePath(), person.getAttribute(IPerson.USERNAME), target.getValue());
            }
        }
    }
    for (final Iterator<org.dom4j.Attribute> names = (Iterator<org.dom4j.Attribute>) layoutDoc
            .selectNodes("//dlm:*/@name").iterator(); names.hasNext();) {
        final org.dom4j.Attribute n = names.next();
        if (n.getValue() == null || n.getValue().trim().length() == 0) {
            // Outer <dlm:positionSet> elements don't seem to use the name
            // attribute, though their childern do.  Just skip these so we
            // don't send a false WARNING.
            continue;
        }
        final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef(
                (String) person.getAttribute(IPerson.USERNAME), n.getValue(), layoutDoc.getRootElement());
        if (dlmPathref != null) {
            // Change the value only if we have a valid pathref...
            n.setValue(dlmPathref.toString());
            // These *may* have fnames...
            if (dlmPathref.getPortletFname() != null) {
                n.getParent().addAttribute("fname", dlmPathref.getPortletFname());
            }
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'",
                        n.getUniquePath(), person.getAttribute(IPerson.USERNAME), n.getValue());
            }
        }
    }

    // Remove synthetic Ids, but from non-fragment owners only...
    if (!this.isFragmentOwner(person)) {

        /*
         * In the case of fragment owners, the original database Ids allow
         * us keep (not break) the associations that subscribers have with
         * nodes on the fragment layout.
         */

        // (5) Remove dlm:plfID...
        for (final Iterator<org.dom4j.Attribute> plfid = (Iterator<org.dom4j.Attribute>) layoutDoc
                .selectNodes("//@dlm:plfID").iterator(); plfid.hasNext();) {
            final org.dom4j.Attribute plf = plfid.next();
            plf.getParent().remove(plf);
        }

        // (6) Remove database Ids...
        for (final Iterator<org.dom4j.Attribute> ids = (Iterator<org.dom4j.Attribute>) layoutDoc
                .selectNodes("//@ID").iterator(); ids.hasNext();) {
            final org.dom4j.Attribute a = ids.next();
            a.getParent().remove(a);
        }
    }

    return layoutDoc.getRootElement();
}

From source file:org.arangitester.log.XmlResult.java

License:Apache License

public void save(File file, FunctionalSuite result) {

    // file indicates a pathname
    Document document = DocumentHelper.createDocument(); // create a new xml document
    Element root = document.addElement("LccFunctionalSuite"); // create the root tag named LccFunctionalSuite
    if (result == null)
        return;/*from www  .  j  av a 2s .c  om*/

    SummaryHelper summary = new SummaryHelper(result);

    root.addAttribute("totalTime", String.valueOf(summary.getTotalTime()));
    System.out.println("Tempo de Execuo: " + summary.getTotalTime() + " min");
    root.addAttribute("total", String.valueOf(summary.getTotal()));
    System.out.println("Total: " + summary.getTotal());
    root.addAttribute("skip", String.valueOf(summary.getSkip()));
    System.out.println("Skiped: " + summary.getSkip());
    root.addAttribute("fail", String.valueOf(summary.getFail()));
    System.out.println("Fail: " + summary.getFail());
    root.addAttribute("successful", String.valueOf(summary.getSuccessful()));
    System.out.println("Successful: " + summary.getSuccessful());
    root.addAttribute("percent", String.valueOf(summary.getPercent()));
    System.out.println("Sucessful: " + summary.getPercent() + "%");

    for (UseCase usecase : result.getCases()) {
        Element userCaseElement = root.addElement("UseCase").addAttribute("name", usecase.getName())
                .addAttribute("startTime", getFormatedDate((usecase.getStartTime())))
                .addAttribute("endTime", getFormatedDate(usecase.getEndTime()));

        for (String obs : usecase.getObs()) {
            Element obsElement = userCaseElement.addElement("Obs");
            obsElement.addText(obs);
        }

        for (Object log : usecase.getlogs()) {
            if (log instanceof Info) {
                userCaseElement.addElement("info").addText(((Info) log).getMessage());
            } else {
                Error error = ((Error) log);
                Element errorElement = userCaseElement.addElement("error").addAttribute("cause",
                        error.getCause());
                if (error.getScreenshot() != null)
                    errorElement.addAttribute("screenshot", error.getScreenshot());

                if (error.getError() != null)
                    errorElement.addText(error.getError());
            }
        }

        for (TestCase testcase : usecase.getTestcases()) {
            Element testCaseElement = userCaseElement.addElement("TestCase")
                    .addAttribute("name", testcase.getJavaMethod())
                    .addAttribute("description", testcase.getTestcase())
                    .addAttribute("startTime", getFormatedDate(testcase.getStartTime()))
                    .addAttribute("endTime", getFormatedDate(testcase.getEndTime()))
                    .addAttribute("skip", String.valueOf(testcase.isSkip()));

            for (Object log : testcase.getlogs()) {
                if (log instanceof Info) {
                    testCaseElement.addElement("info").addText(((Info) log).getMessage());
                } else {
                    Error error = ((Error) log);
                    Element errorElement = testCaseElement.addElement("error").addAttribute("cause",
                            error.getCause());
                    if (error.getScreenshot() != null)
                        errorElement.addAttribute("screenshot", error.getScreenshot());

                    if (error.getError() != null)
                        errorElement.addText(error.getError());
                }
            }

        }
    }
    // End of the document building
    // Now, we will start to write in document
    try {
        file.getParentFile().mkdirs();
        file.createNewFile();
        OutputFormat outformat = OutputFormat.createPrettyPrint();
        XMLWriter write = new XMLWriter(new FileWriter(file), outformat); // Initialize the xml file
        write.write(document); // Write the final document on xml file
        write.close();
    } catch (IOException e) {
        System.out.println("Erro durante a gravao no arquivo " + file + " :\n" + e.toString());
    }

}

From source file:org.ballproject.knime.base.config.CTDNodeConfigurationWriter.java

License:Open Source License

public void write(String filename) throws IOException {
    OutputFormat format = OutputFormat.createPrettyPrint();

    XMLWriter writer = new XMLWriter(new FileWriter(filename), format);
    writer.write(doc);//from  ww  w  . j  av  a2 s .c o  m

    writer.close();
}