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:eu.planets_project.pp.plato.action.ProjectExportAction.java

License:Open Source License

/**
 * Dumps binary data to provided file//from   w  w  w. ja v a 2s .  c  o m
 * It results in an XML file with a single element: data, 
 * @param id
 * @param data
 * @param f
 * @param encoder
 * @throws IOException
 */
private static void writeBinaryData(int id, ByteStream data, File f, BASE64Encoder encoder) throws IOException {
    Document streamDoc = DocumentHelper.createDocument();
    Element d = streamDoc.addElement("data");
    d.addAttribute("id", "" + id);
    d.setText(encoder.encode(data.getData()));
    XMLWriter writer = new XMLWriter(new BufferedWriter(new FileWriter(f)), ProjectExporter.prettyFormat);
    writer.write(streamDoc);
    writer.flush();
    writer.close();
}

From source file:eu.planets_project.pp.plato.action.workflow.ValidatePlanAction.java

License:Open Source License

/**
 * reads the executable preservation plan and formats it.
 * //from w w w .  j  a  v a2s  . co m
 */
private String formatExecutablePlan(String executablePlan) {

    if (executablePlan == null || "".equals(executablePlan)) {
        return "";
    }

    try {
        Document doc = DocumentHelper.parseText(executablePlan);

        StringWriter sw = new StringWriter();

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setNewlines(true);
        format.setTrimText(true);
        format.setIndent("  ");
        format.setExpandEmptyElements(false);
        format.setNewLineAfterNTags(20);

        XMLWriter writer = new XMLWriter(sw, format);

        writer.write(doc);
        writer.close();

        return sw.toString();

    } catch (DocumentException e) {
        return "";
    } catch (IOException e) {
        return "";
    }
}

From source file:eu.planets_project.pp.plato.application.AdminAction.java

License:Open Source License

/**
 * Renders the given exported XML-Document as HTTP response
 *//*from   w  w w.ja va 2s  .  c om*/
private String returnXMLExport(Document doc) {
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_kkmmss");
    String timestamp = format.format(new Date(System.currentTimeMillis()));

    String filename = "export_" + timestamp + ".xml";
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext()
            .getResponse();
    response.setContentType("application/x-download");
    response.setHeader("Content-Disposition", "attachement; filename=\"" + filename + "\"");
    //response.setContentLength(xml.length());
    try {
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        XMLWriter writer = new XMLWriter(out, ProjectExporter.prettyFormat);
        writer.write(doc);
        writer.flush();
        writer.close();
        out.flush();
        out.close();
    } catch (IOException e) {
        FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR,
                "An error occured while generating the export file.");
        log.error("Could not open response-outputstream: ", e);
    }
    FacesContext.getCurrentInstance().responseComplete();
    return null;
}

From source file:eu.planets_project.pp.plato.xml.LibraryExport.java

License:Open Source License

public void exportToStream(LibraryTree lib, OutputStream out) throws IOException {
    XMLWriter writer = new XMLWriter(out, prettyFormat);
    writer.write(exportToDocument(lib));
    writer.close();
}

From source file:eu.planets_project.pp.plato.xml.ProjectExporter.java

License:Open Source License

/**
 * Writes the xml-representation of the given projects to the given target file.
 * NOTE: It writes all data - including encoded binary data - directly to the DOM tree
 *       this may result in performance problems for large amounts of data.  
 *//* w  w w.  j  a  v  a 2  s  .c om*/
public void exportToFile(Plan p, File target) throws IOException {
    XMLWriter writer = new XMLWriter(new FileWriter(target), ProjectExporter.prettyFormat);
    writer.write(exportToXml(p));
    writer.close();
}

From source file:eu.planets_project.pp.plato.xml.ProjectImporter.java

License:Open Source License

/**
 * //from   ww  w . j ava  2  s . c om
 * @param args
 *            first entry is the filename of the xml-file to be imported
 *            second entry is the name of the output-file
 */
public static void main(String[] args) {

    ProjectImporter projectImp = new ProjectImporter();
    ProjectExporter exporter = new ProjectExporter();
    try {
        for (Plan plan : projectImp.importProjects(args[0])) {
            System.out.println("Imported : " + plan.getPlanProperties().getName());
            // export the imported project
            FileOutputStream out = new FileOutputStream(args[1]);
            XMLWriter writer = new XMLWriter(out, ProjectExporter.prettyFormat);
            writer.write(exporter.exportToXml(plan));
            writer.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

From source file:eu.scape_project.planning.plato.wf.CreateExecutablePlan.java

License:Apache License

/**
 * Generates the preservation action plan other plan information and stores
 * it in the plan.//from   ww  w  .  java2 s.  c om
 * 
 * @throws PlanningException
 *             if an error occurred
 */
public void generatePreservationActionPlan() throws PlanningException {
    try {
        Document papDoc = generator.generatePreservationActionPlanDocument(
                plan.getSampleRecordsDefinition().getCollectionProfile(), plan.getExecutablePlanDefinition(),
                plan);

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setEncoding(PlanXMLConstants.ENCODING);

        XMLWriter writer = new XMLWriter(out, outputFormat);

        writer.write(papDoc);
        writer.close();

        ByteStream bs = new ByteStream();
        bs.setData(out.toByteArray());
        bs.setSize(out.size());

        DigitalObject digitalObject = new DigitalObject();
        digitalObject.setFullname(PreservationActionPlanGenerator.FULL_NAME);
        digitalObject.setContentType("application/xml");
        digitalObject.setData(bs);

        digitalObjectManager.moveDataToStorage(digitalObject);

        if (plan.getPreservationActionPlan() != null && plan.getPreservationActionPlan().isDataExistent()) {
            bytestreamsToRemove.add(plan.getPreservationActionPlan().getPid());
        }

        plan.setPreservationActionPlan(digitalObject);
        addedBytestreams.add(digitalObject.getPid());
        plan.getPreservationActionPlan().touch();
    } catch (IOException e) {
        log.error("Error generating preservation action plan {}.", e.getMessage());
        throw new PlanningException("Error generating preservation action plan.", e);
    } catch (StorageException e) {
        log.error("An error occurred while storing the executable plan: {}", e.getMessage());
        throw new PlanningException("An error occurred while storing the profile", e);
    }
}

From source file:eu.scape_project.planning.xml.ProjectExporter.java

License:Apache License

/**
 * Writes the xml-representation of the given projects to the given target
 * file. NOTE: It writes all data - including encoded binary data - directly
 * to the DOM tree this may result in performance problems for large amounts
 * of data./*from  w w w  .  j  a v  a2  s  .  com*/
 * 
 * @param p
 *            the plan to export
 * @param target
 *            the file to write the plan
 * @throws IOException
 *             if an error occured during write
 * @throws PlanningException
 *             if an error occured during export
 */
public void exportToFile(Plan p, File target) throws IOException, PlanningException {
    XMLWriter writer = new XMLWriter(new FileWriter(target), ProjectExporter.prettyFormat);
    try {
        writer.write(exportToXml(p));
    } finally {
        writer.close();
    }
}

From source file:fedora.utilities.XMLDocument.java

License:fedora commons license

public void write(Writer writer) throws IOException {
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter output = new XMLWriter(writer, format);
    output.write(document);/*from  w  w w.ja  v a 2s .com*/
    output.close();
}

From source file:fr.gouv.culture.vitam.digest.DigestCompute.java

License:Open Source License

public static int createDigest(File src, File dst, File ftar, File fglobal, boolean oneDigestPerFile,
        List<File> filesToScan) {
    try {/*from   w  w w  .ja va2 s . c o  m*/
        Element global = null;
        Document globalDoc = null;
        if (fglobal != null) {
            global = XmlDom.factory.createElement("digests");
            global.addAttribute("source", src.getAbsolutePath());
            globalDoc = XmlDom.factory.createDocument(global);
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(StaticValues.CURRENT_OUTPUT_ENCODING);
        XMLWriter writer = new XMLWriter(format);
        int error = 0;
        int currank = 0;
        for (File file : filesToScan) {
            currank++;
            Element result = DigestCompute.checkDigest(StaticValues.config, src, file);
            if (result.selectSingleNode(".[@status='ok']") == null) {
                System.err.println(StaticValues.LBL.error_error.get()
                        + StaticValues.LBL.error_computedigest.get() + StaticValues.getSubPath(file, src));
                error++;
            } else if (oneDigestPerFile) {
                Element rootElement = XmlDom.factory.createElement("digest");
                Document unique = XmlDom.factory.createDocument(rootElement);
                rootElement.add(result);
                FileOutputStream out = null;
                String shortname = StaticValues.getSubPath(file, src);
                String shortnameWithoutFilename = shortname.substring(0, shortname.lastIndexOf(file.getName()));
                File fdirout = new File(dst, shortnameWithoutFilename);
                fdirout.mkdirs();
                File fout = new File(fdirout, file.getName() + "_digest.xml");
                try {
                    out = new FileOutputStream(fout);
                    writer.setOutputStream(out);
                    writer.write(unique);
                    writer.close();
                } catch (FileNotFoundException e) {
                    System.err.println(
                            StaticValues.LBL.error_error.get() + fout.getAbsolutePath() + " " + e.toString());
                    error++;
                } catch (IOException e) {
                    System.err.println(
                            StaticValues.LBL.error_error.get() + fout.getAbsolutePath() + " " + e.toString());
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e1) {
                        }
                    }
                    error++;
                }
                result.detach();
            }
            if (fglobal != null) {
                global.add(result);
            }
        }
        if (ftar != null) {
            currank++;
            Element result = DigestCompute.checkDigest(StaticValues.config, src, ftar);
            if (result.selectSingleNode(".[@status='ok']") == null) {
                System.err.println(StaticValues.LBL.error_error.get()
                        + StaticValues.LBL.error_computedigest.get() + ftar.getAbsolutePath());
                error++;
            } else if (oneDigestPerFile) {
                Element rootElement = XmlDom.factory.createElement("digest");
                Document unique = XmlDom.factory.createDocument(rootElement);
                rootElement.add(result);
                FileOutputStream out = null;
                File fout = new File(dst, ftar.getName() + "_tar_digest.xml");
                try {
                    out = new FileOutputStream(fout);
                    writer.setOutputStream(out);
                    writer.write(unique);
                    writer.close();
                } catch (FileNotFoundException e) {
                    System.err.println(
                            StaticValues.LBL.error_error.get() + fout.getAbsolutePath() + " " + e.toString());
                    error++;
                } catch (IOException e) {
                    System.err.println(
                            StaticValues.LBL.error_error.get() + fout.getAbsolutePath() + " " + e.toString());
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e1) {
                        }
                    }
                    error++;
                }
                result.detach();
            }
            if (fglobal != null) {
                global.add(result);
            }
        }
        if (fglobal != null) {
            if (error > 0) {
                global.addAttribute("status", "error");
            } else {
                global.addAttribute("status", "ok");
            }
            XmlDom.addDate(VitamArgument.ONEXML, StaticValues.config, global);
            FileOutputStream out;
            try {
                out = new FileOutputStream(fglobal);
                writer.setOutputStream(out);
                writer.write(globalDoc);
                writer.close();
            } catch (FileNotFoundException e) {
                System.err.println(
                        StaticValues.LBL.error_error.get() + fglobal.getAbsolutePath() + " " + e.toString());
                error++;
            } catch (IOException e) {
                System.err.println(
                        StaticValues.LBL.error_error.get() + fglobal.getAbsolutePath() + " " + e.toString());
                error++;
            }
        }
        if (error > 0) {
            System.err.println(StaticValues.LBL.error_error.get() + " Digest" + " [ " + currank
                    + (error > 0 ? " (" + StaticValues.LBL.error_error.get() + error + " ) " : "") + " ]");
            return -error;
        }
        return currank;
    } catch (UnsupportedEncodingException e) {
        System.err.println(StaticValues.LBL.error_error.get() + " " + e.toString());
        return -1;
    }

}