Example usage for org.dom4j.io OutputFormat createPrettyPrint

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

Introduction

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

Prototype

public static OutputFormat createPrettyPrint() 

Source Link

Document

A static helper method to create the default pretty printing format.

Usage

From source file:architecture.ee.component.core.lifecycle.RepositoryImpl.java

License:Apache License

public ApplicationProperties getSetupApplicationProperties() {
    if (setupProperties == null) {
        try {//from  w  w w  .  ja va 2 s  .  c o m
            File file = getFile(ApplicationConstants.DEFAULT_STARTUP_FILENAME);
            if (!file.exists()) {
                boolean error = false;
                // create default file...
                log.debug("No startup file now create !!!");
                Writer writer = null;
                try {

                    writer = new OutputStreamWriter(new FileOutputStream(file),
                            ApplicationConstants.DEFAULT_CHAR_ENCODING);
                    XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint());
                    StringBuilder sb = new StringBuilder();
                    org.dom4j.Document document = org.dom4j.DocumentHelper.createDocument();
                    org.dom4j.Element root = document.addElement("startup-config");
                    // setup start
                    // ------------------------------------------------------------
                    org.dom4j.Element setupNode = root.addElement("setup");
                    setupNode.addElement("complete").setText("false");
                    // setup end
                    // --------------------------------------------------------------
                    // license start
                    org.dom4j.Element licenseNode = root.addElement("license");
                    // license end
                    // view start
                    org.dom4j.Element viewNode = root.addElement("view");
                    org.dom4j.Element renderNode = viewNode.addElement("render");
                    org.dom4j.Element freemarkerNode = renderNode.addElement("freemarker");
                    freemarkerNode.addElement("enabled").setText("true");
                    freemarkerNode.addElement("source").addElement("location");
                    org.dom4j.Element velocityNode = renderNode.addElement("velocity");
                    velocityNode.addElement("enabled").setText("false");
                    // view end
                    // security start
                    org.dom4j.Element securityNode = root.addElement("security");
                    securityNode.addElement("authentication").addElement("encoding").addElement("algorithm")
                            .setText("SHA-256");
                    // security end

                    // scripting start
                    org.dom4j.Element scriptingNode = root.addElement("scripting");
                    org.dom4j.Element groovyNode = scriptingNode.addElement("groovy");
                    groovyNode.addElement("debug").setText("false");
                    org.dom4j.Element sourceGroovyNode = groovyNode.addElement("source");
                    sourceGroovyNode.addElement("location");
                    sourceGroovyNode.addElement("encoding").setText(ApplicationConstants.DEFAULT_CHAR_ENCODING);
                    sourceGroovyNode.addElement("recompile").setText("true");
                    // scripting end
                    // database start
                    org.dom4j.Element databaseNode = root.addElement("database");
                    // database end
                    xmlWriter.write(document);
                } catch (Exception e) {
                    log.error(L10NUtils.format("003007", file.getName(), e.getMessage()));
                    error = true;
                } finally {
                    try {
                        writer.flush();
                        writer.close();
                    } catch (Exception e) {
                        log.error(e);
                        error = true;
                    }
                }
            }
            this.setupProperties = new XmlApplicationProperties(file);
        } catch (Exception e) {
            log.warn("I warning you!");
            log.debug(e.getMessage(), e);
            return EmptyApplicationProperties.getInstance();
        }
    }
    return setupProperties;
}

From source file:architecture.ee.component.RepositoryImpl.java

License:Apache License

public ApplicationProperties getSetupApplicationProperties() {
    if (setupProperties == null) {
        if (initailized.get()) {

            File file = getFile(ApplicationConstants.DEFAULT_STARTUP_FILENAME);

            if (!file.exists()) {
                boolean error = false;
                // create default file...
                log.debug(CommonLogLocalizer.format("003012", file.getAbsolutePath()));
                Writer writer = null;
                try {

                    lock.lock();/*from   w ww .j  av  a 2  s .  co  m*/

                    writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
                    XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint());
                    StringBuilder sb = new StringBuilder();

                    org.dom4j.Document document = org.dom4j.DocumentHelper.createDocument();
                    org.dom4j.Element root = document.addElement("startup-config");
                    // setup start
                    // ------------------------------------------------------------
                    org.dom4j.Element setupNode = root.addElement("setup");
                    setupNode.addElement("complete").setText("false");
                    // setup end

                    // license start
                    root.addComment("LICENSE SETTING");
                    org.dom4j.Element licenseNode = root.addElement("license");
                    // license end

                    // view start
                    /*
                    org.dom4j.Element viewNode = root.addElement("view");
                    org.dom4j.Element renderNode = viewNode.addElement("render");
                    org.dom4j.Element freemarkerNode = renderNode.addElement("freemarker");
                    freemarkerNode.addElement("enabled").setText("true");
                    freemarkerNode.addElement("source").addElement("location");
                    org.dom4j.Element velocityNode = renderNode.addElement("velocity");
                    velocityNode.addElement("enabled").setText("false");
                    */
                    // view end

                    // security start         
                    root.addComment("SECURITY SETTING");
                    org.dom4j.Element securityNode = root.addElement("security");
                    org.dom4j.Element encrpptNode = securityNode.addElement("encrypt");
                    encrpptNode.addElement("algorithm").setText("Blowfish");
                    encrpptNode.addElement("key").addElement("current");
                    org.dom4j.Element encrpptPropertyNode = encrpptNode.addElement("property");
                    encrpptPropertyNode.addElement("name").setText("username");
                    encrpptPropertyNode.addElement("name").setText("password");
                    securityNode.addElement("authentication").addElement("encoding").addElement("algorithm")
                            .setText("SHA-256");
                    // security end
                    // services start
                    root.addComment("SERVICES SETTING");
                    org.dom4j.Element servicesNode = root.addElement("services");
                    servicesNode.addElement("sql").addElement("location").addText("sql");
                    // services end

                    // database start
                    root.addComment("DATABASE SETTING");
                    org.dom4j.Element databaseNode = root.addElement("database");
                    org.dom4j.Element databaseDefaultNode = databaseNode.addElement("default");
                    databaseDefaultNode.addComment(" 1. jndi datasource ");
                    databaseDefaultNode.addComment((new StringBuilder()).append("\n").append("      ")
                            .append("<jndiDataSourceProvider>").append("\n").append("      ")
                            .append("   <jndiName></jndiName>").append("\n").append("      ")
                            .append("</jndiDataSourceProvider>").append("\n").toString());
                    databaseDefaultNode.addComment(" 2. connection pool datasource using dbcp ");
                    databaseDefaultNode.addComment((new StringBuilder()).append("\n").append("      ")
                            .append("<pooledDataSourceProvider> ").append("\n").append("      ")
                            .append("    <driverClassName></driverClassName> ").append("\n").append("      ")
                            .append("    <url></url>").append("\n").append("      ")
                            .append("    <username></username>").append("\n").append("      ")
                            .append("    <password></password>").append("\n").append("      ")
                            .append("    <connectionProperties>").append("\n").append("      ")
                            .append("        <initialSize>1</initialSize>").append("\n").append("      ")
                            .append("        <maxActive>8</maxActive>").append("\n").append("      ")
                            .append("        <maxIdle>8</maxIdle>").append("\n").append("      ")
                            .append("        <maxWait>-1</maxWait>").append("\n").append("      ")
                            .append("        <minIdle>0</minIdle>").append("\n").append("      ")
                            .append("        <testOnBorrow>true</testOnBorrow>").append("\n").append("      ")
                            .append("        <testOnReturn>false</testOnReturn>").append("\n").append("      ")
                            .append("        <testWhileIdle>false</testWhileIdle>").append("\n")
                            .append("      ")
                            .append("        <validationQuery>select 1 from dual</validationQuery>")
                            .append("\n").append("      ").append("    </connectionProperties>").append("\n")
                            .append("      ").append("</pooledDataSourceProvider>").toString());
                    // database end
                    xmlWriter.write(document);
                } catch (Exception e) {
                    log.error("fail to making {} - {}", file.getName(), e.getMessage());
                    error = true;
                } finally {

                    try {
                        writer.flush();
                        writer.close();
                    } catch (Exception e) {
                        log.error("error", e);
                        error = true;
                    }
                    lock.unlock();
                }
            } else {
                try {
                    log.debug(CommonLogLocalizer.format("003011", file.getPath()));
                    this.setupProperties = new LocalApplicationProperties(file);
                } catch (IOException e) {
                    log.error(CommonLogLocalizer.getMessage("003013"), e);
                }
            }
        } else {
            return LocalApplicationProperties.EMPTY_APPLICATION_PROPERTIES;
        }
    }
    return setupProperties;
}

From source file:architecture.ee.util.xml.XmlProperties.java

License:Apache License

/**
 * Saves the properties to disk as an XML document. A temporary file is used
 * during the writing process for maximum safety.
 *///  w  w  w.ja  v a2  s  . co m
private synchronized void saveProperties() {
    boolean error = false;
    // Write data out to a temporary file first.
    File tempFile = null;
    Writer writer = null;
    try {
        tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8"));
        OutputFormat prettyPrinter = OutputFormat.createPrettyPrint();
        XmlWriter xmlWriter = new XmlWriter(writer, prettyPrinter);
        xmlWriter.write(document);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        // There were errors so abort replacing the old property file.
        error = true;
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e1) {
                log.error(e1.getMessage(), e1);
                error = true;
            }
        }
    }

    // No errors occured, so delete the main file.
    if (!error) {
        // Delete the old file so we can replace it.
        if (!file.delete()) {
            // log.error(L10NUtils.format("002156",
            // file.getAbsolutePath()));
            return;
        }
        // Copy new contents to the file.
        try {
            copy(tempFile, file);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            // There were errors so abort replacing the old property file.
            error = true;
        }
        // If no errors, delete the temp file.
        if (!error) {
            tempFile.delete();
        }
    }
}

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());
    }/*  w  w w  .jav a2 s  .  c om*/

    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;/* ww w  . jav a2  s . co m*/
    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:bio.pih.genoogle.interfaces.WebServices.java

private String xmlToString(Document doc) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setTrimText(false);/* w w  w .  j  av  a 2s.  c  om*/
    XMLWriter writer = null;

    try {
        writer = new XMLWriter(outputStream, outformat);
    } catch (UnsupportedEncodingException e) {
        logger.fatal(e);
        return e.getLocalizedMessage();
    }

    try {
        writer.write(doc);
    } catch (IOException e) {
        logger.fatal(e);
        return e.getLocalizedMessage();
    }

    try {
        return outputStream.toString("UTF-8");
    } catch (UnsupportedEncodingException e) {
        logger.fatal(e);
        return e.getLocalizedMessage();
    }
}

From source file:BlastResultXMLsplit.BlastXMLsplit.java

public BlastXMLsplit(String filepath, int seqnumber)
        throws FileNotFoundException, IOException, ParserConfigurationException {
    SAXReader reader = new SAXReader();
    reader.setValidation(false);//from w  w w .java  2  s .  c  o  m
    try {
        System.out.println("Xlmfile reading");
        Document document = reader.read(new FileInputStream(filepath));//XMLdocument?
        System.out.println("Xlmfile read done!");
        org.dom4j.DocumentFactory DocumentFactory = new org.dom4j.DocumentFactory();

        ArrayList str = new ArrayList();//??? 

        String fileoutpath;

        org.dom4j.Element rootElm = document.getRootElement();//
        File f = new File(filepath);
        int count = 1;
        List<org.dom4j.Element> blastOutput_iterations = rootElm.element("BlastOutput_iterations").elements();//?
        org.dom4j.Element BlastOutput_program = rootElm.element("BlastOutput_program");
        org.dom4j.Element BlastOutput_version = rootElm.element("BlastOutput_version");
        org.dom4j.Element BlastOutput_reference = rootElm.element("BlastOutput_reference");
        org.dom4j.Element BlastOutput_db = rootElm.element("BlastOutput_db");
        //?
        BlastOutput_program.getParent().remove(BlastOutput_program);
        BlastOutput_version.getParent().remove(BlastOutput_version);
        BlastOutput_reference.getParent().remove(BlastOutput_reference);
        BlastOutput_db.getParent().remove(BlastOutput_db);
        // org.dom4j.Element BlastOutput_query_def=rootElm.element("BlastOutput_query-def");
        //org.dom4j.Element BBlastOutput_query_len=rootElm.element("BlastOutput_query-len");

        org.dom4j.Element BlastOutput_param = rootElm.element("BlastOutput_param");
        rootElm.remove(BlastOutput_param);

        String Iteration_queryIDstr, Iteration_queryDefstr, Iteration_query_len;
        List<org.dom4j.Element> Iterationlist = null;
        int size = blastOutput_iterations.size();
        System.out.println("Your query seqcount is " + size + "\r\n Start dividing your file");
        for (int i = 0; i < size; i = i + seqnumber) {
            //??
            fileoutpath = f.getParent() + System.getProperty("file.separator") + count + ".xml";
            count++;
            System.out.println("The " + count + " is located in " + fileoutpath);
            FileOutputStream fos = new FileOutputStream(fileoutpath);
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(fos, format);
            // XMLWriter writer = new XMLWriter(new FileOutputStream(fileoutpath));
            //w??
            org.dom4j.Element firstelement = blastOutput_iterations.get(i);
            Iteration_queryIDstr = firstelement.element("Iteration_query-ID").getText();
            Iteration_queryDefstr = firstelement.element("Iteration_query-def").getText();
            Iteration_query_len = firstelement.element("Iteration_query-len").getText();

            //org.dom4j.DocumentFactory DocumentFactory = new org.dom4j.DocumentFactory();

            Document document2 = DocumentHelper.createDocument();
            ;
            org.dom4j.Element BlastOutputElement = document2.addElement("BlastOutput");
            //doc.setRootElement(BlastOutputElement);
            //;
            BlastOutputElement.add(BlastOutput_program);
            BlastOutputElement.add(BlastOutput_version);
            BlastOutputElement.add(BlastOutput_reference);
            BlastOutputElement.add(BlastOutput_db);
            BlastOutputElement.addElement("BlastOutput_query-ID");
            BlastOutputElement.element("BlastOutput_query-ID").setText(Iteration_queryIDstr);
            BlastOutputElement.addElement("BlastOutput_query-def");
            BlastOutputElement.element("BlastOutput_query-def").setText(Iteration_queryDefstr);
            BlastOutputElement.addElement("BlastOutput_query-len");
            BlastOutputElement.element("BlastOutput_query-len").setText(Iteration_query_len);
            //                Element BlastOutput_param_new=DocumentFactory.createElement("BlastOutput_param");
            //                for (Iterator it = BlastOutput_param.elementIterator(); it.hasNext();) {
            //                    Element tempele=(Element) it.next();
            //                    tempele.getParent().remove(tempele);
            //                    BlastOutput_param_new.add(tempele);
            //                }
            BlastOutputElement.add(BlastOutput_param);
            //BlastOutputElement.add(BlastOutput_param);
            if (i + seqnumber < blastOutput_iterations.size()) {
                Iterationlist = blastOutput_iterations.subList(i, i + seqnumber);
            } else {
                Iterationlist = blastOutput_iterations.subList(i, blastOutput_iterations.size() - 1);
            }
            //System.out.println(Iterationlist.size());
            //?query
            resetIterationlist(Iterationlist);
            //?BlastOutput_iterations

            Element BlastOutput_iterations = DocumentFactory.createElement("BlastOutput_iterations");
            //BlastOutputElement.addAttribute("BlastOutput_iterations");
            //org.dom4j.Element BlastOutput_iterations = new org.dom4j.Element("BlastOutput_iterations");
            for (int j = 0; j < Iterationlist.size(); j++) {
                Iterationlist.get(j).getParent().remove(Iterationlist.get(j));
                //System.out.println(j);
                BlastOutput_iterations.add(Iterationlist.get(j));
            }
            BlastOutputElement.add(BlastOutput_iterations);

            //
            writer.write(document2);
            writer.close();
            BlastOutput_program.getParent().remove(BlastOutput_program);
            BlastOutput_version.getParent().remove(BlastOutput_version);
            BlastOutput_reference.getParent().remove(BlastOutput_reference);
            BlastOutput_db.getParent().remove(BlastOutput_db);
            BlastOutput_param.getParent().remove(BlastOutput_param);
        }
    } catch (DocumentException ex) {
        Logger.getLogger(BlastXMLsplit.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:ca.coder2000.recipes.RecipeFile.java

License:Mozilla Public License

/**
 * Returns formatted HTML from the xml file.
 * @param stylesheet The stylesheet to transform against.
 * @return The HTML to be used./*from  w  w  w .j  ava 2  s.c o  m*/
 */
public Document getHTML(File stylesheet) {
    Transformer transformer;
    TransformerFactory factory = TransformerFactory.newInstance();

    DocumentSource source = new DocumentSource(doc);
    DocumentResult result = new DocumentResult();

    try {
        transformer = factory.newTransformer(new StreamSource(stylesheet));
        transformer.transform(source, result);
        // Hard coded path MUST remove
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileWriter("k:/recipe/recipe.tmp"), format);
        writer.write(result.getDocument());
    } catch (TransformerException te) {
    } catch (IOException ioe) {
    }

    return result.getDocument();
}

From source file:cc.warlock.build.FeatureVersionReplacer.java

License:Open Source License

protected void replaceVersions() throws BuildException {
    SAXReader reader = new SAXReader();

    try {//from   w w w.  j a  v  a2s. co  m
        File featureFile = new File(new File(new File(buildDirectory, "features"), feature), "feature.xml");
        Document featureDoc = reader.read(featureFile);
        Element featureEl = featureDoc.getRootElement();
        featureEl.attribute("version").setValue(version);

        //          Properties versions = new Properties();
        //          File versionsFile = new File(buildDirectory, "finalPluginsVersions.properties");
        //          FileInputStream stream = new FileInputStream(versionsFile);
        //          versions.load(stream);
        //          stream.close();
        //          
        //          for (Element pluginEl : (List<Element>) featureEl.elements("plugin"))
        //          {
        //             if (pluginEl.attributeValue("version").equals("0.0.0"))
        //             {
        //                if (versions.containsKey(pluginEl.attributeValue("id")))
        //                   pluginEl.attribute("version").setValue(versions.getProperty(pluginEl.attributeValue("id")));
        //             }
        //          }

        OutputFormat format = OutputFormat.createPrettyPrint();

        FileOutputStream outStream = new FileOutputStream(featureFile);
        XMLWriter writer = new XMLWriter(outStream, format);
        writer.write(featureDoc);
        outStream.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:cc.warlock.core.configuration.WarlockConfiguration.java

License:Open Source License

public void save() {
    Document document = DocumentHelper.createDocument();
    Element warlockConfig = DocumentHelper.createElement("warlock-config");

    document.setRootElement(warlockConfig);

    for (IConfigurationProvider provider : providers) {
        List<Element> elements = provider.getTopLevelElements();

        for (Element element : elements) {
            warlockConfig.add(element);/*from w  ww .j  a  v  a2s.  com*/
        }
    }

    for (Element unhandled : unhandledElements) {
        // Make sure to resave unhandled elements, just in case the corresponding handler wasn't instantiated
        warlockConfig.add(unhandled.createCopy());
    }

    try {
        if (configFile.exists()) {
            File backupFile = new File(configFile.getPath() + ".bak");
            if (backupFile.exists())
                backupFile.renameTo(new File(backupFile.getPath() + ".1"));
            configFile.renameTo(backupFile);
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        FileOutputStream stream = new FileOutputStream(configFile);
        XMLWriter writer = new XMLWriter(stream, format);
        writer.write(document);
        stream.close();

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}