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(OutputFormat format) throws UnsupportedEncodingException 

Source Link

Usage

From source file:dk.netarkivet.harvester.tools.HarvestTemplateApplication.java

License:Open Source License

/**
 * Download the template with a given name.
 * The template is assumed to exist./*from www .  j  a v  a2  s.  co  m*/
 * @param templateName The name of a given template
 */
private static void download(final String templateName) {
    System.out.println("Downloading template '" + templateName + "'.");
    try {
        TemplateDAO dao = TemplateDAO.getInstance();
        HeritrixTemplate doc = dao.read(templateName);
        OutputStream os = new FileOutputStream(templateName + ".xml");
        XMLWriter writer = new XMLWriter(os);
        writer.write(doc.getTemplate());
    } catch (IOException e) {
        System.err.println("Error downloading template '" + templateName + "': " + e);
        e.printStackTrace(System.err);
    }
}

From source file:edu.scripps.fl.pubchem.web.session.WebSessionBase.java

License:Apache License

protected void debugDocumentToTempFile(Document doc, boolean displayFile) throws IOException {
    File file = File.createTempFile(getClass().getName(), ".html");
    XMLWriter writer = new XMLWriter(new FileOutputStream(file));
    writer.write(doc);/*from w  w  w.ja v a 2  s  .c om*/
    writer.close();
    if (displayFile)
        Desktop.getDesktop().open(file);
}

From source file:eml.studio.server.oozie.workflow.WFGraph.java

License:Open Source License

public static void main(String args[]) {

    Namespace rootNs = new Namespace("", "uri:oozie:workflow:0.4"); // root namespace uri
    QName rootQName = QName.get("workflow-app", rootNs); // your root element's name
    Element workflow = DocumentHelper.createElement(rootQName);
    Document doc = DocumentHelper.createDocument(workflow);

    workflow.addAttribute("name", "test");
    Element test = workflow.addElement("test");
    test.addText("hello");
    OutputFormat outputFormat = OutputFormat.createPrettyPrint();
    outputFormat.setEncoding("UTF-8");
    outputFormat.setIndent(true);//from  www  .  j  a  va2s.  com
    outputFormat.setIndent("    ");
    outputFormat.setNewlines(true);
    try {
        StringWriter stringWriter = new StringWriter();
        XMLWriter xmlWriter = new XMLWriter(stringWriter);
        xmlWriter.write(doc);
        xmlWriter.close();
        System.out.println(doc.asXML());
        System.out.println(stringWriter.toString().trim());

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

From source file:eu.planets_project.pp.plato.action.ProjectExportAction.java

License:Open Source License

/**
 * Exports the project identified by PlanProperties.Id ppid and writes the document
 * to the given OutputStream - including all binary data.
 * (currently required by {@link #exportAllProjectsToZip()} )
 * - Does NOT clean up temp files written to baseTempPath
 * /*from   ww  w .  j a  v a2 s .c o  m*/
 * @param ppid
 * @param out
 * @param baseTempPath used to write temp files for binary data, 
 *        must not be used by other exports at the same time
 */
public void exportComplete(int ppid, OutputStream out, String baseTempPath) {
    BASE64Encoder encoder = new BASE64Encoder();
    ProjectExporter exporter = new ProjectExporter();
    Document doc = exporter.createProjectDoc();

    //        int i = 0;
    List<Plan> list = null;
    try {
        list = em.createQuery("select p from Plan p where p.planProperties.id = " + ppid).getResultList();
    } catch (Exception e1) {
        list = new ArrayList<Plan>();
        FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR,
                "An error occured while generating the export file.");
        log.error("Could not load planProperties: ", e1);
    }
    try {
        if (list.size() != 1) {
            FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR,
                    "Skipping the export of the plan with properties" + ppid + ": Couldnt load.");
        } else {
            //log.debug("adding project "+p.getplanProperties().getName()+" to XML...");
            String tempPath = baseTempPath;
            File tempDir = new File(tempPath);
            tempDir.mkdirs();

            List<Integer> uploadIDs = new ArrayList<Integer>();
            List<Integer> recordIDs = new ArrayList<Integer>();
            try {
                exporter.addProject(list.get(0), doc, uploadIDs, recordIDs);

                writeBinaryObjects(recordIDs, uploadIDs, tempPath, encoder);
                // perform XSLT transformation to get the DATA into the PLANS
                XMLWriter writer = new XMLWriter(
                        new FileOutputStream("/tmp/testout" + System.currentTimeMillis() + ".xml"));
                writer.write(doc);
                writer.close();
                addBinaryData(doc, out, tempPath);
            } 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);
            } catch (TransformerException e) {
                FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR,
                        "An error occured while generating the export file.");
                log.error(e);
            }
        }
    } finally {
        /* clean up */
        list.clear();
        list = null;

        em.clear();
        System.gc();
    }

}

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  ww.  j  a v a  2 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;
    }

}

From source file:gjset.client.ConcreteClientCommunicator.java

License:Open Source License

private void createIOStreams() throws IOException {
    writer = new XMLWriter(socket.getOutputStream());
    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    XMLreader = new SAXReader();
}

From source file:gjset.server.PlayerClientHandler.java

License:Open Source License

private void createIOStreams() throws IOException {
    try {/*from   w ww .j  a va  2  s.c  o  m*/
        writer = new XMLWriter(socket.getOutputStream());
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    final SAXReader XMLreader = new SAXReader();

    Runnable listenForMessage = new Runnable() {
        public void run() {
            try {
                String textReceived = reader.readLine();
                while (socket.isConnected() && textReceived != null) {
                    // Create an input stream to allow the XML parser to read from the string.
                    InputStream stringInput = new ByteArrayInputStream(textReceived.getBytes());
                    Document document = XMLreader.read(stringInput);

                    // Now receive the message.
                    receiveMessage(document.getRootElement());

                    // Then go looking for the next message.
                    textReceived = reader.readLine();
                }

                destroy();
            } catch (IOException e) {
                System.err.println(
                        "IO Exception reading input in client handler. (Possibly because of closed socket.)");
                //e.printStackTrace();
            } catch (DocumentException e) {
                System.err.println("Document Exception parsing text in client handler.");
                //e.printStackTrace();
            }
        }
    };

    listeningThread = new Thread(listenForMessage, "Client Handler Thread");
}

From source file:gjset.tests.MockClient.java

License:Open Source License

private void createIOStreams() throws IOException {
    writer = new XMLWriter(socket.getOutputStream());
    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    XMLreader = new SAXReader();

    Runnable listenForMessage = new Runnable() {
        public void run() {
            try {
                String textReceived = reader.readLine();
                while (socket.isConnected() && textReceived != null) {
                    // Create an input stream to allow the XML parser to read from the string.
                    InputStream stringInput = new ByteArrayInputStream(textReceived.getBytes());
                    Document document = XMLreader.read(stringInput);

                    // Now receive teh message.
                    receiveMessage(document.getRootElement());

                    // Then go looking for the next message.
                    textReceived = reader.readLine();
                }/* w ww .j ava2  s . c  o  m*/
            } catch (IOException e) {
                System.err
                        .println("IO Exception reading input in client. (Possibly because of closed socket.)");
                //e.printStackTrace();
            } catch (DocumentException e) {
                System.err.println("Document Exception parsing text in client.");
                //e.printStackTrace();
            }
        }
    };

    listeningThread = new Thread(listenForMessage);
}

From source file:gjset.tools.MessageUtils.java

License:Open Source License

/**
 * Useful for debugging, this command pretty prints XML.
 * //from w w w  .  j  av a2  s  .co  m
 * @param element
 * @return
 */
public static String prettyPrint(Element element) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    XMLWriter writer;
    try {
        writer = new XMLWriter(stream);
        writer.write(element);
        writer.flush();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return stream.toString();
}

From source file:hk.hku.cecid.ebms.pkg.PKISignatureImpl.java

License:Open Source License

void sign(String alias, char[] password, String keyStoreLocation, String algo, String digestAlgo,
        boolean signEnvelopeOnly) throws SignatureException {
    try {/*from   ww w  .j a  v a  2 s .  co  m*/
        final SOAPPart soapPart = ebxmlMessage.getSOAPMessage().getSOAPPart();
        DocumentResult docResult = new DocumentResult();
        TransformerFactory.newInstance().newTransformer().transform(soapPart.getContent(), docResult);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        (new XMLWriter(baos)).write(docResult.getDocument());
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        // soapPartDocument is a DOM equivilance of soapPart
        final Document soapPartDocument = factory.newDocumentBuilder()
                .parse(new ByteArrayInputStream(baos.toByteArray()));
        final String soapHeaderName = soapPart.getEnvelope().getHeader().getElementName().getLocalName();
        final Element soapHeader = (Element) soapPartDocument
                .getElementsByTagNameNS(NAMESPACE_URI_SOAP_ENVELOPE, soapHeaderName).item(0);
        ApacheXMLDSigner signature = new ApacheXMLDSigner();
        CompositeKeyStore ks = new CompositeKeyStore();
        ks.addKeyStoreFile(keyStoreLocation, null, password);
        PrivateKey pk = (PrivateKey) ks.getKey(alias, password);
        /* 
         * To reduce the complexity of the exception message,
         * the exception can be catch on the final catch block.
         *  
         try {
        pk = (PrivateKey) ks.getKey(alias, password);
        if(pk ==null){
           String message ="Cannot retrieve key from keystore["+keyStoreLocation+"]" +"\n"+
              "KeyStore Type: " + ks.getKeyStore().getType() +"\n"+
              "Key Provider: " + ks.getKeyStore().getProvider().getInfo();
           throw new NullPointerException(message);
        }
        }
        catch (Exception e) {
        String err = "Cannot get private key: " + alias + " - "
            + e.getMessage();
           logger.warn(err);
        throw new SignException(err);
        }*/

        if (algo != null) {
            if (!isAlgorithmMatchedWithKey(pk, algo)) {
                throw new SignException("Signing algorithm not matched with key algorithm, "
                        + "actual key algorithum:" + pk.getAlgorithm() + "\t" + "expect algorithum: " + algo);
            }
            if (digestAlgo == null) {
                signature.setEnvelope(soapPartDocument, algo);
            } else {
                signature.setEnvelope(soapPartDocument, algo, digestAlgo);
            }
        } else {
            String keyAlgo = getAlgorithmFromPrivateKey(pk);
            signature.setEnvelope(soapPartDocument, keyAlgo);
        }
        /*
        if (algo == null) {
        // use default algorithm, i.e. dsa-sha1
        signature.setEnvelope(soapPartDocument);
        }
        else {
        // use user-defined algorithm, only support dsa-sha1 and 
        // rsa-sha1
        if (digestAlgo == null) {
            signature.setEnvelope(soapPartDocument, algo);
        } else {
            signature.setEnvelope(soapPartDocument, algo, digestAlgo);
        }
        }
        */

        // important, if not, the transformation will fail
        soapHeader.appendChild(signature.getElement());

        if (!signEnvelopeOnly) {
            Iterator i = ebxmlMessage.getPayloadContainers();
            while (i.hasNext()) {
                PayloadContainer pc = (PayloadContainer) i.next();
                signature.addDocument(pc.getHref(), pc.getDataHandler().getInputStream(), pc.getContentType());
            }
        }

        signature.sign(ks, alias, password);

        domToSoap(signature.getElement(), this);

        Iterator childElements = getChildElements(SignatureReference.SIGNATURE_REFERENCE);
        if (childElements.hasNext()) {
            while (childElements.hasNext()) {
                references.add(new SignatureReference(soapEnvelope, (SOAPElement) childElements.next()));
            }
        } else {
            throw new SOAPValidationException(SOAPValidationException.SOAP_FAULT_CLIENT,
                    "<" + NAMESPACE_PREFIX_DS + ":" + SignatureReference.SIGNATURE_REFERENCE
                            + "> is not found in <" + NAMESPACE_PREFIX_DS + ":" + ELEMENT_SIGNATURE + ">!");
        }

        childElements = getChildElements(ELEMENT_SIGNATURE_VALUE);
        if (childElements.hasNext()) {
            signatureValue = ((SOAPElement) childElements.next()).getValue();
        } else {
            throw new SOAPValidationException(SOAPValidationException.SOAP_FAULT_CLIENT,
                    "<" + NAMESPACE_PREFIX_DS + ":" + ELEMENT_SIGNATURE_VALUE + "> is not found in <"
                            + NAMESPACE_PREFIX_DS + ":" + ELEMENT_SIGNATURE + ">!");
        }
    } catch (Exception e) {
        String err = ErrorMessages.getMessage(ErrorMessages.ERR_PKI_CANNOT_SIGN, e);
        err += "\n" + "Try to retreive key alias[" + alias + "] from keystore[" + keyStoreLocation + "]";
        throw new SignatureException(err, e);
    }
}