Example usage for org.dom4j.io XMLWriter flush

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

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the underlying Writer

Usage

From source file:org.snipsnap.util.XMLSnipRepair.java

License:Open Source License

public static void repair(File input, File output, File webAppDir) {
    System.err.println("STEP 1: parsing input file ...");
    Document document = null;/*from  w  ww .  jav a2 s  . co m*/
    try {
        document = load(input);
    } catch (Exception e) {
        System.err.println("Unable to read input document: " + e);
        System.err.println(
                "This is usually the case for illegal XML characters, please manually edit the file and remove them.");
        System.exit(0);
    }

    System.err.println("STEP 2: checking SnipSpace consistency ...");
    Document repaired = repair(document, webAppDir);

    System.err.println("STEP 3: writing output file ...");
    OutputFormat outputFormat = new OutputFormat();
    outputFormat.setEncoding("UTF-8");
    outputFormat.setNewlines(true);
    try {
        XMLWriter xmlWriter = new XMLWriter(
                null == output ? System.out : (OutputStream) new FileOutputStream(output));
        xmlWriter.write(repaired);
        xmlWriter.flush();
        xmlWriter.close();
    } catch (Exception e) {
        System.err.println("Error: unable to write data: " + e);
    }
    System.err.println("Finished.");
}

From source file:org.snipsnap.xmlrpc.SnipSnapHandler.java

License:Open Source License

public String getSnipAsXml(String name) {
    Snip snip = space.load(name);/*from   w  w w.  ja  v  a  2 s . c o m*/
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    OutputFormat outputFormat = OutputFormat.createCompactFormat();
    outputFormat.setEncoding("UTF-8");
    try {
        XMLWriter writer = new XMLWriter(out, outputFormat);
        writer.write(SnipSerializer.getInstance().serialize(snip));
        writer.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return out.toString();
}

From source file:org.springframework.extensions.webscripts.AbstractStore.java

License:Apache License

public void createDocuments(List<Pair<String, Document>> pathContents) throws IOException {
    for (Pair<String, Document> pathContent : pathContents) {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setSuppressDeclaration(false);

        StringBuilderWriter writer = new StringBuilderWriter(1024);
        XMLWriter xmlWriter = new XMLWriter(writer, format);
        xmlWriter.write(pathContent.getSecond());
        xmlWriter.flush();
        writer.close();//from  ww w.j  av  a 2 s . c o  m
        createDocument(pathContent.getFirst(), writer.toString());
    }
}

From source file:org.springframework.extensions.webscripts.RemoteStore.java

License:Apache License

@Override
public void createDocuments(List<Pair<String, Document>> pathContents) throws IOException {
    Document master = DocumentHelper.createDocument();
    Element docEl = master.addElement("master");
    for (Pair<String, Document> pathContent : pathContents) {
        Element document = docEl.addElement("document");
        final String storePath = getStorePath();
        document.addAttribute("path",
                (storePath.equals("/") ? storePath : '/' + storePath) + pathContent.getFirst());
        document.add(pathContent.getSecond().getRootElement().createCopy());
    }/*w  w  w  .j ava  2  s.  com*/
    ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setSuppressDeclaration(false);
    XMLWriter xmlWriter = new XMLWriter(out, format);
    xmlWriter.write(master);
    xmlWriter.flush();
    out.close();
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    Response res = callPost(buildEncodeCall(API_CREATE_MULTI, ""), in);

    if (logger.isDebugEnabled())
        logger.debug(
                "RemoteStore.createDocuments() " + pathContents.size() + " = " + res.getStatus().getCode());

    if (Status.STATUS_OK != res.getStatus().getCode()) {
        throw new IOException("Unable to create documents in remote store: " + this.getEndpoint()
                + " due to error: " + res.getStatus().getCode() + " " + res.getStatus().getMessage());
    }
}

From source file:org.talend.componentdesigner.manager.ComponentFolderManager.java

License:Open Source License

/**
 * DOC slanglois Comment method "writeXMLContent".
 * /*  ww w . j  av a2 s  .  c o m*/
 * @param iFile
 * @param document
 * @param enCode
 * @throws CoreException
 */
private void writeXMLContent(IFile iFile, Document document, String enCode) throws CoreException {
    PrintWriter pw = null;
    XMLWriter writer = null;
    byte[] byteArray = null;

    // get xml content as inputstream
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = null;
    try {
        transformer = tf.newTransformer();
    } catch (TransformerConfigurationException e1) {
        // e1.printStackTrace();
        org.talend.componentdesigner.exception.ExceptionHandler.process(e1);
    }
    DOMSource source = new DOMSource(document);
    transformer.setOutputProperty(OutputKeys.ENCODING, enCode);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

    ByteArrayOutputStream sw = new ByteArrayOutputStream();
    pw = new PrintWriter(sw);
    StreamResult result = new StreamResult(pw);
    try {
        transformer.transform(source, result);
    } catch (TransformerException e1) {
        // e1.printStackTrace();
        org.talend.componentdesigner.exception.ExceptionHandler.process(e1);
    }
    try {
        sw.flush();
    } catch (IOException e1) {
        // e1.printStackTrace();
        org.talend.componentdesigner.exception.ExceptionHandler.process(e1);
    } finally {
        if (pw != null) {
            pw.close();
        }
    }
    byteArray = sw.toByteArray();

    // format the xml content
    SAXReader saxReader = new SAXReader();

    org.dom4j.Document dom4jDocument = null;
    try {
        dom4jDocument = saxReader.read(new ByteArrayInputStream(byteArray));
    } catch (DocumentException e1) {
        // e1.printStackTrace();
        org.talend.componentdesigner.exception.ExceptionHandler.process(e1);
    }

    /** format the output like the webBrowser */

    OutputFormat format = OutputFormat.createPrettyPrint();

    /** give the xml encoding */

    format.setEncoding(enCode);

    sw = new ByteArrayOutputStream();

    try {
        writer = new XMLWriter(sw, format);
    } catch (UnsupportedEncodingException e1) {
        // e1.printStackTrace();
        org.talend.componentdesigner.exception.ExceptionHandler.process(e1);
    }

    try {
        writer.write(dom4jDocument);
        writer.flush();
    } catch (IOException e1) {
        // e1.printStackTrace();
        org.talend.componentdesigner.exception.ExceptionHandler.process(e1);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                // e.printStackTrace();
                org.talend.componentdesigner.exception.ExceptionHandler.process(e);
            }
        }
    }
    byteArray = sw.toByteArray();

    // write content
    iFile.setContents(new ByteArrayInputStream(byteArray), true, false, null);

}

From source file:org.talend.core.model.genhtml.XMLHandler.java

License:Open Source License

/**
 * Generates xml file base on inputted path, file path and an instance of <code>Document</code>
 * // w ww  . ja  v  a  2 s  .c  om
 * @param tempFolderPath
 * @param filePath
 * @param document
 */
public static void generateXMLFile(String tempFolderPath, String filePath, Document document) {
    XMLWriter output = null;
    FileOutputStream out = null;
    Writer writer = null;

    try {
        // OutputFormat format = OutputFormat.createPrettyPrint();
        out = new java.io.FileOutputStream(filePath);
        writer = new OutputStreamWriter(out, "UTF-8"); //$NON-NLS-1$

        OutputFormat format = OutputFormat.createPrettyPrint();
        output = new XMLWriter(writer, format) {

            /*
             * (non-Javadoc)
             * 
             * @see org.dom4j.io.XMLWriter#writeDeclaration()
             */
            @Override
            protected void writeDeclaration() throws IOException {
                OutputFormat formatTmp = this.getOutputFormat();
                String encoding = formatTmp.getEncoding();

                // Only print of declaration is not suppressed
                if (!formatTmp.isSuppressDeclaration()) {
                    // Assume 1.0 version
                    if (encoding.equals("UTF8")) { //$NON-NLS-1$
                        writer.write("<?xml version=\"1.1\""); //$NON-NLS-1$

                        if (!formatTmp.isOmitEncoding()) {
                            writer.write(" encoding=\"UTF-8\""); //$NON-NLS-1$
                        }

                        writer.write("?>"); //$NON-NLS-1$
                    } else {
                        writer.write("<?xml version=\"1.1\""); //$NON-NLS-1$

                        if (!formatTmp.isOmitEncoding()) {
                            writer.write(" encoding=\"" + encoding + "\""); //$NON-NLS-1$ //$NON-NLS-2$
                        }

                        writer.write("?>"); //$NON-NLS-1$
                    }

                    if (formatTmp.isNewLineAfterDeclaration()) {
                        println();
                    }
                }
            }
        };
        output.setMaximumAllowedCharacter(127);
        output.write(document);
        output.flush();
    } catch (Exception e) {
        ExceptionHandler.process(e);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (Exception e) {
                ExceptionHandler.process(e);
            }
        }
        if (writer != null) {
            try {
                writer.close();
            } catch (Exception e) {
                ExceptionHandler.process(e);
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
                ExceptionHandler.process(e);
            }
        }

    }
}

From source file:org.talend.repository.ui.wizards.exportjob.scriptsmanager.JobJavaScriptsWSManager.java

License:Open Source License

/**
 * DOC x Comment method "genWebInfoForder".
 * //from w w w  .j  a va 2  s . c  om
 * @param list
 */
private void editWSDDFile(ProcessItem processItem) {
    String projectName = getCorrespondingProjectName(processItem);
    String selectedProcessVersion = processItem.getProperty().getVersion();
    if (!isMultiNodes() && this.getSelectedJobVersion() != null) {
        selectedProcessVersion = this.getSelectedJobVersion();
    }

    String jobFolderName = JavaResourcesHelper.getJobFolderName(escapeFileNameSpace(processItem),
            selectedProcessVersion);

    String deployFileName = getTmpFolder() + PATH_SEPARATOR + projectName + PATH_SEPARATOR + jobFolderName
            + PATH_SEPARATOR + "deploy.wsdd"; //$NON-NLS-1$
    String serverConfigFile = getTmpFolder() + PATH_SEPARATOR + "server-config.wsdd"; //$NON-NLS-1$

    File deployFile = new File(deployFileName);
    if (!deployFile.exists()) {
        log.error(org.talend.repository.i18n.Messages.getString("JobJavaScriptsWSManager.errorMessage")); //$NON-NLS-1$
        return;
    }
    // edit the server-config.wsdd file
    try {

        File wsddFile = new File(serverConfigFile);
        BufferedReader reader = new BufferedReader(new FileReader(wsddFile));

        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read(reader);

        BufferedReader wsdlreader = new BufferedReader(new FileReader(deployFile));
        SAXReader wsdlsaxReader = new SAXReader();
        Document wsdldoc = wsdlsaxReader.read(wsdlreader);
        Element wsdlroot = wsdldoc.getRootElement();
        Element element = wsdlroot.element("service"); //$NON-NLS-1$

        List<Element> elements = element.elements("arrayMapping"); //$NON-NLS-1$
        for (Element item : elements) {
            Attribute attribute = item.attribute("qname"); //$NON-NLS-1$
            item.remove(attribute);
            attribute.setValue(attribute.getValue().replaceFirst(">", "")); //$NON-NLS-1$ //$NON-NLS-2$
            item.add(attribute);
        }

        Element root = doc.getRootElement();
        List<Node> content = root.content();
        for (int i = 0; i < content.size(); i++) {
            Node n = content.get(i);
            if (n instanceof Element) {
                if (n.getName().equals("transport")) { //$NON-NLS-1$
                    content.add(i - 1, element);
                    break;
                }
            }
        }

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(serverConfigFile), "UTF-8")); //$NON-NLS-1$

        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter output = new XMLWriter(writer, format);
        output.write(doc);
        output.flush();
        output.close();

    } catch (Exception e) {
        ExceptionHandler.process(e);
    }
}

From source file:org.tsp.bws.BWSDocument.java

License:Open Source License

/** 
 * Prints the current document to the console via the dom4j XMLWriter 
 *///from w w w  .ja  v  a  2 s  . c o m
public void printDocumentSource() {
    // use pretty printing
    OutputFormat outformat = new OutputFormat();// = OutputFormat.createPrettyPrint();
    //      outformat.setEnconding();
    // use standard encoding, else: outformat.setEncoding(String encodingScheme)
    try {
        XMLWriter writer = new XMLWriter(System.out);
        writer.write(this.xmlDocument);
        writer.flush();
        // go to the next line
        System.out.println("\n");
    } catch (Exception e) {
        System.out.println("[Error] Exception printing the document, wrong encoding scheme?");
        e.printStackTrace();
    }
}

From source file:org.unitime.banner.queueprocessor.util.ClobTools.java

License:Apache License

public static Clob documentToCLOB(Document document, Connection conn) throws IOException, SQLException {
    Clob clob = conn.createClob();
    XMLWriter writer = new XMLWriter(clob.setCharacterStream(1l), OutputFormat.createCompactFormat());
    writer.write(document);//from  w  w w  . java  2 s.c o m
    writer.flush();
    writer.close();
    return clob;
}

From source file:org.unitime.commons.hibernate.blob.XmlBlobType.java

License:Open Source License

public void nullSafeSet(PreparedStatement ps, Object value, int index, SessionImplementor session)
        throws SQLException, HibernateException {
    if (value == null) {
        ps.setNull(index, sqlTypes()[0]);
    } else {/*from ww w  .  j av  a 2s  . c o  m*/
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            XMLWriter writer = new XMLWriter(new GZIPOutputStream(bytes), OutputFormat.createCompactFormat());
            writer.write((Document) value);
            writer.flush();
            writer.close();
            ps.setBinaryStream(index, new ByteArrayInputStream(bytes.toByteArray(), 0, bytes.size()),
                    bytes.size());
        } catch (IOException e) {
            throw new HibernateException(e.getMessage(), e);
        }
    }
}