Example usage for org.dom4j.io XMLWriter XMLWriter

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

Introduction

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

Prototype

public XMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException 

Source Link

Usage

From source file:nl.nn.adapterframework.util.XmlUtils.java

License:Apache License

public static String canonicalize(String input) throws DocumentException, IOException {
    if (StringUtils.isEmpty(input)) {
        return null;
    }/*from w  ww  .j  a  v a2s  .co  m*/
    org.dom4j.Document doc = DocumentHelper.parseText(input);
    StringWriter sw = new StringWriter();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setExpandEmptyElements(true);
    XMLWriter xw = new XMLWriter(sw, format);
    xw.write(doc);
    return sw.toString();
}

From source file:nl.nn.ibistesttool.PipeDescriptionProvider.java

License:Apache License

/**
 * Get a PipeDescription object for the specified pipe. The returned object
 * is cached.//from w  w  w . ja v a  2s.c  o  m
 */
public PipeDescription getPipeDescription(PipeLine pipeLine, IPipe pipe) {
    PipeDescription pipeDescription;
    String adapterName = pipeLine.getOwner().getName();
    String pipeName = pipe.getName();
    String checkpointName = null;
    String xpathExpression = null;
    if (pipeLine.getPipe(pipeName) == null) {
        if (PipeLine.INPUT_VALIDATOR_NAME.equals(pipeName)) {
            checkpointName = INPUT_VALIDATOR_CHECKPOINT_NAME;
            xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/inputValidator";
        } else if (PipeLine.OUTPUT_VALIDATOR_NAME.equals(pipeName)) {
            checkpointName = OUTPUT_VALIDATOR_CHECKPOINT_NAME;
            xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/outputValidator";
        } else if (PipeLine.INPUT_WRAPPER_NAME.equals(pipeName)) {
            checkpointName = INPUT_WRAPPER_CHECKPOINT_NAME;
            xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/inputWrapper";
        } else if (PipeLine.OUTPUT_WRAPPER_NAME.equals(pipeName)) {
            checkpointName = OUTPUT_WRAPPER_CHECKPOINT_NAME;
            xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/outputWrapper";
        } else if (pipeName.startsWith(MessageSendingPipe.INPUT_VALIDATOR_NAME_PREFIX)
                && pipeName.endsWith(MessageSendingPipe.INPUT_VALIDATOR_NAME_SUFFIX)) {
            checkpointName = INPUT_VALIDATOR_CHECKPOINT_NAME;
            String parentPipeName = getParentPipeName(pipeName, MessageSendingPipe.INPUT_VALIDATOR_NAME_PREFIX,
                    MessageSendingPipe.INPUT_VALIDATOR_NAME_SUFFIX);
            xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/pipe[@name=\""
                    + parentPipeName + "\"]/inputValidator";
        } else if (pipeName.startsWith(MessageSendingPipe.OUTPUT_VALIDATOR_NAME_PREFIX)
                && pipeName.endsWith(MessageSendingPipe.OUTPUT_VALIDATOR_NAME_SUFFIX)) {
            checkpointName = OUTPUT_VALIDATOR_CHECKPOINT_NAME;
            String parentPipeName = getParentPipeName(pipeName, MessageSendingPipe.OUTPUT_VALIDATOR_NAME_PREFIX,
                    MessageSendingPipe.OUTPUT_VALIDATOR_NAME_SUFFIX);
            xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/pipe[@name=\""
                    + parentPipeName + "\"]/outputValidator";
        } else if (pipeName.startsWith(MessageSendingPipe.INPUT_WRAPPER_NAME_PREFIX)
                && pipeName.endsWith(MessageSendingPipe.INPUT_WRAPPER_NAME_SUFFIX)) {
            checkpointName = INPUT_WRAPPER_CHECKPOINT_NAME;
            String parentPipeName = getParentPipeName(pipeName, MessageSendingPipe.INPUT_WRAPPER_NAME_PREFIX,
                    MessageSendingPipe.INPUT_WRAPPER_NAME_SUFFIX);
            xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/pipe[@name=\""
                    + parentPipeName + "\"]/inputWrapper";
        } else if (pipeName.startsWith(MessageSendingPipe.OUTPUT_WRAPPER_NAME_PREFIX)
                && pipeName.endsWith(MessageSendingPipe.OUTPUT_WRAPPER_NAME_SUFFIX)) {
            checkpointName = OUTPUT_WRAPPER_CHECKPOINT_NAME;
            String parentPipeName = getParentPipeName(pipeName, MessageSendingPipe.OUTPUT_WRAPPER_NAME_PREFIX,
                    MessageSendingPipe.OUTPUT_WRAPPER_NAME_SUFFIX);
            xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/pipe[@name=\""
                    + parentPipeName + "\"]/outputWrapper";
        }
    } else {
        xpathExpression = "//*/adapter[@name=\"" + adapterName + "\"]/pipeline/pipe[@name=\"" + pipeName
                + "\"]";
    }
    synchronized (pipeDescriptionCaches) {
        // When a configuration is changed (reloaded) a new configuration
        // object will be created. The old configuration object will be
        // removed from pipeDescriptionCaches by the garbage collection as
        // this is a WeakHashMap.
        Configuration configuration = pipeLine.getAdapter().getConfiguration();
        Map<String, PipeDescription> pipeDescriptionCache = pipeDescriptionCaches.get(configuration);
        if (pipeDescriptionCache == null) {
            pipeDescriptionCache = new HashMap<String, PipeDescription>();
            pipeDescriptionCaches.put(configuration, pipeDescriptionCache);
        }
        pipeDescription = pipeDescriptionCache.get(xpathExpression);
        if (pipeDescription == null) {
            pipeDescription = new PipeDescription();
            pipeDescription.setCheckpointName(getCheckpointName(pipe, checkpointName));
            if (xpathExpression == null) {
                pipeDescription.setDescription("Could not create xpath to extract pipe from configuration");
                pipeDescriptionCache.put(xpathExpression, pipeDescription);
            } else {
                Document document = documents.get(configuration);
                if (document == null) {
                    try {
                        document = DocumentHelper.parseText(configuration.getLoadedConfiguration());
                        documents.put(configuration, document);
                    } catch (DocumentException e) {
                        pipeDescription = new PipeDescription();
                        pipeDescription.setCheckpointName(getCheckpointName(pipe, checkpointName));
                        pipeDescription.setDescription("Could not parse configuration: " + e.getMessage());
                        pipeDescriptionCache.put(xpathExpression, pipeDescription);
                    }
                }
                if (document != null) {
                    Node node = document.selectSingleNode(xpathExpression);
                    if (node != null) {
                        StringWriter stringWriter = new StringWriter();
                        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
                        XMLWriter xmlWriter = new XMLWriter(stringWriter, outputFormat);
                        try {
                            xmlWriter.write(node);
                            xmlWriter.flush();
                            pipeDescription.setDescription(stringWriter.toString());
                        } catch (IOException e) {
                            pipeDescription.setDescription("IOException: " + e.getMessage());
                        }
                        addResourceNamesToPipeDescription((Element) node, pipeDescription);
                    } else {
                        pipeDescription.setDescription("Pipe not found in configuration.");
                    }
                }
            }
            pipeDescriptionCache.put(xpathExpression, pipeDescription);
        }
    }
    return pipeDescription;
}

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 {/* w  ww .ja  v  a2 s .  c o  m*/
        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:nl.tue.gale.common.GaleUtil.java

License:Open Source License

public static String serializeXML(Element element) {
    StringWriter out = new StringWriter();
    OutputFormat of = new OutputFormat();
    of.setExpandEmptyElements(true);//  ww  w . ja  v a2 s  .  com
    XMLWriter writer = new XMLWriter(out, of) {
        @Override
        protected void writeEmptyElementClose(String qualifiedName) throws IOException {
            if (omitCloseSet.contains(qualifiedName.toUpperCase())) {
                writer.write(" />");
            } else {
                super.writeEmptyElementClose(qualifiedName);
            }
        }
    };
    try {
        writer.write(element);
        writer.flush();
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalArgumentException("unable to serialize XML: " + e.getMessage());
    }
    return out.toString();
}

From source file:noThreads.Playlist.java

License:Open Source License

public void createPlaylist(String filePath)
        throws IOException, DocumentException, SAXException, ParserConfigurationException {
    String xmlObject, title = null;
    boolean flag = true;
    XspfPlaylist playlist = new XspfPlaylist();
    playlist.setTitle("My Playlist");
    playlist.setVersion("1");

    // create track list first
    XspfPlaylistTrackList tracks = new XspfPlaylistTrackList();

    for (int i = 0; i < eradioLinks.size(); i++) {
        if (flag == true) {
            flag = false;/*from  ww  w  .  ja  va2s. c o m*/
            title = org.apache.commons.lang3.StringEscapeUtils.escapeXml(eradioLinks.get(i));
        } else {
            flag = true;
            //escape the xml characters of the url
            xmlObject = org.apache.commons.lang3.StringEscapeUtils.escapeXml(eradioLinks.get(i));

            // now create track, set title and add to list
            XspfTrack track = new XspfTrack();
            track.setTitle(title);
            track.setLocation(xmlObject);
            tracks.addTrack(track);
        }
    }
    // add tracks to playlist
    playlist.setPlaylistTrackList(tracks);

    //or use Dom4j to output the playlist
    File file = new File(filePath);
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(file), format);
    Document doc = DocumentHelper.parseText(playlist.makeTextDocument());
    writer.write(doc);
    writer.close();
}

From source file:org.alfresco.module.org_alfresco_module_wcmquickstart.util.AssetSerializerXmlImpl.java

License:Open Source License

public void start(Writer underlyingWriter) throws AssetSerializationException {
    try {/*from  www  .j  av a 2s  . c  o m*/
        OutputFormat format = OutputFormat.createCompactFormat();
        format.setEncoding("UTF-8");

        writer = new XMLWriter(underlyingWriter, format);
        writer.startDocument();
        startElement("assets", EMPTY_ATTRIBUTES);
    } catch (Exception ex) {
        throw new AssetSerializationException(ex);
    }
}

From source file:org.alfresco.repo.admin.patch.util.ImportFileUpdater.java

License:Open Source License

/**
 * Get the writer for the import file/* w w  w  .j  av a  2s . c o  m*/
 * 
 * @param destination   the destination XML import file
 * @return            the XML writer
 */
private XMLWriter getWriter(String destination) {
    try {
        // Define output format
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setNewLineAfterDeclaration(false);
        format.setIndentSize(INDENT_SIZE);
        format.setEncoding(this.fileEncoding);

        return new XMLWriter(new FileOutputStream(destination), format);
    } catch (Exception exception) {
        throw new AlfrescoRuntimeException("Unable to create XML writer.", exception);
    }
}

From source file:org.alfresco.repo.exporter.ExporterComponent.java

License:Open Source License

/**
 * Create an XML Exporter that exports repository information to the specified
 * output stream in xml format./*from  w w  w.j av  a  2  s.  c  o  m*/
 * 
 * @param viewWriter  the output stream to write to
 * @param referenceType  the format of references to export
 * @return  the xml exporter
 */
private Exporter createXMLExporter(OutputStream viewWriter, ReferenceType referenceType) {
    // Define output format
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(indentSize);
    format.setEncoding("UTF-8");

    // Construct an XML Exporter
    try {
        XMLWriter writer = new XMLWriter(viewWriter, format);
        ViewXMLExporter exporter = new ViewXMLExporter(namespaceService, nodeService, searchService,
                dictionaryService, permissionService, writer);
        exporter.setReferenceType(referenceType);
        return exporter;
    } catch (UnsupportedEncodingException e) {
        throw new ExporterException("Failed to create XML Writer for export", e);
    } catch (Exception e) {
        throw new ExporterException("Failed to create XML Writer for export", e);
    }
}

From source file:org.alfresco.repo.importer.ExportSourceImporter.java

License:Open Source License

private XMLWriter createXMLExporter(Writer writer) {
    // Define output format
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);//from ww w .j a  v a2 s  . c om
    format.setEncoding("UTF-8");

    // Construct an XML Exporter

    XMLWriter xmlWriter = new XMLWriter(writer, format);
    return xmlWriter;
}

From source file:org.alfresco.repo.security.permissions.impl.model.PermissionModel.java

License:Open Source License

private InputStream processModelDocType(InputStream is, String dtdSchemaUrl)
        throws DocumentException, IOException {
    SAXReader reader = new SAXReader();
    // read document without validation
    Document doc = reader.read(is);
    DocumentType docType = doc.getDocType();
    if (docType != null) {
        // replace DOCTYPE setting the full path to the xsd
        docType.setSystemID(dtdSchemaUrl);
    } else {/* w ww .ja  va  2 s.c  o  m*/
        // add the DOCTYPE
        docType = new DefaultDocumentType(doc.getRootElement().getName(), dtdSchemaUrl);
        doc.setDocType(docType);
    }

    ByteArrayOutputStream fos = new ByteArrayOutputStream();
    try {
        OutputFormat format = OutputFormat.createPrettyPrint(); // uses UTF-8
        XMLWriter writer = new XMLWriter(fos, format);
        writer.write(doc);
        writer.flush();
    } finally {
        fos.close();
    }

    return new ByteArrayInputStream(fos.toByteArray());
}