Example usage for org.dom4j.io XMLWriter write

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

Introduction

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

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

From source file:jp.aegif.alfresco.online_webdav.PropPatchMethod.java

License:Open Source License

/**
 * Generates the XML response for a PROPFIND request that asks for a list of
 * all known properties//ww  w  .j  a  v a2  s . co m
 * 
 * @param xml XMLWriter
 * @param node NodeRef
 * @param isDir boolean
 */
protected void generatePropertyResponse(XMLWriter xml, WebDAVProperty property, int status,
        String description) {
    try {
        // Output the start of the properties element
        Attributes nullAttr = getDAVHelper().getNullAttributes();

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT, nullAttr);

        // Output property name
        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP, nullAttr);
        if (property.hasNamespaceName()) {
            xml.write(DocumentHelper.createElement(
                    property.getNamespaceName() + WebDAV.NAMESPACE_SEPARATOR + property.getName()));
        } else {
            xml.write(DocumentHelper.createElement(property.getName()));
        }
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROP, WebDAV.XML_NS_PROP);

        // Output action result status
        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS, nullAttr);
        xml.write(WebDAV.HTTP1_1 + " " + status + " " + description);
        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_STATUS, WebDAV.XML_NS_STATUS);

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_PROPSTAT, WebDAV.XML_NS_PROPSTAT);
    } catch (Exception ex) {
        // Convert to a runtime exception
        throw new AlfrescoRuntimeException("XML processing error", ex);
    }
}

From source file:jp.aegif.alfresco.online_webdav.PropPatchMethod.java

License:Open Source License

/**
 * Generates the error tag/*from  w ww . j  av a2 s  .com*/
 * 
 * @param xml XMLWriter
 */
protected void generateError(XMLWriter xml) {
    try {
        // Output the start of the error element
        Attributes nullAttr = getDAVHelper().getNullAttributes();

        xml.startElement(WebDAV.DAV_NS, WebDAV.XML_ERROR, WebDAV.XML_NS_ERROR, nullAttr);
        // Output error
        xml.write(DocumentHelper.createElement(WebDAV.XML_NS_CANNOT_MODIFY_PROTECTED_PROPERTY));

        xml.endElement(WebDAV.DAV_NS, WebDAV.XML_ERROR, WebDAV.XML_NS_ERROR);
    } catch (Exception ex) {
        // Convert to a runtime exception
        throw new AlfrescoRuntimeException("XML processing error", ex);
    }
}

From source file:jp.aegif.alfresco.online_webdav.WebDAVMethod.java

License:Open Source License

/**
 * Generates the lock discovery XML response
 * /*from  w ww.  j  a v  a 2  s.  co m*/
 * @param xml XMLWriter
 * @param lockNode NodeRef
 * @param emptyNamespace boolean True if namespace should be empty. Used to avoid bugs in WebDAV clients.
 * @param scope String lock scope
 * @param depth String lock depth
 * @param lToken String locktoken
 * @param owner String lock owner
 * @param expiryDate the date/time the lock should expire
 */
protected void generateLockDiscoveryXML(XMLWriter xml, FileInfo lockNodeInfo, boolean emptyNamespace,
        String scope, String depth, String lToken, String owner, Date expiryDate) throws Exception {
    Attributes nullAttr = getDAVHelper().getNullAttributes();
    String ns = emptyNamespace ? "" : WebDAV.DAV_NS;
    if (lockNodeInfo != null) {
        // Output the XML response

        xml.startElement(ns, WebDAV.XML_LOCK_DISCOVERY,
                emptyNamespace ? WebDAV.XML_LOCK_DISCOVERY : WebDAV.XML_NS_LOCK_DISCOVERY, nullAttr);
        xml.startElement(ns, WebDAV.XML_ACTIVE_LOCK,
                emptyNamespace ? WebDAV.XML_ACTIVE_LOCK : WebDAV.XML_NS_ACTIVE_LOCK, nullAttr);

        xml.startElement(ns, WebDAV.XML_LOCK_TYPE,
                emptyNamespace ? WebDAV.XML_LOCK_TYPE : WebDAV.XML_NS_LOCK_TYPE, nullAttr);
        xml.write(DocumentHelper.createElement(emptyNamespace ? WebDAV.XML_WRITE : WebDAV.XML_NS_WRITE));
        xml.endElement(ns, WebDAV.XML_LOCK_TYPE,
                emptyNamespace ? WebDAV.XML_LOCK_TYPE : WebDAV.XML_NS_LOCK_TYPE);

        xml.startElement(ns, WebDAV.XML_LOCK_SCOPE,
                emptyNamespace ? WebDAV.XML_LOCK_SCOPE : WebDAV.XML_NS_LOCK_SCOPE, nullAttr);
        xml.write(DocumentHelper.createElement(emptyNamespace ? scope : WebDAV.DAV_NS_PREFIX + scope));
        xml.endElement(ns, WebDAV.XML_LOCK_SCOPE,
                emptyNamespace ? WebDAV.XML_LOCK_SCOPE : WebDAV.XML_NS_LOCK_SCOPE);

        // NOTE: We only support one level of lock at the moment

        xml.startElement(ns, WebDAV.XML_DEPTH, emptyNamespace ? WebDAV.XML_DEPTH : WebDAV.XML_NS_DEPTH,
                nullAttr);
        xml.write(depth);
        xml.endElement(ns, WebDAV.XML_DEPTH, emptyNamespace ? WebDAV.XML_DEPTH : WebDAV.XML_NS_DEPTH);

        xml.startElement(ns, WebDAV.XML_OWNER, emptyNamespace ? WebDAV.XML_OWNER : WebDAV.XML_NS_OWNER,
                nullAttr);
        xml.write(owner);
        xml.endElement(ns, WebDAV.XML_OWNER, emptyNamespace ? WebDAV.XML_OWNER : WebDAV.XML_NS_OWNER);

        xml.startElement(ns, WebDAV.XML_TIMEOUT, emptyNamespace ? WebDAV.XML_TIMEOUT : WebDAV.XML_NS_TIMEOUT,
                nullAttr);

        // Output the expiry time

        String strTimeout = WebDAV.INFINITE;
        if (expiryDate != null) {
            long timeoutRemaining = (expiryDate.getTime() - System.currentTimeMillis()) / 1000L;

            strTimeout = WebDAV.SECOND + timeoutRemaining;
        }
        xml.write(strTimeout);

        xml.endElement(ns, WebDAV.XML_TIMEOUT, emptyNamespace ? WebDAV.XML_TIMEOUT : WebDAV.XML_NS_TIMEOUT);

        xml.startElement(ns, WebDAV.XML_LOCK_TOKEN,
                emptyNamespace ? WebDAV.XML_LOCK_TOKEN : WebDAV.XML_NS_LOCK_TOKEN, nullAttr);
        xml.startElement(ns, WebDAV.XML_HREF, emptyNamespace ? WebDAV.XML_HREF : WebDAV.XML_NS_HREF, nullAttr);

        xml.write(lToken);

        xml.endElement(ns, WebDAV.XML_HREF, emptyNamespace ? WebDAV.XML_HREF : WebDAV.XML_NS_HREF);
        xml.endElement(ns, WebDAV.XML_LOCK_TOKEN,
                emptyNamespace ? WebDAV.XML_LOCK_TOKEN : WebDAV.XML_NS_LOCK_TOKEN);

        xml.endElement(ns, WebDAV.XML_ACTIVE_LOCK,
                emptyNamespace ? WebDAV.XML_ACTIVE_LOCK : WebDAV.XML_NS_ACTIVE_LOCK);
        xml.endElement(ns, WebDAV.XML_LOCK_DISCOVERY,
                emptyNamespace ? WebDAV.XML_LOCK_DISCOVERY : WebDAV.XML_NS_LOCK_DISCOVERY);
    }
}

From source file:jt56.comm.code.util.WolfXmlUtil.java

License:Open Source License

public void getXMLWrite(Document document, String filePath) throws Exception {
    OutputFormat of = new OutputFormat(" ", true);
    of.setEncoding("UTF-8");
    XMLWriter xw = new XMLWriter(new FileWriter(filePath), of);
    xw.setEscapeText(false);//  ww w  .  j a v  a  2 s  . c  om
    xw.write(document);
    xw.close();
    System.out.println(document.asXML());
}

From source file:lempel.blueprint.base.config.XmlConfig.java

License:Open Source License

public void save(final String fileName) throws IOException {
    org.dom4j.Document dom4jDoc = new DOMReader().read(config);
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(fileName), format);
    writer.write(dom4jDoc);
    writer.close();/*from w  w w.  ja v  a 2 s.c o m*/
}

From source file:main.FrevoMain.java

License:Open Source License

/**
 * Starts a saving procedure calling the method's own saveResults function.
 * Run-specific data will be added to the end of the file.
 * /*from w w  w .j  a v a2  s.  co  m*/
 * @param fileName
 *            Name of the saved file without the extension. (E.g.
 *            solution_generation_13)
 * @param method
 *            The corresponding method instance to be called for saving.
 */
public static File saveResult(String fileName, final Element representationRootElement, long startSeed,
        long currentActiveSeed) {
    // create new document for output
    Document doc = DocumentHelper.createDocument();
    doc.addDocType("frevo", null, System.getProperty("user.dir") + "//Components//ISave.dtd");
    Element dfrevo = doc.addElement("frevo");

    String fileLocation = "Undefined";

    // export sessionconfig
    Element sessionconfig = dfrevo.addElement("sessionconfig");

    // custom name
    Element configentry = sessionconfig.addElement("configentry");
    configentry.addAttribute("key", "CustomName");
    configentry.addAttribute("type", "STRING");
    configentry.addAttribute("value", customName);

    // number of runs
    Element runentry = sessionconfig.addElement("configentry");
    runentry.addAttribute("key", "NumberofRuns");
    runentry.addAttribute("type", "INT");
    runentry.addAttribute("value", Integer.toString(getNumberOfSimulationRuns()));

    // starting seed
    Element seedentry = sessionconfig.addElement("configentry");
    seedentry.addAttribute("key", "StartingSeed");
    seedentry.addAttribute("type", "LONG");
    // seedentry.addAttribute("value", Long.toString(getSeed()));
    seedentry.addAttribute("value", Long.toString(startSeed));

    // active seed
    Element aseedentry = sessionconfig.addElement("configentry");
    aseedentry.addAttribute("key", "CurrentSeed");
    aseedentry.addAttribute("type", "LONG");
    aseedentry.addAttribute("value", Long.toString(currentActiveSeed));

    try {
        // export problem
        Element problemsettings = dfrevo.addElement("problem");
        ComponentXMLData problem = FrevoMain.SELECTED_PROBLEM;
        problemsettings.addAttribute("class", problem.getClassName());
        Vector<String> keys = new Vector<String>(problem.getProperties().keySet());
        for (String k : keys) {
            Element entry = problemsettings.addElement("problementry");
            entry.addAttribute("key", k);
            entry.addAttribute("type", problem.getTypeOfProperty(k).toString());
            entry.addAttribute("value", problem.getValueOfProperty(k));
        }

        // export method
        Element methodsettings = dfrevo.addElement("method");
        ComponentXMLData method = FrevoMain.SELECTED_METHOD;
        methodsettings.addAttribute("class", method.getClassName());
        keys = new Vector<String>(method.getProperties().keySet());
        for (String k : keys) {
            Element entry = methodsettings.addElement("methodentry");
            entry.addAttribute("key", k);
            entry.addAttribute("type", method.getTypeOfProperty(k).toString());
            entry.addAttribute("value", method.getValueOfProperty(k));
        }

        // export ranking
        Element rankingsettings = dfrevo.addElement("ranking");
        ComponentXMLData ranking = FrevoMain.SELECTED_RANKING;
        rankingsettings.addAttribute("class", ranking.getClassName());
        keys = new Vector<String>(ranking.getProperties().keySet());
        for (String k : keys) {
            Element entry = rankingsettings.addElement("rankingentry");
            entry.addAttribute("key", k);
            entry.addAttribute("type", ranking.getTypeOfProperty(k).toString());
            entry.addAttribute("value", ranking.getValueOfProperty(k));
        }

        // export representation
        Element repsettings = dfrevo.addElement("representation");
        ComponentXMLData representation = FrevoMain.SELECTED_REPRESENTATION;
        repsettings.addAttribute("class", representation.getClassName());
        keys = new Vector<String>(representation.getProperties().keySet());
        for (String k : keys) {
            Element entry = repsettings.addElement("representationentry");
            entry.addAttribute("key", k);
            entry.addAttribute("type", representation.getTypeOfProperty(k).toString());
            entry.addAttribute("value", representation.getValueOfProperty(k));
        }

        // call method's own save solution
        dfrevo.add(representationRootElement);

        // save contents to file

        String location = FREVO_INSTALL_DIRECTORY + File.separator + "Results" + File.separator + customName;
        File rootSaveDir = new File(location);

        // remove spaces from filename
        fileName.replaceAll(" ", "_");

        // create save directory based on given custom name
        rootSaveDir.mkdirs();

        // create sub-directories for different seeds
        if (FrevoMain.getNumberOfSimulationRuns() > 1) {
            // create seed directory if there are more than one run
            File seedDir = new File(location + File.separator + "seed_" + startSeed);
            seedDir.mkdir();
            fileLocation = seedDir + File.separator + fileName + ".zre";
        } else {
            // save it the root location
            fileLocation = rootSaveDir + File.separator + fileName + ".zre";
        }

        File saveFile = new File(fileLocation);

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));

        saveFile.createNewFile();
        FileWriter out = new FileWriter(saveFile);
        BufferedWriter bw = new BufferedWriter(out);
        XMLWriter wr = new XMLWriter(bw, format);
        wr.write(doc);
        wr.close();
        System.out.println("XML Writing Completed: " + fileLocation);

        if (isFrevoWithGraphics()) {
            mainWindow.addRecentResult(saveFile);
        }
        return saveFile;
    } catch (OutOfMemoryError mem) {
        System.err.println("Could not export! (Out of memory)");
    } catch (IOException e) {
        System.err.println("IOException while writing to XML! Check path at: " + fileLocation);
        e.printStackTrace();
    }
    return null;
}

From source file:main.FrevoMain.java

License:Open Source License

/**
 * Saves FREVO settings to the configuration file. Initiates file writing to
 * store data./*from   w ww . j a  va 2  s. c  om*/
 */
public static void saveSettings() {
    Document doc;
    File configfile = new File(FREVO_INSTALL_DIRECTORY + "/frevo_config.xml");
    if (configfile.exists()) {
        // load data if it already exists
        doc = SafeSAX.read(configfile, true);

        Node windowsizes = doc.selectSingleNode("/frevo/window-sizes");

        List<?> items = windowsizes.selectNodes(".//window");
        Iterator<?> it = items.iterator();

        while (it.hasNext()) {
            Element el = (Element) it.next();
            String name = el.valueOf("./@name");

            // save main data
            if (name.equals("main")) {
                el.addAttribute("width", Integer.toString(FrevoMain.mainWindowParameters[0]));
                el.addAttribute("height", Integer.toString(FrevoMain.mainWindowParameters[1]));
            }
            // save component browser data
            if (name.equals("componentbrowser")) {
                el.addAttribute("width", Integer.toString(FrevoMain.componentBrowserParameters[0]));
                el.addAttribute("height", Integer.toString(FrevoMain.componentBrowserParameters[1]));
                el.addAttribute("topsplit", Integer.toString(FrevoMain.componentBrowserParameters[2]));
                el.addAttribute("bigsplit", Integer.toString(FrevoMain.componentBrowserParameters[3]));
            }
        }
    } else {
        try {
            configfile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // file does not exist
        doc = DocumentHelper.createDocument();
        doc.addDocType("frevo", null, "config.dtd");
        Element dfrevo = doc.addElement("frevo");

        dfrevo.addElement("tags");

        Element windowsizes = dfrevo.addElement("window-sizes");
        Element mainwindow = windowsizes.addElement("window");
        mainwindow.addAttribute("name", "main");
        mainwindow.addAttribute("width", Integer.toString(FrevoMain.mainWindowParameters[0]));
        mainwindow.addAttribute("height", Integer.toString(FrevoMain.mainWindowParameters[1]));

        Element compwindow = windowsizes.addElement("window");
        compwindow.addAttribute("name", "componentbrowser");
        compwindow.addAttribute("width", Integer.toString(FrevoMain.componentBrowserParameters[0]));
        compwindow.addAttribute("height", Integer.toString(FrevoMain.componentBrowserParameters[1]));
        compwindow.addAttribute("topsplit", Integer.toString(FrevoMain.componentBrowserParameters[2]));
        compwindow.addAttribute("bigsplit", Integer.toString(FrevoMain.componentBrowserParameters[3]));
    }

    // write to file
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));

        configfile.createNewFile();
        FileWriter out = new FileWriter(configfile);
        BufferedWriter bw = new BufferedWriter(out);
        XMLWriter wr = new XMLWriter(bw, format);
        wr.write(doc);
        wr.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:main.FrevoMain.java

License:Open Source License

/**
 * Imports a component packaged in the FREVO package format (zcp). Copied
 * files will still persist even if operation fails or the component is bad.
 * /* w w w.  j a  v  a 2  s. co  m*/
 * @param importfile
 *            The ZCP file to be imported.
 */
public static void importComponent(File importfile) {
    // unzip to the given location
    String outputdir = null;
    URI frevo_install_base = new File(FrevoMain.getInstallDirectory()).toURI();
    try {
        ZipFile zfile = new ZipFile(importfile);
        File directory = new File(FREVO_INSTALL_DIRECTORY + File.separator + "Components");

        Enumeration<? extends ZipEntry> entries = zfile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File file = new File(directory, entry.getName());
            if (entry.isDirectory()) {
                file.mkdirs();
            } else {
                file.getParentFile().mkdirs();
                InputStream in = zfile.getInputStream(entry);
                try {
                    copy(in, file);
                    // copy data from root XML
                    String extension = FrevoMain.getExtension(file);
                    if (extension.equals("xml")) {
                        URI fileURI = frevo_install_base.relativize(file.toURI());
                        String uristring = fileURI.toString();
                        String opath = uristring.substring(0, uristring.length() - extension.length() - 1);
                        if ((outputdir == null) || (opath.length() < outputdir.length())) {
                            outputdir = opath;
                        }
                    }
                } finally {
                    in.close();
                }
            }
        }
        zfile.close();
    } catch (ZipException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // component successfully installed, add to Eclipse classpath
    File classpath = new File(FREVO_INSTALL_DIRECTORY + File.separator + ".classpath");
    if (classpath.exists()) {
        System.out.println("Adjusting Eclipse classpath...");
        Document doc = SafeSAX.read(classpath, true);

        Element root = doc.getRootElement();

        Element componentElement = root.addElement("classpathentry");
        componentElement.addAttribute("kind", "src");
        componentElement.addAttribute("output", outputdir);
        componentElement.addAttribute("path", outputdir);

        // save file
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setLineSeparator(System.getProperty("line.separator"));
            FileWriter out = new FileWriter(classpath);
            BufferedWriter bw = new BufferedWriter(out);
            XMLWriter wr = new XMLWriter(bw, format);
            wr.write(doc);
            wr.close();
        } catch (IOException e) {
            System.err.println("ERROR: Could not write Eclipse classpath file!");
            e.printStackTrace();
        }
    }

}

From source file:main.FrevoMain.java

License:Open Source License

/**
 * Removes the component from the installed components. This function also
 * removes all files within the component's directory. Forces FREVO to
 * reload all components afterwards.//from  ww  w .  j  a  v a2 s  .c  om
 * 
 * @param cdata
 *            The component to be removed
 */
public static void deleteComponent(ComponentXMLData cdata) {

    // remove base XML
    File baseXML = cdata.getSourceXMLFile();
    baseXML.delete();

    // erase all files within component directory
    // get class root directory
    String classDir = cdata.getClassDir();

    // extract directory name
    // construct copy
    int i = 0;
    while (i < classDir.length()) {
        char c = classDir.charAt(i);
        if ((c == '/') || (c == '\\')) {
            i++;
        } else {
            break;
        }
    }

    int end = i + 1;
    while (end < classDir.length()) {
        char c = classDir.charAt(end);
        if ((c == '/') || (c == '\\')) {
            break;
        } else {
            end++;
        }
    }

    classDir = classDir.substring(i, end);

    String comprootdirname = classDir.split("/")[0];

    // get component root directory
    String comprootdir = FrevoMain.getComponentDirectory(cdata.getComponentType()) + comprootdirname;

    File rootdir = new File(comprootdir);

    eraseDirectory(rootdir);

    // Remove entry from classpath
    File classpath = new File(FrevoMain.getInstallDirectory() + File.separator + ".classpath");
    if (classpath.exists()) {
        Document doc = SafeSAX.read(classpath, true);

        Element root = doc.getRootElement();
        String output; // the string to match the "output" field in
        // classpath xml

        // correct pathname for multiproblems
        if (cdata.getComponentType() == ComponentType.FREVO_MULTIPROBLEM)
            output = "Components/" + "Problems/" + comprootdirname;
        else if (cdata.getComponentType() == ComponentType.FREVO_BULKREPRESENTATION)
            output = "Components/" + "Representations/" + comprootdirname;
        else
            output = "Components/" + FrevoMain.getComponentTypeAsString(cdata.getComponentType()) + "s/"
                    + comprootdirname;
        // System.out.println("removing "+output);
        Node node = root.selectSingleNode("classpathentry[@output='" + output + "']");
        if (node != null)
            node.detach();

        // save XML
        try {
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setLineSeparator(System.getProperty("line.separator"));
            FileWriter out = new FileWriter(classpath);
            BufferedWriter bw = new BufferedWriter(out);
            XMLWriter wr = new XMLWriter(bw, format);
            wr.write(doc);
            wr.close();
        } catch (IOException e) {
            System.err.println("ERROR: Could not write Eclipse classpath file!");
            e.printStackTrace();
        }

    }

    // force reloading components
    FrevoMain.reLoadComponents(true);
}

From source file:mesquite.lib.XMLUtil.java

License:Open Source License

public static String getDocumentAsXMLString(Document doc, boolean escapeText) {
    try {//from w  w  w. j ava  2 s. c o  m
        String encoding = doc.getXMLEncoding();

        if (encoding == null)
            encoding = "UTF-8";

        Writer osw = new StringWriter();
        OutputFormat opf = new OutputFormat("  ", true, encoding);
        XMLWriter writer = new XMLWriter(osw, opf);
        writer.setEscapeText(escapeText);
        writer.write(doc);
        writer.close();
        return osw.toString();
    } catch (IOException e) {
        MesquiteMessage.warnProgrammer("XML Document could not be returned as string.");
    }
    return null;
}