Example usage for org.dom4j.io OutputFormat OutputFormat

List of usage examples for org.dom4j.io OutputFormat OutputFormat

Introduction

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

Prototype

public OutputFormat(String indent, boolean newlines) 

Source Link

Document

Creates an OutputFormat with the given indent added with optional newlines between the Elements.

Usage

From source file:itensil.io.xml.XMLDocument.java

License:Open Source License

public static void writeStream(Document doc, OutputStream out) throws IOException {
    XMLWriter dxw = new XMLWriter(out, new OutputFormat("\t", true));
    dxw.write(doc);//from   w  ww .ja v  a2s  .  c  o m
}

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);//from  www .  jav a  2  s. c o  m
    xw.write(document);
    xw.close();
    System.out.println(document.asXML());
}

From source file:mesquite.lib.XMLUtil.java

License:Open Source License

public static String getDocumentAsXMLString2(Document doc) {
    try {/*from ww w.  j  a v  a2s .c  o  m*/
        String encoding = doc.getXMLEncoding();

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

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

From source file:net.unicon.toro.installer.tools.MergeConfiguration.java

License:Open Source License

private void saveXml(Element el, File saveTo) {
    try {/* ww w  .j  a v  a 2  s.  c  o m*/
        OutputFormat format = new OutputFormat("    ", true);
        format.setTrimText(true);
        XMLWriter writer = new XMLWriter(new FileWriter(saveTo), format);
        writer.write(el);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:nl.tue.gale.ae.processor.plugin.ExportPlugin.java

License:Open Source License

public void doGet(Resource resource) throws ProcessorException {
    GaleContext gale = GaleContext.of(resource);
    try {//  ww  w.ja  v a 2 s. c om
        String root = gale.req().getParameter("root");
        if (root == null || "".equals(root))
            throw new IllegalArgumentException("no 'root' specified as parameter");
        URI[] conceptList = CountModule.getUriCache(URIs.of(root), gale);
        Set<Concept> concepts = new TreeSet<Concept>(new Concept.comparator());
        for (URI concept : conceptList) {
            Concept c = gale.dm().get(concept);
            concepts.add(c);
            concepts.addAll(c.getNamedOutConcepts("extends"));
        }
        Element result = GDOMFormat.toXML(ImmutableList.copyOf(concepts));

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        XMLWriter writer = new XMLWriter(out, new OutputFormat("  ", true));
        writer.write(result);
        resource.put("stream", new ByteArrayInputStream(out.toByteArray()));
        resource.put("mime", "application/gdom");
        gale.usedStream();
    } catch (Exception e) {
        throw new ProcessorException("unable to export domain model to .gdom file: " + e.getMessage(), e);
    }
}

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  www .  j  av  a  2s  . 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.danann.cernunnos.xml.XslTransformTask.java

License:Apache License

public void perform(TaskRequest req, TaskResponse res) {
    final String contextLocation = (String) context.evaluate(req, res);
    final String stylesheetLocation = (String) stylesheet.evaluate(req, res);
    final Tuple<String, String> transformerKey = new Tuple<String, String>(contextLocation, stylesheetLocation);
    final Templates templates = this.transformerCache.getCachedObject(req, res, transformerKey,
            this.transformerFactory);

    Element srcElement = null;/*ww  w .j a v  a2s.  c  o m*/
    Node nodeReagentEvaluated = node != null ? (Node) node.evaluate(req, res) : null;
    if (nodeReagentEvaluated != null) {
        // Reading from the NODE reagent is preferred...
        srcElement = (Element) nodeReagentEvaluated;
    } else {
        // But read from LOCATION if NODE isn't set...
        final String locationStr = (String) location.evaluate(req, res);
        final URL loc;
        try {
            final URL ctx;
            try {
                ctx = new URL(contextLocation);
            } catch (MalformedURLException mue) {
                throw new RuntimeException("Failed to parse context '" + contextLocation + "' into URL", mue);
            }

            loc = new URL(ctx, locationStr);
        } catch (MalformedURLException mue) {
            throw new RuntimeException("Failed to parse location '" + locationStr + "' with context '"
                    + contextLocation + "' into URL", mue);
        }

        // Use an EntityResolver if provided...
        SAXReader rdr = new SAXReader();
        EntityResolver resolver = (EntityResolver) entityResolver.evaluate(req, res);
        if (resolver != null) {
            rdr.setEntityResolver(resolver);
        }

        final Document document;
        try {
            document = rdr.read(loc);
        } catch (DocumentException de) {
            throw new RuntimeException("Failed to read XML Document for XSLT from " + loc.toExternalForm(), de);
        }
        srcElement = document.getRootElement();
    }

    DocumentFactory dfac = new DocumentFactory();
    Document ddoc = dfac.createDocument((Element) srcElement.clone());
    DOMWriter dwriter = new DOMWriter();

    DocumentResult rslt = new DocumentResult();

    final Transformer trans;
    try {
        trans = templates.newTransformer();
    } catch (TransformerConfigurationException tce) {
        throw new RuntimeException("Failed to retrieve Transformer for XSLT", tce);
    }

    try {
        trans.transform(new DOMSource(dwriter.write(ddoc)), rslt);
    } catch (TransformerException te) {
        throw new RuntimeException("Failed to perform XSL transformation", te);
    } catch (DocumentException de) {
        throw new RuntimeException("Failed to translate JDOM Document to W3C Document", de);
    }

    final Element rootElement = rslt.getDocument().getRootElement();

    if (to_file != null) {
        File f = new File((String) to_file.evaluate(req, res));
        if (f.getParentFile() != null) {
            // Make sure the necessary directories are in place...
            f.getParentFile().mkdirs();
        }

        final XMLWriter writer;
        try {
            writer = new XMLWriter(new FileOutputStream(f), new OutputFormat("  ", true));
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Failed to create XML writer", uee);
        } catch (FileNotFoundException fnfe) {
            throw new RuntimeException("Could not create file for XML output: " + f, fnfe);
        }

        try {
            writer.write(rootElement);
        } catch (IOException ioe) {
            throw new RuntimeException("Failed to write transformed XML document to: " + f, ioe);
        }
    } else {
        // default behavior...
        res.setAttribute(Attributes.NODE, rootElement);
    }

    super.performSubtasks(req, res);

}

From source file:org.dom4j.samples.CreateXMLDemo.java

License:Open Source License

public void run(String[] args) throws Exception {
    Document document = createDocument();
    OutputFormat format = new OutputFormat("  ", true);

    if (args.length < 1) {
        XMLWriter writer = new XMLWriter(System.out, format);
        writer.write(document);/*w  ww . j  a  v  a2 s .c  om*/
    } else {
        String fileName = args[0];
        println("Writing file: " + fileName);
        FileWriter out = new FileWriter(args[0]);
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        out.close();
    }
}

From source file:org.dom4j.samples.XPathTool.java

License:Open Source License

public void run(String[] args) throws Exception {
    if (args.length < 1) {
        printUsage("{options} <xml file>");
        return;//from   ww w. j a  va2 s .c  o m
    }

    for (int i = 0, size = args.length; i < size; i++) {
        String arg = args[i];
        if (arg.startsWith("-")) {
            readOptions(arg);
        } else {
            println("Parsing: " + arg);
            document = parse(arg);
            break;
        }
    }

    xmlWriter = new XMLWriter(System.out, new OutputFormat("  ", true));
    userLoop();
}

From source file:org.hibernate.envers.boot.internal.AdditionalJaxbMappingProducerImpl.java

License:LGPL

@Override
public Collection<MappingDocument> produceAdditionalMappings(final MetadataImplementor metadata,
        IndexView jandexIndex, final MappingBinder mappingBinder,
        final MetadataBuildingContext buildingContext) {
    final ServiceRegistry serviceRegistry = metadata.getMetadataBuildingOptions().getServiceRegistry();
    final EnversService enversService = serviceRegistry.getService(EnversService.class);

    if (!enversService.isEnabled()) {
        // short-circuit if envers integration has been disabled.
        return Collections.emptyList();
    }//from   ww  w . ja  v  a2  s .co m

    final ArrayList<MappingDocument> additionalMappingDocuments = new ArrayList<MappingDocument>();

    // atm we do not have distinct origin info for envers
    final Origin origin = new Origin(SourceType.OTHER, "envers");
    //      final DOMWriter writer = new DOMWriter();

    final MappingCollector mappingCollector = new MappingCollector() {
        @Override
        public void addDocument(Document document) throws DocumentException {
            dump(document);

            // while the commented-out code here is more efficient (well, understanding that
            // this whole process is un-efficient)  it leads to un-decipherable messages when
            // we get mapping mapping errors from envers output.
            //            final DOMSource domSource = new DOMSource( writer.write( document ) );
            //            domSource.setSystemId( "envers" );
            //            final Binding jaxbBinding = mappingBinder.bind( domSource, origin );

            // this form at least allows us to get better error messages
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final Writer w = new PrintWriter(baos);
            try {
                final XMLWriter xw = new XMLWriter(w, new OutputFormat(" ", true));
                xw.write(document);
                w.flush();
            } catch (IOException e) {
                throw new HibernateException("Unable to bind Envers-generated XML", e);
            }

            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            BufferedInputStream bis = new BufferedInputStream(bais);
            final Binding jaxbBinding = mappingBinder.bind(bis, origin);

            final JaxbHbmHibernateMapping jaxbRoot = (JaxbHbmHibernateMapping) jaxbBinding.getRoot();
            additionalMappingDocuments.add(new MappingDocument(jaxbRoot, origin, buildingContext));
        }
    };

    enversService.initialize(metadata, mappingCollector);

    return additionalMappingDocuments;
}