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:W3cDocument.java

License:Open Source License

public static String getXml(org.w3c.dom.Document w3cDoc, String encoding) {
    try {//from  w  w w .java  2s  . c  o  m
        org.dom4j.io.DOMReader xmlReader = new org.dom4j.io.DOMReader();
        org.dom4j.Document dom4jDoc = xmlReader.read(w3cDoc);

        //?
        OutputFormat format = new OutputFormat();//("    ", true);
        //?
        format.setEncoding(encoding);
        //format.setOmitEncoding(true);
        format.setSuppressDeclaration(true);
        //xml
        StringWriter out = new StringWriter();
        XMLWriter xmlWriter = new XMLWriter(out, format);
        xmlWriter.setEscapeText(true);

        //?doc
        xmlWriter.write(dom4jDoc);
        xmlWriter.flush();
        //??printWriter
        String xml = out.toString();
        out.close();
        return xml;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:InitializeDB.java

License:Open Source License

public static void clearEntryWithVulsoft(String filename) {

    try {/*from   w w  w  . j a  va2s.c  om*/

        SAXReader saxReader = new SAXReader();

        Document document = saxReader.read(filename);

        List soft = document

                .selectNodes("/*[local-name(.)='nvd']/*[local-name(.)='entry']/*[local-name(.)='vuln_soft']");

        Iterator sft = soft.iterator();

        Element nvd = (Element) document

                .selectSingleNode("/*[local-name(.)='nvd']");

        while (sft.hasNext()) {

            Element vsft = (Element) sft.next();

            nvd.remove(vsft.getParent());

            XMLWriter output = new XMLWriter(new FileWriter(filename));//

            output.write(document);

            output.flush();

            output.close();

        }

    } catch (Exception e) {

        e.printStackTrace();

    }

}

From source file:VersionRelease.java

License:Open Source License

public void run() {
    processDir(jbossHome);//www . ja  va  2 s. co m
    try {
        DocumentFactory df = DocumentFactory.getInstance();
        Document doc = df.createDocument();
        Element root = doc.addElement("jar-versions");
        Iterator iter = jars.iterator();
        while (iter.hasNext()) {
            JarInfo info = (JarInfo) iter.next();
            info.writeXML(root);
        }

        File versionsXml = new File(jbossHome, "jar-versions.xml");
        FileWriter versionInfo = new FileWriter(versionsXml);
        OutputFormat outformat = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(versionInfo, outformat);
        writer.setEscapeText(true);
        writer.write(doc);
        writer.flush();
        versionInfo.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:au.com.acegi.xmlformat.FormatUtil.java

License:Apache License

/**
 * Ingest an input stream, writing formatted XML to the output stream. The
 * caller is responsible for closing the input and output streams. Any errors
 * in the input stream will cause an exception and the output stream should
 * not be relied upon.//from   w  w  w.j a  va 2  s  .  com
 *
 * @param in  input XML stream
 * @param out output XML stream
 * @param fmt format configuration to apply
 * @throws DocumentException if input XML could not be parsed
 * @throws IOException       if output XML stream could not be written
 */
static void format(final InputStream in, final OutputStream out, final OutputFormat fmt)
        throws DocumentException, IOException {
    final SAXReader reader = new SAXReader();
    reader.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(final String publicId, final String systemId)
                throws SAXException, IOException {
            return new InputSource(new StringReader(""));
        }
    });
    final Document xmlDoc = reader.read(in);

    final XMLWriter xmlWriter = new XMLWriter(out, fmt);
    xmlWriter.write(xmlDoc);
    xmlWriter.flush();
}

From source file:be.hikage.maven.plugin.xmlmerge.MergeXmlMojo.java

License:Apache License

private void writeMergedXml(File baseFile, Document base, StringBuilder prologHeader) throws IOException {
    FileOutputStream fos = new FileOutputStream(baseFile);

    if (processProlog && prologHeader != null && StringUtils.isNotEmpty(prologHeader.toString())) {
        fos.write(prologHeader.toString().getBytes());
    }/*from  w ww  .  j  a  v  a 2 s .com*/

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setSuppressDeclaration(true);
    format.setNewLineAfterDeclaration(false);
    XMLWriter writer = new XMLWriter(fos, format);
    writer.write(base);
    writer.flush();
    writer.close();

}

From source file:bio.pih.genoogle.interfaces.Console.java

public void execute(InputStreamReader isr, boolean echo) {
    BufferedReader lineReader = new BufferedReader(isr);

    boolean executePrev = false;
    String prev = null;/*w  w w .  ja v a 2s. com*/
    String line = null;

    Map<Parameter, Object> consoleParameters = SearchParams.getSearchParamsMap();

    System.out.print("genoogle console> ");

    try {
        while (running && (executePrev || (line = lineReader.readLine()) != null)) {
            long begin = System.currentTimeMillis();
            long end = -1;

            if (echo) {
                System.out.println(line);
            }
            try {
                line = line.trim();
                if (line.length() == 0) {
                    continue;
                }

                if (executePrev) {
                    if (prev == null) {
                        System.out.println("no previous commands.");
                        executePrev = false;
                        continue;
                    }
                    line = prev;
                    System.out.println(line);
                    executePrev = false;
                }

                String[] commands = line.split("[ \t]+");
                if (commands[0].equals(SEARCH)) {
                    if (commands.length >= 3) {
                        String db = commands[1];
                        String queryFile = commands[2];

                        Map<Parameter, Object> searchParameters = Maps.newHashMap();
                        searchParameters.putAll(consoleParameters);

                        for (int i = 4; i < commands.length; i++) {
                            String command = commands[i];
                            String[] split = command.split("=");
                            if (split.length != 2) {
                                System.out.println(command + " is an invalid parameter.");
                            }
                            String paramName = split[0];
                            String paramValue = split[1];

                            Parameter p = Parameter.getParameterByName(paramName);
                            if (p == null) {
                                System.out.println(paramName + " is an invalid parameter name");
                                continue;
                            }
                            Object value = p.convertValue(paramValue);
                            searchParameters.put(p, value);
                        }

                        if (new File(queryFile).exists()) {
                            BufferedReader in = new BufferedReader(new FileReader(queryFile));
                            profileLogger.info("<" + line + ">");
                            List<SearchResults> results = genoogle.doBatchSyncSearch(in, db, searchParameters);
                            end = System.currentTimeMillis();
                            long total = end - begin;
                            profileLogger.info("</" + line + ":" + total + ">");
                            Document document = Output.genoogleOutputToXML(results);
                            OutputFormat outformat = OutputFormat.createPrettyPrint();
                            outformat.setTrimText(false);
                            outformat.setEncoding("UTF-8");
                            OutputStream os;
                            if (commands.length >= 4) {
                                String outputFile = commands[3];
                                os = new FileOutputStream(new File(outputFile + ".xml"));
                            } else {
                                os = System.out;
                            }
                            XMLWriter writer = new XMLWriter(os, outformat);
                            writer.write(document);
                            writer.flush();

                        } else {
                            System.err.println("query file: " + queryFile + " does not exist.");
                        }

                    } else {
                        System.out.println("SEARCH DB QUERY_FILE OUTPUT_FILE");
                    }

                } else if (commands[0].equals(GC)) {
                    System.gc();

                } else if (commands[0].equals(LIST)) {
                    for (AbstractSequenceDataBank db : genoogle.getDatabanks()) {
                        System.out.println(db.getName() + " - " + db.getAlphabet().getName() + "("
                                + db.getClass().getName() + ")");
                    }

                } else if (commands[0].equals(DEFAULT)) {
                    System.out.println(genoogle.getDefaultDatabank());

                } else if (commands[0].equals(PARAMETERS)) {
                    for (Entry<Parameter, Object> entry : consoleParameters.entrySet()) {
                        System.out.println(entry.getKey().getName() + "=" + entry.getValue());
                    }

                } else if (commands[0].equals(SET)) {
                    String[] split = commands[1].split("=");
                    if (split.length != 2) {
                        System.out.println(commands[1] + " is invalid set parameters option.");
                    }
                    String paramName = split[0];
                    String paramValue = split[1];

                    Parameter p = Parameter.getParameterByName(paramName);
                    if (p == null) {
                        System.out.println(paramName + " is an invalid parameter name");
                        continue;
                    }
                    Object value = p.convertValue(paramValue);
                    consoleParameters.put(p, value);
                    System.out.println(paramName + " is " + paramValue);

                } else if (commands[0].equals(SEQ)) {
                    if (commands.length != 3) {
                        System.out.println("SEQ database id");
                        continue;
                    }

                    String db = commands[1];
                    int id = Integer.parseInt(commands[2]);

                    String seq = genoogle.getSequence(db, id);

                    System.out.println(seq);

                } else if (commands[0].equals(PREV) || commands[0].equals("p")) {
                    executePrev = true;
                    continue;

                } else if (commands[0].endsWith(BATCH)) {
                    if (commands.length != 2) {
                        System.out.println("BATCH <batchfile>");
                        continue;
                    }

                    File f = new File(commands[1]);
                    execute(new InputStreamReader(new FileInputStream(f)), true);
                    end = System.currentTimeMillis();

                } else if (commands[0].equals(EXIT)) {
                    genoogle.finish();

                } else if (commands[0].equals(HELP)) {
                    System.out.println("Commands:");
                    System.out.println(
                            "search <data bank> <input file> <output file> <parameters>: does the search");
                    System.out.println("list : lists the data banks.");
                    System.out.println("parameters : shows the search parameters and their values.");
                    System.out.println("set <parameter>=<value> : set the parameters value.");
                    System.out.println("gc : executes the java garbage collection.");
                    System.out.println("prev or l: executes the last command.");
                    System.out.println("batch <batch file> : runs the commands listed in this batch file.");
                    System.out.println("help: this help.");
                    System.out.println("exit : finish Genoogle execution.");
                    System.out.println();
                    System.out.println("Search Parameters:");

                    System.out.println(
                            "MaxSubSequenceDistance : maximum index entries distance to be considered in the same HSPs.");
                    System.out.println("SequencesExtendDropoff : drop off for sequence extension.");
                    System.out.println("MaxHitsResults : maximum quantity of returned results.");
                    System.out.println("QuerySplitQuantity : how many slices the input query will be divided.");
                    System.out.println("MinQuerySliceLength : minimum size of each input query slice.");
                    System.out.println(
                            "MaxThreadsIndexSearch : quantity of threads which will be used to index search.");
                    System.out.println(
                            "MaxThreadsExtendAlign : quantity of threads which will be used to extend and align the HSPs.");
                    System.out.println("MatchScore : score when has a match at the alignment.");
                    System.out.println("MismatchScore : score when has a mismatch at the alignment.");
                } else {
                    System.err.println("Unknow command: " + commands[0]);
                    continue;
                }

                prev = line;
                System.out.print("genoogle console> ");
            } catch (IndexOutOfBoundsException e) {
                logger.fatal(e.getStackTrace(), e);
                continue;
            } catch (UnsupportedEncodingException e) {
                logger.fatal(e.getStackTrace(), e);
                continue;
            } catch (FileNotFoundException e) {
                logger.fatal(e.getStackTrace(), e);
                continue;
            } catch (ParseException e) {
                logger.fatal(e.getStackTrace(), e);
                continue;
            } catch (IOException e) {
                logger.fatal(e.getStackTrace(), e);
                continue;
            } catch (NoSuchElementException e) {
                logger.fatal(e.getStackTrace(), e);
                continue;
            } catch (UnknowDataBankException e) {
                logger.error(e.getStackTrace(), e);
                continue;
            } catch (InterruptedException e) {
                logger.fatal(e.getStackTrace(), e);
                continue;
            } catch (ExecutionException e) {
                logger.fatal(e.getStackTrace(), e);
                continue;
            } catch (IllegalSymbolException e) {
                logger.fatal(e.getStackTrace(), e);
                continue;
            }
        }
    } catch (IOException e) {
        logger.fatal(e.getStackTrace(), e);
        return;
    }
}

From source file:cn.feng.web.ssm.excel.controller.StringUtils.java

License:Apache License

/**
 * /*from   w ww.ja  v a2 s  . c o  m*/
 * dom4j 
 * @param document
 * @return
 */
public static String document2str(Document document, String chartset) {
    String result = "";
    OutputFormat format;
    ByteArrayOutputStream out;
    try {
        format = OutputFormat.createPrettyPrint();
        format.setEncoding(chartset);
        out = new ByteArrayOutputStream();
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(document);
        writer.flush();
        writer.close();
        result = out.toString(format.getEncoding());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:cn.mario256.blog.util.SystemUtils.java

License:Open Source License

/**
 * /*from  w ww.  jav a 2 s. c o  m*/
 * 
 * @param setting
 *            
 */
@SuppressWarnings("unchecked")
public static void setSetting(Setting setting) {
    Assert.notNull(setting);

    try {
        File turingXmlFile = new ClassPathResource(CommonAttributes.TURING_XML_PATH).getFile();
        Document document = new SAXReader().read(turingXmlFile);
        List<org.dom4j.Element> elements = document.selectNodes("/turing/setting");
        for (org.dom4j.Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = BEAN_UTILS.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }

        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            xmlWriter = new XMLWriter(new FileOutputStream(turingXmlFile), outputFormat);
            xmlWriter.write(document);
            xmlWriter.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            try {
                if (xmlWriter != null) {
                    xmlWriter.close();
                }
            } catch (IOException e) {
            }
        }
        Ehcache cache = CACHE_MANAGER.getEhcache(Setting.CACHE_NAME);
        String cacheKey = "setting";
        cache.put(new Element(cacheKey, setting));
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.alibaba.citrus.springext.support.SchemaUtil.java

License:Open Source License

/** DOM */
public static void writeDocument(Document doc, Writer writer, String charset) throws IOException {
    charset = defaultIfEmpty(trimToNull(charset), "UTF-8");

    OutputFormat format = OutputFormat.createPrettyPrint();

    format.setEncoding(charset);/*from w  w w  .  j av  a2 s  .c o  m*/
    format.setIndent(true);
    format.setIndentSize(4);

    XMLWriter xmlWriter = new XMLWriter(writer, format);
    xmlWriter.write(doc);
    xmlWriter.flush();
}

From source file:com.alibaba.citrus.springext.util.ConvertToUnqualifiedStyle.java

License:Open Source License

private static void writeDocument(Document doc, OutputStream stream) throws IOException {
    String charset = "UTF-8";
    Writer writer = new OutputStreamWriter(stream, charset);

    OutputFormat format = new OutputFormat();

    format.setEncoding(charset);/*from   w w  w  .  j  av a2  s . c  o  m*/

    XMLWriter xmlWriter = new XMLWriter(writer, format);
    xmlWriter.write(doc);
    xmlWriter.flush();
}