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:com.globalsight.cxe.adapter.msoffice.ExcelRepairer.java

License:Apache License

private void repairExcelSharedStrings() throws Exception {
    File f = new File(path + "/xl/sharedStrings.xml");
    if (!f.exists())
        return;/*from   ww w .  j ava  2 s  . c  om*/

    String content = FileUtil.readFile(f, "utf-8");

    XmlParser parser = new XmlParser();
    org.dom4j.Document document = parser.parseXml(content);
    Element element = document.getRootElement();
    List<Element> rs = getElementByName(element, "r");
    for (Element r : rs) {
        @SuppressWarnings("rawtypes")
        List els = r.content();

        StringBuffer sb = new StringBuffer();
        Element wt = null;
        List<DefaultText> texts = new ArrayList<DefaultText>();

        for (Object el : els) {
            if (el instanceof DefaultText) {
                DefaultText text = (DefaultText) el;
                String s = text.getStringValue();
                if ("\n".equals(s))
                    continue;

                texts.add(text);
                sb.append(text.getStringValue());
            } else if (el instanceof Element) {
                Element elm = (Element) el;
                if ("t".equals(elm.getName())) {
                    wt = elm;
                    sb.append(elm.getStringValue());
                }
            }
        }

        if (wt == null) {
            wt = r.addElement("t");
            wt.addAttribute("xml:space", "preserve");
        }

        if (sb.length() == 0)
            sb.append(" ");

        wt.clearContent();
        wt.addText(sb.toString());

        for (DefaultText text : texts) {
            r.remove(text);
        }
    }

    Writer fileWriter = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
    XMLWriter xmlWriter = new XMLWriter(fileWriter);
    xmlWriter.write(document);
    xmlWriter.close();
}

From source file:com.globalsight.cxe.adapter.msoffice.WordRepairer.java

License:Apache License

private static void repairDocFiles(File f) throws Exception {
    if (!f.exists())
        return;//from  w  w  w .  j av  a 2s .  com

    StyleUtil util = StyleFactory.getStyleUtil(StyleFactory.DOCX);
    util.updateBeforeExport(f.getAbsolutePath());

    String content = FileUtil.readFile(f, "utf-8");

    XmlParser parser = new XmlParser();
    parser.setErrorHandler(new ErrorHandler() {
        @Override
        public void warning(SAXParseException arg0) throws SAXException {
            // Do nothing.
        }

        @Override
        public void fatalError(SAXParseException arg0) throws SAXException {
            return;
        }

        @Override
        public void error(SAXParseException e) throws SAXException {
            String s = e.getMessage();
            if (s.matches("Attribute .*? was already specified for element[\\s\\S]*"))
                return;

            throw new SAXException("XML parse error at\n  line " + e.getLineNumber() + "\n  column "
                    + e.getColumnNumber() + "\n  Message:" + e.getMessage());
        }
    });

    org.dom4j.Document document = parser.parseXml(content);
    Element element = document.getRootElement();

    forHyperlinkInWr(element);
    forHyperlinkInWt(element);
    forWtNotInWr(element);
    forTextInWr(element);
    forWrInWr(element);
    forTextInWp(element);
    forNodesInWt(element);

    Writer fileWriter = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
    XMLWriter xmlWriter = new XMLWriter(fileWriter);
    xmlWriter.write(document);
    xmlWriter.close();

    if (content.contains("</mc:AlternateContent>")) {
        forAlternateContent(f);
    }
}

From source file:com.globalsight.cxe.util.Dom4jUtil.java

License:Apache License

public static String formatXML(Document document, String charset) {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(charset);// ww w  .  ja  v a 2s .  com
    StringWriter sw = new StringWriter();
    XMLWriter xw = new XMLWriter(sw, format);
    try {
        xw.write(document);
        xw.flush();
        xw.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return document.asXML();
    }

    return sw.toString();
}

From source file:com.globalsight.diplomat.util.XmlUtil.java

License:Apache License

public static String format(String xml, EntityResolver entityResolver) {
    XmlParser parser = XmlParser.hire();
    if (entityResolver != null) {
        parser.setEntityResolver(entityResolver);
    }/*from w  w  w.  j ava2s  .c  om*/
    org.dom4j.Document dom = parser.parseXml(xml);
    OutputFormat format = new OutputFormat();
    format.setNewlines(true);
    format.setIndent(true);

    StringWriter writer = new StringWriter();
    XMLWriter xmlWriter = new XMLWriter(writer, format);
    try {
        xmlWriter.write(dom);
        xmlWriter.close();
    } catch (IOException e) {
        return xml;
    } finally {
        try {
            xmlWriter.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    return writer.getBuffer().toString();
}

From source file:com.globalsight.everest.workflow.WorkflowTemplateAdapter.java

License:Apache License

/**
 * Saves the workflow template xml to the file storage dir.
 * //from  w w w  .j ava2s .  co  m
 * @param p_document
 *            - the xml document of the workflow template.
 * @param p_templateName
 *            - the workflow template name.
 * 
 */
private void saveXmlToFileStore(Document p_document, String p_templateName) {
    OutputFormat format = OutputFormat.createCompactFormat();
    XMLWriter writer = null;
    try {
        String aaa = AmbFileStoragePathUtils.getWorkflowTemplateXmlDir().getAbsolutePath();
        writer = new XMLWriter(
                new FileOutputStream(AmbFileStoragePathUtils.getWorkflowTemplateXmlDir().getAbsolutePath()
                        + File.separator + p_templateName + WorkflowConstants.SUFFIX_XML),
                format);
        writer.write(p_document);
    } catch (Exception e) {
        c_category.info("Exception occurs when saving the template xml to file storage");
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:com.globalsight.smartbox.bussiness.process.Usecase02PreProcess.java

License:Apache License

/**
 * Convert csv/txt file to xml file// w  w  w  .j  a  va2 s .  c om
 * 
 * @param format
 * @param originFile
 * @return
 */
private String convertToXML(String format, File originFile) {
    String fileName = originFile.getName();
    // Save the converted file to temp directory
    String xmlFilePath = jobInfo.getTempFile() + File.separator
            + fileName.substring(0, fileName.lastIndexOf(".")) + ".xml";
    File xmlFile = new File(xmlFilePath);
    FileReader fr = null;
    FileInputStream fis = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    XMLWriter output = null;
    try {
        String encoding = FileUtil.guessEncoding(originFile);

        Document document = DocumentHelper.createDocument();
        Element aElement = document.addElement("root");
        aElement.addAttribute("BomInfo", encoding == null ? "" : encoding);

        if (encoding == null) {
            fr = new FileReader(originFile);
            br = new BufferedReader(fr);
        } else {
            fis = new FileInputStream(originFile);
            isr = new InputStreamReader(fis, encoding);
            br = new BufferedReader(isr);
        }

        String str;
        if ("csv".equals(format)) {
            while ((str = br.readLine()) != null) {
                String[] values = str.split("\",\"");
                values[0] = values[0].substring(1);
                values[10] = values[10].substring(0, values[10].length() - 1);
                writeRow(aElement, values);
            }
        } else {
            while ((str = br.readLine()) != null) {
                str = str + "*";
                String[] values = str.split("\\|");
                values[10] = values[10].substring(0, values[10].lastIndexOf("*"));
                writeRow(aElement, values);
            }
        }

        output = new XMLWriter(new FileOutputStream(xmlFile));
        output.write(document);
    } catch (Exception e) {
        String message = "Failed to convert to XML, File Name: " + originFile.getName();
        LogUtil.fail(message, e);
        return null;
    } finally {
        try {
            if (output != null) {
                output.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
            if (fr != null) {
                fr.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return xmlFile.getPath();
}

From source file:com.googlecode.fascinator.common.sax.SafeSAXReader.java

License:Open Source License

/**
 * Convert node to string//from w  ww. j ava  2 s .  c om
 * 
 * @param outDoc Node to be converted
 * @return String of the converted node
 * @throws IOException if the conversion fail
 */
public String docToString(Node outDoc) throws IOException {
    Writer osw = new StringWriter();
    OutputFormat opf = new OutputFormat("", false, "UTF-8");
    opf.setSuppressDeclaration(true);
    opf.setExpandEmptyElements(true);
    XMLWriter writer = new XMLWriter(osw, opf);
    writer.setEscapeText(false);
    writer.write(outDoc);
    writer.close();

    return osw.toString();
}

From source file:com.googlecode.fascinator.common.sax.SafeSAXReader.java

License:Open Source License

/**
 * Convert node to stream//w  w  w  . j  ava  2  s  .c  om
 * 
 * @param outDoc Node to be converted
 * @param outStream output stream of the converted node
 * @throws IOException if the conversion fail
 */
public void docToStream(Node outDoc, OutputStream outStream) throws IOException {
    OutputFormat opf = new OutputFormat("", false, "UTF-8");
    opf.setSuppressDeclaration(true);
    opf.setExpandEmptyElements(true);
    XMLWriter writer = new XMLWriter(outStream, opf);
    writer.setEscapeText(false);
    writer.write(outDoc);
    writer.close();
}

From source file:com.hihframework.osplugins.dom4j.XmlParseUtil.java

License:Apache License

/**
 * XML?? XML???/*w w w.  j av a2  s  .  co m*/
 *
 * @param document
 *            ?
 * @param file
 *            ?XML
 */
public void writeXml(Document document, File file) {
    try {
        //?
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter output = new XMLWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"), format);
        output.write(document);
        output.flush();
        output.close();
    } catch (IOException e) {
        log.info(e.getMessage());
    }

}

From source file:com.hihframework.osplugins.dom4j.XmlParseUtil.java

License:Apache License

/**
 * XML?? ?/*from  w  w w . j a  va  2 s.c  o m*/
 *
 * @param document
 *            ?
 * @param file
 *            ?XML
 */
public void writeXml(Document document) {
    try {
        //?
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter output = new XMLWriter(System.out, format);
        //XMLWriter output = new XMLWriter(new FileWriter(file));
        output.write(document);
        output.flush();
        output.close();
    } catch (IOException e) {
        log.info(e.getMessage());
    }

}