Example usage for org.dom4j.io XMLWriter XMLWriter

List of usage examples for org.dom4j.io XMLWriter XMLWriter

Introduction

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

Prototype

public XMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException 

Source Link

Usage

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  ww w.j  a va 2s . c o  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  ww  w. j ava2s.  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();/*  ww w.  ja  v a2  s. co m*/
}

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.  
 *///from ww w  .  j  a  v a  2 s. co m
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

/**
 * /* ww  w . j  a  v a  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   w w w .  j  a  v  a 2 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.plan.XMLDataWrapper.java

License:Apache License

/**
 * Reads an XML element and <code>value</code> and keeps this data for the
 * next call of {@link #setData(Object)}.
 * /*from   ww w  .j a va 2s  . c om*/
 * Additionally checks the <code>value</code> if a <code>changelog</code>
 * element is present and stores it for the next call of
 * {@link #setChangeLog(Object)}.
 * 
 * @param value
 *            the value to create
 * @throws IOException
 *             if the data could not be written
 * @throws ParseException
 *             if the data could not be parsed
 */
public void setEncoded(Element value) throws IOException, ParseException {

    DOMReader reader = new DOMReader();
    org.w3c.dom.Document w3cDocument = value.getOwnerDocument();
    w3cDocument.appendChild(value);
    Document doc = reader.read(w3cDocument);

    org.dom4j.Element changeLogElement = (org.dom4j.Element) doc
            .selectSingleNode("//*[local-name()='changelog']");
    createChangeLog(changeLogElement);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    XMLWriter writer = new XMLWriter(out, outputFormat);
    writer.write(doc);

    this.data = out.toByteArray();

}

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 ww .  ja v  a 2 s .c  om*/
 * 
 * @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);/* www .  ja v  a 2  s .  c  om*/
    output.close();
}

From source file:fr.gouv.culture.vitam.command.VitamCommand.java

License:Open Source License

public static void computeDigest() {
    XMLWriter writer = null;// w w  w .j a  va  2s . co m
    try {
        writer = new XMLWriter(outputStream, StaticValues.defaultOutputFormat);
    } catch (UnsupportedEncodingException e1) {
        System.err.println(StaticValues.LBL.error_writer.get() + ": " + e1.toString());
        return;
    }
    File basedir = new File(checkDigest);
    List<File> files;
    try {
        files = DroidHandler.matchedFiled(new File[] { basedir }, extensions,
                StaticValues.config.argument.recursive);
    } catch (CommandExecutionException e1) {
        System.err.println(StaticValues.LBL.error_error.get() + e1.toString());
        return;
    }
    System.out.println("Digest...");
    Element root = null;
    VitamResult vitamResult = new VitamResult();
    if (basedir.isFile()) {
        basedir = basedir.getParentFile();
    }
    if (StaticValues.config.argument.outputModel == VitamOutputModel.OneXML) {
        root = XmlDom.factory.createElement("digests");
        root.addAttribute("source", basedir.getAbsolutePath());
        vitamResult.unique = XmlDom.factory.createDocument(root);
    }
    int currank = 0;
    int error = 0;
    for (File file : files) {
        currank++;
        String shortname;
        shortname = StaticValues.getSubPath(file, basedir);
        FileInputStream inputstream;
        try {
            inputstream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            System.err.println(StaticValues.LBL.error_computedigest.get() + ": " + shortname);
            continue;
        }
        String[] shas = DigestCompute.computeDigest(inputstream, StaticValues.config.argument);
        //SEDA type since already configured
        Element result = XmlDom.factory.createElement(StaticValues.config.DOCUMENT_FIELD);
        Element attachment = XmlDom.factory.createElement(StaticValues.config.ATTACHMENT_FIELD);
        attachment.addAttribute(StaticValues.config.FILENAME_ATTRIBUTE.substring(1), shortname);
        result.add(attachment);
        if (shas[0] != null) {
            Element integrity = XmlDom.factory.createElement(StaticValues.config.INTEGRITY_FIELD);
            integrity.addAttribute(StaticValues.config.ALGORITHME_ATTRIBUTE.substring(1),
                    StaticValues.XML_SHA1);
            integrity.setText(shas[0]);
            result.add(integrity);
        }
        if (shas[1] != null) {
            Element integrity = XmlDom.factory.createElement(StaticValues.config.INTEGRITY_FIELD);
            integrity.addAttribute(StaticValues.config.ALGORITHME_ATTRIBUTE.substring(1),
                    StaticValues.XML_SHA256);
            integrity.setText(shas[1]);
            result.add(integrity);
        }
        if (shas[2] != null) {
            Element integrity = XmlDom.factory.createElement(StaticValues.config.INTEGRITY_FIELD);
            integrity.addAttribute(StaticValues.config.ALGORITHME_ATTRIBUTE.substring(1),
                    StaticValues.XML_SHA512);
            integrity.setText(shas[2]);
            result.add(integrity);
        }
        if ((shas[0] == null && StaticValues.config.argument.sha1)
                || (shas[1] == null && StaticValues.config.argument.sha256)
                || (shas[2] == null && StaticValues.config.argument.sha512)) {
            result.addAttribute("status", "error");
            error++;
        } else {
            result.addAttribute("status", "ok");
        }
        XmlDom.addDate(StaticValues.config.argument, StaticValues.config, result);
        if (root != null) {
            root.add(result);
        } else {
            // multiple
            root = XmlDom.factory.createElement("digests");
            root.addAttribute("source", basedir.getAbsolutePath());
            root.add(result);
            try {
                writer.write(root);
            } catch (IOException e) {
                System.err.println(StaticValues.LBL.error_error.get() + e.toString());
            }
            root = null;
        }
    }
    if (root != null) {
        if (error == 0) {
            root.addAttribute("status", "ok");
        } else {
            root.addAttribute("status", "error on " + error + " / " + currank + " file checks");
        }
        XmlDom.addDate(StaticValues.config.argument, StaticValues.config, root);
        try {
            writer.write(vitamResult.unique);
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_analysis.get() + e);
        }
    }
    System.out.println(StaticValues.LBL.action_digest.get() + " [ " + currank
            + (error > 0 ? " (" + StaticValues.LBL.error_error.get() + error + " ) " : "") + " ]");
}