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:condorclient.utilities.XMLHandler.java

public String createXML() {
    String strXML = null;/*from  w ww  .java  2  s .c  o  m*/
    Document document = DocumentHelper.createDocument();
    // document.
    Element root = document.addElement("root");

    Element job = root.addElement("Job");

    Element jobDescFile = job.addElement("item");
    jobDescFile.addAttribute("about", "descfile");
    Element file_name = jobDescFile.addElement("name");
    file_name.addText("submit.txt");
    Element filer_path = jobDescFile.addElement("path");
    filer_path.addText("D:\\HTCondor\\test\\2");

    StringWriter strWtr = new StringWriter();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    XMLWriter xmlWriter = new XMLWriter(strWtr, format);
    try {
        xmlWriter.write(document);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    strXML = strWtr.toString();
    //--------

    //-------
    //strXML=document.asXML();
    //------
    //-------------
    File file = new File("condorclient.xml");
    if (file.exists()) {
        file.delete();
    }
    try {
        file.createNewFile();
        XMLWriter out = new XMLWriter(new FileWriter(file));
        out.write(document);
        out.flush();
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //--------------

    return strXML;
}

From source file:condorclient.utilities.XMLHandler.java

public void removeJobs(int[] delClusterIds, int delsum) {

    SAXReader saxReader = new SAXReader();
    Document document = null;/*from   ww w .  j  a  va2 s .c o m*/
    try {
        document = saxReader.read(new File("niInfo.xml"));

    } catch (DocumentException ex) {
        Logger.getLogger(XMLHandler.class.getName()).log(Level.SEVERE, null, ex);
    }

    List list = document.selectNodes("/root/info/job");//?job
    Iterator iter = list.iterator();
    Element root = document.getRootElement();
    Element info = root.element("info");
    try {
        while (iter.hasNext()) {
            Element job = (Element) iter.next();
            String id = job.attributeValue("id");
            for (int i = 0; i < delsum; i++) {
                if (id.equals("" + delClusterIds[i])) {

                    info.remove(job);
                }
            }

        }
    } catch (Exception e) {

        System.out.println("???");
    }

    XMLWriter writer = null;
    try {
        writer = new XMLWriter(new FileWriter(new File("niInfo.xml")));
        writer.write(document);
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(XMLHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:condorclient.utilities.XMLHandler.java

void setTransfer(String clusterId) {
    SAXReader saxReader = new SAXReader();
    Document document = null;/*from   ww  w.j  av a 2  s. c  o m*/
    try {
        document = saxReader.read(new File("niInfo.xml"));

    } catch (DocumentException ex) {
        Logger.getLogger(XMLHandler.class.getName()).log(Level.SEVERE, null, ex);
    }

    List list = document.selectNodes("/root/info/job");
    Iterator iter = list.iterator();

    while (iter.hasNext()) {
        Element job = (Element) iter.next();

        String id = job.attributeValue("id");
        if (id.equals(clusterId)) {
            job.attribute("transfer").setValue("1");
        }

    }
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(new FileWriter(new File("niInfo.xml")));
        writer.write(document);
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(XMLHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:controller.setup.Setup.java

private void updateHibernateCfgFile(String bd, String bdHost, String bdPort, String bdName, String bdUser,
        String bdUserMdp) {/*from   w w  w . jav a 2s.com*/

    System.out.println(
            "------------------------------ Creation hibernate config file -----------------------------");

    try {

        URL resource = Thread.currentThread().getContextClassLoader().getResource("hibernate.cfg.xml");
        File f = new File(resource.toURI());

        SAXReader xmlReader = new SAXReader();
        Document doc = xmlReader.read(f);
        Element sessionFactory = (Element) doc.getRootElement().elements().get(0);

        if (sessionFactory.elements().size() != 0)
            for (Iterator elt = sessionFactory.elements().iterator(); elt.hasNext();)
                sessionFactory.remove((Element) elt.next());

        if (bd.equals("mysql")) {
            sessionFactory.addElement("property").addAttribute("name", "dialect")
                    .addText("org.hibernate.dialect.MySQLDialect");
            sessionFactory.addElement("property").addAttribute("name", "connection.url")
                    .addText("jdbc:mysql://" + bdHost + ":" + bdPort + "/" + bdName);
            sessionFactory.addElement("property").addAttribute("name", "connection.driver_class")
                    .addText("com.mysql.jdbc.Driver");
        } else if (bd.equals("pgsql")) {
            sessionFactory.addElement("property").addAttribute("name", "dialect")
                    .addText("org.hibernate.dialect.PostgreSQLDialect");
            sessionFactory.addElement("property").addAttribute("name", "connection.url")
                    .addText("jdbc:postgresql://" + bdHost + ":" + bdPort + "/" + bdName);
            sessionFactory.addElement("property").addAttribute("name", "connection.driver_class")
                    .addText("org.postgresql.Driver");
        } else if (bd.equals("oracle")) {
            sessionFactory.addElement("property").addAttribute("name", "dialect")
                    .addText("org.hibernate.dialect.OracleDialect");
            sessionFactory.addElement("property").addAttribute("name", "connection.url")
                    .addText("jdbc:oracle:thin:@" + bdHost + ":" + bdPort + ":" + bdName);
            sessionFactory.addElement("property").addAttribute("name", "connection.driver_class")
                    .addText("oracle.jdbc.OracleDriver");
        } else if (bd.equals("mssqlserver")) {
            sessionFactory.addElement("property").addAttribute("name", "dialect")
                    .addText("org.hibernate.dialect.SQLServerDialect");
            sessionFactory.addElement("property").addAttribute("name", "connection.url")
                    .addText("jdbc:sqlserver://" + bdHost + ":" + bdPort + ";databaseName=" + bdName + ";");
            sessionFactory.addElement("property").addAttribute("name", "connection.driver_class")
                    .addText("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        }

        sessionFactory.addElement("property").addAttribute("name", "connection.username").addText(bdUser);
        sessionFactory.addElement("property").addAttribute("name", "connection.password").addText(bdUserMdp);
        sessionFactory.addElement("property").addAttribute("name", "hbm2ddl.auto").addText("update");

        XMLWriter writer = new XMLWriter(new FileWriter(f));
        writer.write(doc);
        writer.close();

        System.out.println(
                "------------------------------ Creation hibernate config file over -----------------------------");

    }

    catch (URISyntaxException e) {
        e.printStackTrace();
    }

    catch (DocumentException e) {
        e.printStackTrace();
    }

    catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:controllers.ServiceController.java

License:Apache License

private boolean writeBodyToFile(String filename) {
    String xmlFile = filename + ".xml";
    String jsonFile = filename + ".shape.json";
    try {// www.j a v a 2  s  . c  o m
        BufferedReader br = request.getReader();

        boolean hasJson = false;
        StringBuffer buf = new StringBuffer();
        //Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmlFile),"utf-8"));

        String inputLine;
        while ((inputLine = br.readLine()) != null) {
            if (inputLine.equals("===boundary===")) {
                /*?shapes*/
                //writer.close();
                //writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(jsonFile),"utf-8"));

                SAXReader reader = new SAXReader();
                reader.setEntityResolver(new DTDEntityResolver());
                Document document = reader.read(new StringReader(buf.toString()));
                OutputFormat format = new OutputFormat(" ", true);
                XMLWriter writer = new XMLWriter(
                        new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmlFile), "utf-8")),
                        format);
                writer.write(document);
                writer.flush();
                writer.close();

                hasJson = true;
                buf = new StringBuffer();
                continue;
            }

            buf.append(inputLine).append("\n");

            //writer.write(inputLine);
            //writer.write("\n");
        }
        //writer.close();
        br.close();

        if (!hasJson) {
            Trace.write(Trace.Error, "write osworkflow: no json-shape define!");
            return false;
        }

        String jsonString = buf.toString();
        jsonString = formatJsonStrings(jsonString);
        if (jsonString == null) {
            Trace.write(Trace.Error, "write osworkflow[json]: " + buf.toString());
            return false;
        }

        Writer jsonWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(jsonFile), "utf-8"));
        jsonWriter.write(jsonString);
        jsonWriter.close();

        return true;
    } catch (DocumentException de) {
        Trace.write(Trace.Error, de, "write osworkflow[xml].");
    } catch (IOException e) {
        Trace.write(Trace.Error, e, "write osworkflow.");
    }

    return false;
}

From source file:cparser.CParser.java

License:GNU General Public License

public static void main(final String argv[]) {
    System.loadLibrary("cparser");
    init();// ww  w. j a  v  a 2s .c o  m

    if (argv.length < 1)
        System.exit(1);

    final CParser cp = new CParser(new File(argv[0]).getAbsolutePath());

    System.out.println("Parsing");
    int ret = cp.parse();

    if (ret != 0)
        System.err.println("Parsing failed with error " + ret);

    final Node n = cp.getRoot();
    System.out.println("Computing");
    n.compute();
    System.out.println("Creating CFG");
    n.createCFG();
    System.out.println("Generating XML");
    final String xml = n.toXML();
    System.out.println("Writing XML text");
    try {
        final FileWriter fw = new FileWriter("xml.text");
        fw.write(xml);
        fw.close();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    System.err.println("Node:\n\tcls=" + n.getClass().getName());
    System.err.println("\tstr=" + n.toString());
    System.err.println("\tXML:");
    try {
        System.out.println("Generating XML tree");
        Document doc = DocumentHelper.parseText(xml);
        System.out.println("Writing XML");
        OutputFormat format = OutputFormat.createPrettyPrint();
        OutputStream os = new FileOutputStream("out.xml");
        try {
            XMLWriter writer = new XMLWriter(os, format);
            writer.write(doc);
            writer.close();
            os.close();
            /*            writer = new XMLWriter(System.err, format);
                        writer.write(doc);
                        writer.close();*/
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    fini();
}

From source file:cz.dasnet.dasik.Dasik.java

License:Open Source License

@Override
protected void onConnect() {
    log.info("Connected on " + getServer());
    auth();/*from w ww  .j a v  a2 s  .  c  o  m*/
    if (authed) {
        requestInvites();
    }
    final Dasik bot = this;
    try {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                bot.joinChannels();
            }
        }, 1000);

        TimerTask dumpTask = new TimerTask() {

            @Override
            public void run() {
                Document document = DocumentHelper.createDocument();
                Element channelinfo = document.addElement("channelinfo");

                for (String c : activeChannels.keySet()) {
                    Element channel = channelinfo.addElement("channel");
                    Element name = channel.addElement("name");
                    name.setText(c);
                    Element size = channel.addElement("size");
                    size.setText("" + getUsers(c).length);
                }

                Element updatetime = channelinfo.addElement("updatetime");
                updatetime.setText(new Long(new Date().getTime() / 1000).toString());

                try {
                    XMLWriter writer = new XMLWriter(new FileWriter("channelinfo.xml"));
                    writer.write(document);
                    writer.close();
                } catch (IOException ex) {
                    log.error("Unable to dump channel info", ex);
                }
            }
        };

        Timer dump = new Timer("dump", true);
        dump.schedule(dumpTask, 10000, 60000);
    } catch (Exception ex) {
        this.joinChannels();
        log.error("Channel autojoin timer failed to schedule the task.", ex);
    }
}

From source file:DAO.LocationDAO.java

public boolean addNewLocation(String webAppPath, String location) {
    try {/*from   w  w  w . ja va  2s. c o  m*/
        SAXReader reader = new SAXReader();
        Document document = reader.read(webAppPath + "/xml/Locations.xml");
        Element root = document.getRootElement();
        int max = 0;
        for (Iterator i = root.elementIterator("Location"); i.hasNext();) {
            Element elt = (Element) i.next();
            int cur = Integer.parseInt(elt.element("LocationId").getText());
            if (cur > max) {
                max = cur;
            }
        }

        Integer newLocationId = max + 1;
        Element newLocation = root.addElement("Location");
        newLocation.addElement("LocationId").setText(newLocationId.toString());
        newLocation.addElement("Name").setText(location);
        root.appendAttributes(newLocation);
        try {
            FileOutputStream fos = new FileOutputStream(webAppPath + "/xml/Locations.xml");
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter xmlwriter = new XMLWriter(fos, format);
            xmlwriter.write(document);
            System.out.println("dead");
            xmlwriter.close();
        } catch (Exception ex) {
            System.out.println("Failed!");
            ex.printStackTrace();
        }
        //Node node = document.selectSingleNode("/Locations/Location[not(../Location/LocationId > LocationId)]");
        //String id = node.valueOf("LocationId");
        //System.out.println(id);
        return true;
    } catch (DocumentException ex) {
        System.out.println("Add New Location Failed!");
        Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
}

From source file:de.ailis.wlandsuite.game.blocks.GameBlock.java

License:Open Source License

/**
 * Writes the block to a stream as XML//from w ww  .  j a va  2  s  .c o  m
 *
 * @param stream
 *            The output stream
 * @throws IOException
 *             When file operation fails.
 */

public void writeXml(final OutputStream stream) throws IOException {
    XMLWriter writer;
    Document document;
    OutputFormat format;

    format = OutputFormat.createPrettyPrint();
    format.setTrimText(false);

    writer = new XMLWriter(stream, format);
    try {
        final Element rootElement = toXml();
        document = DocumentHelper.createDocument(rootElement);
        writer.write(document);
    } finally {
        writer.close();
    }
}

From source file:de.ailis.xadrian.utils.XmlUtils.java

License:Open Source License

/**
 * Writes the specified document to the specified file.
 *
 * @param document// w w w .  ja va2 s  .com
 *            The document to write
 * @param file
 *            The file to write to
 * @throws IOException
 *             If file could not be written
 */
public static void write(final Document document, final File file) throws IOException {
    final OutputFormat format = OutputFormat.createPrettyPrint();
    final XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"), format);
    try {
        writer.write(document);
    } finally {
        writer.close();
    }
}