Example usage for org.dom4j DocumentHelper createDocument

List of usage examples for org.dom4j DocumentHelper createDocument

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper createDocument.

Prototype

public static Document createDocument(Element rootElement) 

Source Link

Usage

From source file:cz.fi.muni.xkremser.editor.server.OAIPMHClientImpl.java

License:Open Source License

@Override
public ArrayList<MetadataBundle> search(String url) {
    ArrayList<MetadataBundle> retList = new ArrayList<MetadataBundle>();
    try {/*  w  w w  .  j  a  v  a  2  s.c o m*/
        if (!url.startsWith("http")) {
            url = "http://" + url;
        }
        if (marc2mods == null) {
            if (!new File(config.getEditorHome() + MARC_TO_MODS_XSLT).exists()) {
                LOGGER.error("File " + config.getEditorHome() + MARC_TO_MODS_XSLT + " does not exist.");
                return retList;
            }
            marc2mods = Dom4jUtils.loadDocument(new File(config.getEditorHome() + MARC_TO_MODS_XSLT), true);
        }
        InputStream marcStream = RESTHelper.get(url + MARC_METADATA_PREFIX, null, null, false);

        if (marc2dc == null) {
            if (!new File(config.getEditorHome() + MARC_TO_DC_XSLT).exists()) {
                LOGGER.error("File " + config.getEditorHome() + MARC_TO_DC_XSLT + " does not exist.");
                return retList;
            }
            marc2dc = Dom4jUtils.loadDocument(new File(config.getEditorHome() + MARC_TO_DC_XSLT), true);
        }

        //            StringWriter writer = new StringWriter();
        //            IOUtils.copy(marcStream, writer, "UTF-8");
        //            String theString = writer.toString();
        //            System.out.println(theString);

        Document marcDoc = Dom4jUtils.loadDocument(marcStream, true);
        if (marcDoc.asXML().contains("idDoesNotExist") || marcDoc.asXML().contains("cannotDisseminateFormat")) {
            return retList;
        }

        MarcDocument mrc = new MarcDocument(marcDoc);
        MarcSpecificMetadata marcSpecific = new MarcSpecificMetadata(mrc.findSysno(), mrc.findBase(),
                mrc.find040a(), mrc.find080a(), mrc.find650a(), mrc.find260aCorrected(),
                mrc.find260bCorrected(), mrc.find260c());
        @SuppressWarnings("unused")
        InputStream dcStream = null;
        @SuppressWarnings("unused")
        boolean dcSuccess = true;
        try {
            dcStream = RESTHelper.get(url + OAI_METADATA_PREFIX, null, null, false);
        } catch (IOException e) {
            LOGGER.warn(e.getMessage());
            dcSuccess = false;
        }
        Document dcDoc = Dom4jUtils.transformDocument(marcDoc, marc2dc);
        //            Document dcDoc = Dom4jUtils.loadDocument(dcStream, true);
        Document modsDoc = Dom4jUtils.transformDocument(marcDoc, marc2mods);

        //            System.out.println("\n\n\n*****\n\n\n");
        //            Dom4jUtils.writeDocument(marcDoc, System.out, PrintType.PRETTY);
        //            System.out.println("\n\n\n*****\n\n\n");
        //            Dom4jUtils.writeDocument(dcDoc, System.out, PrintType.PRETTY);
        //            System.out.println("\n\n\n*****\n\n\n");
        //            Dom4jUtils.writeDocument(modsDoc, System.out, PrintType.PRETTY);
        //            System.out.println("\n\n\n*****\n\n\n");

        Element dcElement = (Element) dcXPath.selectSingleNode(dcDoc);
        final DublinCore dc = DCUtils.getDC(DocumentHelper.createDocument(dcElement.createCopy()).asXML());
        dc.removeTrailingSlash();
        if (dc != null && dc.getTitle() != null && dc.getTitle().size() != 0 && dc.getTitle().get(0) != null
                && "".equals(dc.getTitle().get(0).trim())) {
            dc.addTitle("no title");
        }
        ModsType mods = BiblioModsUtils.getMods(XMLUtils.parseDocument(modsDoc.asXML(), true));
        final ModsCollection modsC = new ModsCollection();
        modsC.setMods(Arrays.asList(mods));
        MetadataBundle bundle = new MetadataBundle(dc, BiblioModsUtils.toModsClient(modsC), marcSpecific);
        retList.add(bundle);
        return retList;
    } catch (ParserConfigurationException e) {
        LOGGER.error(e.getMessage());
    } catch (SAXException e) {
        LOGGER.error(e.getMessage());
    } catch (DocumentException e) {
        LOGGER.error(e.getMessage());
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
    }
    return retList;
}

From source file:cz.mzk.editor.server.metadataDownloader.OAIPMHClientImpl.java

License:Open Source License

@Override
public ArrayList<MetadataBundle> search(String url, String base) {
    ArrayList<MetadataBundle> retList = new ArrayList<MetadataBundle>();
    try {/*from   w ww. j  a  va 2  s  . c o  m*/
        if (!url.startsWith("http")) {
            url = "http://" + url;
        }
        if (marc2mods == null) {
            if (!new File(config.getEditorHome() + MARC_TO_MODS_XSLT).exists()) {
                LOGGER.error("File " + config.getEditorHome() + MARC_TO_MODS_XSLT + " does not exist.");
                return retList;
            }
            marc2mods = Dom4jUtils.loadDocument(new File(config.getEditorHome() + MARC_TO_MODS_XSLT), true);
        }
        InputStream marcStream = RESTHelper.get(url + MARC_METADATA_PREFIX, null, null, false);

        if (marc2dc == null) {
            if (!new File(config.getEditorHome() + MARC_TO_DC_XSLT).exists()) {
                LOGGER.error("File " + config.getEditorHome() + MARC_TO_DC_XSLT + " does not exist.");
                return retList;
            }
            marc2dc = Dom4jUtils.loadDocument(new File(config.getEditorHome() + MARC_TO_DC_XSLT), true);
        }

        if (!checkAndReplace(marc2mods, false))
            checkAndReplace(marc2dc, true);

        //            StringWriter writer = new StringWriter();
        //            IOUtils.copy(marcStream, writer, "UTF-8");
        //            String theString = writer.toString();
        //            System.out.println(theString);

        Document marcDoc = Dom4jUtils.loadDocument(marcStream, true);
        if (marcDoc.asXML().contains("idDoesNotExist") || marcDoc.asXML().contains("cannotDisseminateFormat")) {
            return retList;
        }

        MarcDocument mrc = new MarcDocument(marcDoc);
        MarcSpecificMetadata marcSpecific = new MarcSpecificMetadata(mrc.findSysno(), base, mrc.find040a(),
                mrc.find080a(), mrc.find650a(), mrc.find260aCorrected(), mrc.find260bCorrected(),
                mrc.find260c(), mrc.find910b());
        @SuppressWarnings("unused")
        InputStream dcStream = null;
        @SuppressWarnings("unused")
        boolean dcSuccess = true;
        try {
            dcStream = RESTHelper.get(url + OAI_METADATA_PREFIX, null, null, false);
        } catch (IOException e) {
            LOGGER.warn(e.getMessage());
            dcSuccess = false;
        }
        Document dcDoc = Dom4jUtils.transformDocument(marcDoc, marc2dc);
        //            Document dcDoc = Dom4jUtils.loadDocument(dcStream, true);
        Document modsDoc = Dom4jUtils.transformDocument(marcDoc, marc2mods);

        //            System.out.println("\n\n\n*****\n\n\n");
        //            Dom4jUtils.writeDocument(marcDoc, System.out, PrintType.PRETTY);
        //            System.out.println("\n\n\n*****\n\n\n");
        //            Dom4jUtils.writeDocument(dcDoc, System.out, PrintType.PRETTY);
        //            System.out.println("\n\n\n*****\n\n\n");
        //            Dom4jUtils.writeDocument(modsDoc, System.out, PrintType.PRETTY);
        //            System.out.println("\n\n\n*****\n\n\n");

        Element dcElement = (Element) dcXPath.selectSingleNode(dcDoc);
        final DublinCore dc = DCUtils.getDC(DocumentHelper.createDocument(dcElement.createCopy()).asXML());
        dc.removeTrailingSlash();
        if (dc != null && dc.getTitle() != null && dc.getTitle().size() != 0 && dc.getTitle().get(0) != null
                && "".equals(dc.getTitle().get(0).trim())) {
            dc.addTitle("no title");
        }
        ModsType mods = BiblioModsUtils.getMods(XMLUtils.parseDocument(modsDoc.asXML(), true));
        final ModsCollection modsC = new ModsCollection();
        modsC.getMods().addAll(Arrays.<ModsType>asList(mods));
        MetadataBundle bundle = new MetadataBundle(dc, BiblioModsUtils.toModsClient(modsC), marcSpecific);
        retList.add(bundle);
        return retList;
    } catch (ParserConfigurationException e) {
        LOGGER.error(e.getMessage());
    } catch (SAXException e) {
        LOGGER.error(e.getMessage());
    } catch (DocumentException e) {
        LOGGER.error(e.getMessage());
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
    }
    return retList;
}

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

License:Open Source License

/**
 * Writes the block to a stream as XML/*w  w  w . ja v  a  2 s .  co  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:edu.upenn.cis.orchestra.reconciliation.bdbstore.BdbDataSetFactory.java

License:Apache License

/**
 * Returns a {@code FlatXmlDataSet} representation of the underlying
 * Berkeley database./*www.j  a va 2  s . com*/
 * 
 * @return a {@code FlatXmlDataSet} representation of the Berkeley database.
 * @throws Exception
 */
public FlatXmlDataSet getDataSet() throws Exception {

    Element root = DocumentHelper.createElement("dataset");
    Document dsDoc = DocumentHelper.createDocument(root);
    DefaultDataSet dataset = new DefaultDataSet();
    initializeEnvironments(usHome, cdss, peerNames);
    BdbEnvironment envFormat = env.getFormat();

    List<Database> dbs = env.getDbs();

    processDatabases(root, dataset, envFormat, dbs);
    for (IBdbStoreEnvironment ss : stateStoreEnvs) {
        BdbEnvironment stateStoreFormat = ss.getFormat();
        List<Database> ssDbs = ss.getDbs();
        processDatabases(root, dataset, stateStoreFormat, ssDbs);
    }
    close();
    return new FlatXmlDataSet(new StringReader(dsDoc.asXML()), false, true, false);
}

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

License:Open Source License

/**
 * Transform the Graph into an workflow xml definition
 * @param jobname the job name of Oozie job, can't be null
 * @return workflow xml// w w  w.j a v a  2s  .c o m
 */
public String toWorkflow(String jobname) {
    Namespace xmlns = new Namespace("", "uri:oozie:workflow:0.4"); // root namespace uri
    QName qName = QName.get("workflow-app", xmlns); // your root element's name
    Element workflow = DocumentHelper.createElement(qName);
    Document xmldoc = DocumentHelper.createDocument(workflow);
    // Create workflow root
    workflow.addAttribute("xmlns", "uri:oozie:workflow:0.4");
    // <workflow-app name='xxx'></workflow-app>
    if (jobname == null || "".equals(jobname))
        workflow.addAttribute("name", "Not specified");
    else
        workflow.addAttribute("name", jobname);

    Queue<NodeDef> que = new LinkedList<NodeDef>();
    que.add(start);

    while (!que.isEmpty()) {
        NodeDef cur = que.remove();

        cur.append2XML(workflow);

        for (NodeDef toNode : cur.getOutNodes()) {
            toNode.delInNode(cur);
            if (toNode.getInDegree() == 0)
                que.add(toNode);
        }
    }

    // Set XML document format
    OutputFormat outputFormat = OutputFormat.createPrettyPrint();
    // Set XML encoding, use the specified encoding to save the XML document to the string, it can be specified GBK or ISO8859-1
    outputFormat.setEncoding("UTF-8");
    outputFormat.setSuppressDeclaration(true); // Whether generate xml header
    outputFormat.setIndent(true); // Whether set indentation
    outputFormat.setIndent("    "); // Implement indentation with four spaces
    outputFormat.setNewlines(true); // Set whether to wrap

    try {
        // stringWriter is used to save xml document
        StringWriter stringWriter = new StringWriter();
        // xmlWriter is used to write XML document to string(tool)
        XMLWriter xmlWriter = new XMLWriter(stringWriter, outputFormat);

        // Write the created XML document into the string
        xmlWriter.write(xmldoc);

        xmlWriter.close();

        System.out.println(stringWriter.toString().trim());
        // Print the string, that is, the XML document
        return stringWriter.toString().trim();

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

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 va  2 s.  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:ie.cmrc.smtx.base.serialisation.rdfxml.RDFXMLSerialiser.java

License:Apache License

/**
 * Creates an RDF document containing the XML representation of the provided
 * resource/*from  w  w w.j  a v a2s  .  co  m*/
 * @param resource An {@link RDFXMLisable} instance
 * @param elementSet Specifies the level of information to serialise
 * (see {@link ElementSetName} for more details)
 * @param language Language code. Only annotations in this language will
 * be included in the XML.
 * @return XML document
 */
public static Document makeRDFXMLDocument(RDFXMLisable resource, ElementSetName elementSet, String language) {
    Element rdfElt = DocumentHelper.createElement(new QName("RDF", Namespaces.RDF));
    rdfElt.add(Namespaces.RDF);
    rdfElt.add(Namespaces.RDFS);
    rdfElt.add(Namespaces.OWL);
    rdfElt.add(Namespaces.SKOS);
    rdfElt.add(Namespaces.XSD);

    if (resource != null) {
        Element xmlElement = resource.toXMLElement(elementSet, language);
        if (xmlElement != null)
            rdfElt.add(xmlElement);
    }

    Document doc = DocumentHelper.createDocument(rdfElt);

    return doc;
}

From source file:ie.cmrc.smtx.base.serialisation.rdfxml.RDFXMLSerialiser.java

License:Apache License

/**
 * Creates an RDF document containing the XML representation of the provided
 * resources// ww w .j av  a2 s  .c  om
 * @param resources A collection of {@link RDFXMLisable} instances
 * @param elementSet Specifies the level of information to serialise
 * (see {@link ElementSetName} for more details)
 * @param language Language code. Only annotations in this language will
 * be included in the XML.
 * @return XML document
 */
public static Document makeRDFXMLDocument(Collection<? extends RDFXMLisable> resources,
        ElementSetName elementSet, String language) {
    Element rdfElt = DocumentHelper.createElement(new QName("RDF", Namespaces.RDF));
    rdfElt.add(Namespaces.RDF);
    rdfElt.add(Namespaces.RDFS);
    rdfElt.add(Namespaces.OWL);
    rdfElt.add(Namespaces.SKOS);
    rdfElt.add(Namespaces.XSD);

    if (resources != null) {
        for (RDFXMLisable resource : resources) {
            if (resource != null) {
                Element xmlElement = resource.toXMLElement(elementSet, language);
                if (xmlElement != null)
                    rdfElt.add(xmlElement);
            }
        }
    }

    Document doc = DocumentHelper.createDocument(rdfElt);

    return doc;
}

From source file:ie.cmrc.smtx.base.serialisation.rdfxml.RDFXMLSerialiser.java

License:Apache License

/**
 * Creates an RDF document containing the XML representation of the provided
 * resources//ww  w  .j a  v  a2 s . c o m
 * @param resources An iterator over {@link RDFXMLisable} instances
 * @param elementSet Specifies the level of information to serialise
 * (see {@link ElementSetName} for more details)
 * @param language Language code. Only annotations in this language will
 * be included in the XML.
 * @return XML document
 */
public static Document makeRDFXMLDocument(Iterator<? extends RDFXMLisable> resources, ElementSetName elementSet,
        String language) {
    Element rdfElt = DocumentHelper.createElement(new QName("RDF", Namespaces.RDF));
    rdfElt.add(Namespaces.RDF);
    rdfElt.add(Namespaces.RDFS);
    rdfElt.add(Namespaces.OWL);
    rdfElt.add(Namespaces.SKOS);
    rdfElt.add(Namespaces.XSD);

    if (resources != null) {
        while (resources.hasNext()) {
            RDFXMLisable resource = resources.next();
            if (resource != null) {
                Element xmlElement = resource.toXMLElement(elementSet, language);
                if (xmlElement != null)
                    rdfElt.add(xmlElement);
            }
        }
    }

    Document doc = DocumentHelper.createDocument(rdfElt);

    return doc;
}

From source file:ie.cmrc.smtx.sws.exceptions.SWSExceptionReport.java

License:Apache License

public Document getXML() {

    if (!this.isEmpty()) {

        Namespace sws = new Namespace("sws", swsURI);
        Namespace xml = new Namespace("xml", xmlURI);
        //Namespace xsi = new Namespace("xsi", xsiURI);

        QName exReportQN = new QName("ExceptionReport", sws);

        Element exceptionReport = DocumentHelper.createElement(exReportQN);

        exceptionReport.add(xml);//from w  w w  . j  a v a2  s .c  o  m
        exceptionReport.add(sws);
        //exceptionReport.add(xsi);

        //QName schemaLocQN = new QName ("schemaLocation", xsi);
        //exceptionReport.addAttribute(schemaLocQN, this.xsiSchameLocation);

        //Language
        if (this.language != null) {
            if (!this.language.trim().equals("")) {
                QName langQN = new QName("lang", xml);
                exceptionReport.addAttribute(langQN, this.language.trim());
            }
        }

        //Version
        exceptionReport.addAttribute("version", this.version);

        QName exceptionQN = new QName("Exception", sws);
        for (SWSException e : this.exceptions) {
            if (e != null) {
                Element exception = exceptionReport.addElement(exceptionQN).addAttribute("code", e.getCode());
                if (e.getLocator() != null) {
                    if (!e.getLocator().trim().equals("")) {
                        exception.addAttribute("locator", e.getLocator().trim());
                    }
                }

                if (e.getMessage() != null) {
                    QName messageQN = new QName("Message", sws);
                    exception.addElement(messageQN).addText(e.getMessage());
                }
            }
        }

        Document exceptionReportDoc = DocumentHelper.createDocument(exceptionReport);
        return exceptionReportDoc;

    } else {
        //Raise Empty exceptionReport exception
        return null;
    }
}