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:org.craftercms.cstudio.alfresco.util.XmlUtils.java

License:Open Source License

/**
 * convert document to string/*from   ww  w.ja  v  a 2s  .c o m*/
 * 
 * @param document
 * @return XML as String
 * @throws IOException
 */
public static String convertDocumentToString(Document document) throws IOException {
    StringWriter sw = new StringWriter();
    XMLWriter writer = new XMLWriter(sw);
    try {
        writer.write(document);
        writer.flush();
        return sw.toString();
    } finally {
        sw.close();
        writer.close();
    }
}

From source file:org.craftercms.cstudio.loadtesting.actions.WriteContent.java

License:Open Source License

/**
 * convert InputStream to string//from  w w  w.  j  a v a2s. c o  m
 * @param internalName 
 * 
 * @param is
 * @return string
 */
public String getFileContent(String baseFileName, String fileName, String internalName) throws Exception {
    InputStream is = null;
    InputStreamReader isReader = null;
    StringWriter sw = null;
    XMLWriter writer = null;
    try {
        is = this.getClass().getResourceAsStream("/" + baseFileName);
        isReader = new InputStreamReader(is, "UTF-8");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(isReader);
        Element root = document.getRootElement();
        Node node = root.selectSingleNode("file-name");
        node.setText(fileName);
        Node node2 = root.selectSingleNode("internal-name");
        node2.setText(internalName);
        sw = new StringWriter();
        writer = new XMLWriter(sw);
        writer.write(document);
        writer.flush();
        return sw.toString();
    } finally {
        if (is != null) {
            is.close();
        }
        if (isReader != null) {
            isReader.close();
        }
        if (sw != null) {
            sw.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:org.dentaku.gentaku.tools.cgen.visitor.JellyTemplateGeneratingVisitor.java

License:Apache License

public void handleElement(Element element) throws VisitorException {
    if (element.getParent().getName().equals("schema")) {
        QName rootName = DocumentFactory.getInstance().createQName("jelly", "j", "jelly:core");
        Branch parent = DocumentHelper.createDocument().addElement(rootName).addNamespace("x", "jelly:xml");

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(getEncoding());
        format.setSuppressDeclaration(false);
        format.setExpandEmptyElements(false);

        pushParent(parent.addElement(element.getName()));
        for (Iterator it = element.elementIterator(); it.hasNext();) {
            visit((Element) it.next());
        }// w  w  w .  j  av a2s  . c  o  m
        popParent();

        try {
            String filename = element.getName() + ".jelly";

            Writer out = new FileWriter(new File(getRootDir(), filename));
            final XMLWriter xmlWriter = new XMLWriter(out, format);
            xmlWriter.setEscapeText(false);

            xmlWriter.write(parent);
            xmlWriter.flush();
            xmlWriter.close();
        } catch (Exception e) {
            throw new VisitorException("Exception occurred when running Jelly", e);
        }

        topLevelElements.put(element.getName(), element);

    } else {
        String refName = element.attributeValue("ref");
        if (refName != null) {
            Branch parent = getCurrentParent();
            // create an include
            QName qName = DocumentFactory.getInstance().createQName("import", "j", "jelly:core");
            parent.addElement(qName).addAttribute("uri", refName + ".jelly").addAttribute("inherit", "true");
        }
    }
}

From source file:org.dentaku.gentaku.tools.cgen.xmi.XMIGenTask.java

License:Apache License

private void writeFile(Branch document, File file) throws IOException {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(System.getProperty("file.encoding"));
    format.setSuppressDeclaration(false);
    format.setExpandEmptyElements(false);

    Writer out = new FileWriter(file);
    final XMLWriter xmlWriter = new XMLWriter(out, format);
    xmlWriter.setEscapeText(false);//  w w w. j av a  2s .  c o m

    xmlWriter.write(document);
    xmlWriter.flush();
    xmlWriter.close();
}

From source file:org.dom4j.samples.RoundTripDemo.java

License:Open Source License

/** Outputs the document to a buffer, parse it back again then output it */
protected void process(Document document) throws Exception {

    System.out.println("about to output: " + document);

    // output the document to a buffer
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out);
    writer.write(document);// w w w .  j av  a  2 s . c o m
    writer.close();

    // parse back again
    StringReader in = new StringReader(out.toString());
    SAXReader reader = new SAXReader();
    Document doc2 = reader.read(in);

    System.out.println("parsed back again: " + doc2);

    // now lets output it again
    writer.setOutputStream(System.out);
    writer.write(doc2);
}

From source file:org.eclipse.birt.build.GenCaseResult.java

License:Open Source License

private void genReport(String path) {

    /*/*from   w  ww  .  ja  va2 s.  c o m*/
     * Add genDate node to report
     */

    DOMElement testElement = new DOMElement("ReportDate");
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");

    String strDate = currentDate.format(cal.getTime());
    testElement.setText(strDate);
    this.rootElement.add(testElement);

    DocumentFactory factory = new DocumentFactory();
    Document doc = factory.createDocument(rootElement);
    OutputFormat format = OutputFormat.createPrettyPrint();

    try {

        XMLWriter writer = new XMLWriter(new FileWriter(this.getReportPath(path)), format);
        writer.write(doc);
        writer.close();

    } catch (Exception ex) {

        ex.printStackTrace();

    }

}

From source file:org.eclipse.birt.build.VersionUpdater.java

License:Open Source License

/**
 * @author //from  www . j a v a 2s . co  m
 * @param folderPath
 * @param plug_id
 * @param lastDate
 * @param dayInpast
 */
private void genVersionLog(File folderPath, String plug_id, String lastDate, int dayInpast) {
    // gen the dest file path
    String parentPath = folderPath.getAbsolutePath();
    String fileName = plug_id + "_DayInPast" + ".xml";
    String fullName = parentPath + "/" + fileName;
    File dest = new File(fullName);
    System.out.println("dest file full path:\t" + fullName);
    try {
        //genarate document factory
        DocumentFactory factory = new DocumentFactory();
        //create root element
        DOMElement rootElement = new DOMElement("plugin");
        rootElement.setAttribute("id", plug_id);
        //add child:lastdate
        DOMElement dateElement = new DOMElement("LastDate");
        dateElement.setText(lastDate);
        rootElement.add(dateElement);
        //add child:dayinpast
        DOMElement dayElement = new DOMElement("DayInPast");
        dayElement.setText(Integer.toString(dayInpast));
        rootElement.add(dayElement);
        //gen the doc
        Document doc = factory.createDocument(rootElement);

        //PrettyFormat
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileWriter(dest), format);
        writer.write(doc);
        writer.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:org.eclipse.ecr.core.io.impl.plugins.XMLDirectoryWriter.java

License:Open Source License

@Override
public DocumentTranslationMap write(ExportedDocument doc) throws IOException {

    File file = new File(getDestination() + File.separator + doc.getPath().toString());
    if (!file.mkdirs()) {
        throw new IOException("Cannot create target directory: " + file.getAbsolutePath());
    }//from www  .j  av a 2 s . c  o m
    OutputFormat format = AbstractDocumentWriter.createPrettyPrint();
    XMLWriter writer = null;
    try {
        writer = new XMLWriter(new FileOutputStream(file.getAbsolutePath() + File.separator + "document.xml"),
                format);
        writer.write(doc.getDocument());
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
    Map<String, Blob> blobs = doc.getBlobs();
    for (Map.Entry<String, Blob> entry : blobs.entrySet()) {
        String blobPath = file.getAbsolutePath() + File.separator + entry.getKey();
        entry.getValue().transferTo(new File(blobPath));
    }

    // write external documents
    for (Map.Entry<String, Document> entry : doc.getDocuments().entrySet()) {
        writer = null;
        try {
            writer = new XMLWriter(
                    new FileOutputStream(file.getAbsolutePath() + File.separator + entry.getKey() + ".xml"),
                    format);
            writer.write(entry.getValue());
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    return null;
}

From source file:org.eclipse.ecr.core.io.impl.plugins.XMLDocumentWriter.java

License:Open Source License

@Override
public DocumentTranslationMap write(ExportedDocument doc) throws IOException {

    OutputFormat format = AbstractDocumentWriter.createPrettyPrint();
    XMLWriter writer = null;
    try {/* w w  w  .ja  va 2 s. co m*/
        writer = new XMLWriter(out, format);
        writer.write(doc.getDocument());
    } finally {
        if (writer != null) {
            writer.close();
        }
    }

    // keep location unchanged
    DocumentLocation oldLoc = doc.getSourceLocation();
    String oldServerName = oldLoc.getServerName();
    DocumentRef oldDocRef = oldLoc.getDocRef();
    DocumentTranslationMap map = new DocumentTranslationMapImpl(oldServerName, oldServerName);
    map.put(oldDocRef, oldDocRef);
    return map;
}

From source file:org.ecocean.servlet.ScanResultsServlet.java

License:Open Source License

public boolean writeXML(HttpServletRequest request, Vector results, String num, String newEncDate,
        String newEncShark, String newEncSize) {
    String context = "context0";
    context = ServletUtilities.getContext(request);
    try {/*from w ww . j  ava  2 s.c o  m*/
        System.out.println("Prepping to write XML file for encounter " + num);

        //now setup the XML write for the encounter
        int resultsSize = results.size();
        MatchObject[] matches = new MatchObject[resultsSize];
        for (int a = 0; a < resultsSize; a++) {
            matches[a] = (MatchObject) results.get(a);
        }
        Arrays.sort(matches, new MatchComparator());
        StringBuffer resultsXML = new StringBuffer();
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("matchSet");
        root.addAttribute("scanDate", (new java.util.Date()).toString());
        root.addAttribute("R", request.getParameter("R"));
        root.addAttribute("epsilon", request.getParameter("epsilon"));
        root.addAttribute("Sizelim", request.getParameter("Sizelim"));
        root.addAttribute("maxTriangleRotation", request.getParameter("maxTriangleRotation"));
        root.addAttribute("C", request.getParameter("C"));
        for (int i = 0; i < matches.length; i++) {
            MatchObject mo = matches[i];
            Element match = root.addElement("match");
            match.addAttribute("points", (new Double(mo.matchValue)).toString());
            match.addAttribute("adjustedpoints", (new Double(mo.adjustedMatchValue)).toString());
            match.addAttribute("pointBreakdown", mo.pointBreakdown);
            String finalscore = (new Double(mo.matchValue * mo.adjustedMatchValue)).toString();
            if (finalscore.length() > 7) {
                finalscore = finalscore.substring(0, 6);
            }
            match.addAttribute("finalscore", finalscore);

            //check if logM is very small...
            try {
                match.addAttribute("logMStdDev", (new Double(mo.getLogMStdDev())).toString());
            } catch (java.lang.NumberFormatException nfe) {
                match.addAttribute("logMStdDev", "<0.01");
            }

            match.addAttribute("evaluation", mo.getEvaluation());

            Element enc = match.addElement("encounter");
            enc.addAttribute("number", mo.encounterNumber);
            enc.addAttribute("date", mo.date);
            enc.addAttribute("sex", mo.catalogSex);
            enc.addAttribute("assignedToShark", mo.getIndividualName());
            enc.addAttribute("size", ((new Double(mo.size)).toString() + " meters"));
            for (int k = 0; k < mo.scores.size(); k++) {
                Element spot = enc.addElement("spot");
                spot.addAttribute("x", (new Double(((VertexPointMatch) mo.scores.get(k)).oldX)).toString());
                spot.addAttribute("y", (new Double(((VertexPointMatch) mo.scores.get(k)).oldY)).toString());
            }
            Element enc2 = match.addElement("encounter");
            enc2.addAttribute("number", num);
            enc2.addAttribute("date", newEncDate);
            enc2.addAttribute("sex", mo.newSex);
            enc2.addAttribute("assignedToShark", newEncShark);
            enc2.addAttribute("size", (newEncSize + " meters"));
            for (int j = 0; j < mo.scores.size(); j++) {
                Element spot = enc2.addElement("spot");
                spot.addAttribute("x", (new Double(((VertexPointMatch) mo.scores.get(j)).newX)).toString());
                spot.addAttribute("y", (new Double(((VertexPointMatch) mo.scores.get(j)).newY)).toString());
            }

        }

        //prep for writing out the XML

        //setup data dir
        String rootWebappPath = getServletContext().getRealPath("/");
        File webappsDir = new File(rootWebappPath).getParentFile();
        File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName(context));
        //if(!shepherdDataDir.exists()){shepherdDataDir.mkdirs();}
        //File encountersDir=new File(shepherdDataDir.getAbsolutePath()+"/encounters");
        //if(!encountersDir.exists()){encountersDir.mkdirs();}

        //in case this is a right-side scan, change file name to save to
        String fileAddition = "";
        if ((request.getParameter("rightSide") != null) && (request.getParameter("rightSide").equals("true"))) {
            fileAddition = "Right";
        }
        //File file=new File((new File(".")).getCanonicalPath()+File.separator+"webapps"+File.separator+"ROOT"+File.separator+"encounters"+File.separator+num+File.separator+"lastFull"+fileAddition+"Scan.xml");
        //File file = new File(encountersDir.getAbsoluteFile()+"/"+ num + "/lastFull" + fileAddition + "Scan.xml");
        File file = new File(Encounter.dir(shepherdDataDir, num) + "/lastFull" + fileAddition + "Scan.xml");

        FileWriter mywriter = new FileWriter(file);
        org.dom4j.io.OutputFormat format = org.dom4j.io.OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));
        org.dom4j.io.XMLWriter writer = new org.dom4j.io.XMLWriter(mywriter, format);
        writer.write(document);
        writer.close();
        System.out.println("Successful write.");
        return true;
    } catch (Exception e) {
        System.out.println("Encountered an error trying to write back XML results!");
        e.printStackTrace();
        return false;
    }
}