Example usage for org.dom4j Document setDocType

List of usage examples for org.dom4j Document setDocType

Introduction

In this page you can find the example usage for org.dom4j Document setDocType.

Prototype

void setDocType(DocumentType docType);

Source Link

Document

Sets the DocumentType property

Usage

From source file:com.mg.framework.support.ui.UIProducer.java

License:Open Source License

public static Document performDocument(Document document, RuntimeMacrosLoader runtimeMacrosLoader) {
    logger.debug("Original form descriptor:\n".concat(document.asXML()));
    Document result = DocumentFactory.getInstance().createDocument(document.getXMLEncoding());
    result.setDocType(document.getDocType());
    result.setRootElement(copyElement(document.getRootElement(), runtimeMacrosLoader));
    result.getRootElement().addNamespace(document.getRootElement().getNamespacePrefix(),
            document.getRootElement().getNamespaceURI());
    try {//from  www.ja  v  a2  s .  co m
        //?   ?,  ?  ? namespaces
        result = DocumentHelper.parseText(result.asXML());
        logger.debug("Finished form descriptor:\n".concat(result.asXML()));
        return result;
    } catch (DocumentException e) {
        throw new ApplicationException(e);
    }
}

From source file:de.innovationgate.wga.common.beans.hdbmodel.ModelDefinition.java

License:Open Source License

public static ModelDefinition read(InputStream in) throws Exception {

    // First read XML manually and validate against the DTD provided in this OpenWGA distribution (to prevent it being loaded from the internet, which might not work, see #00003612) 
    SAXReader reader = new SAXReader();
    reader.setIncludeExternalDTDDeclarations(true);
    reader.setIncludeInternalDTDDeclarations(true);
    reader.setEntityResolver(new EntityResolver() {

        @Override/*w  w  w  .  j a va2 s  .  c o m*/
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

            if (systemId.equals("http://doc.openwga.com/hdb-model-definition-6.0.dtd")) {
                return new InputSource(ModelDefinition.class.getClassLoader().getResourceAsStream(
                        WGUtils.getPackagePath(ModelDefinition.class) + "/hdb-model-definition-6.0.dtd"));
            } else {
                // use the default behaviour
                return null;
            }

        }

    });

    org.dom4j.Document domDoc = reader.read(in);

    // Remove doctype (we already have validated) and provide the resulting XML to the serializer
    domDoc.setDocType(null);
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out);
    writer.write(domDoc);
    String xml = out.toString();

    return _serializer.read(ModelDefinition.class, new StringReader(xml));
}

From source file:net.sf.ginp.setup.SetupManagerImpl.java

License:Open Source License

/**
 * @param visit//from   w  w  w.  ja v a2 s  . c  o m
 * @return
 * @throws DocumentException
 * @throws TransformerException
 */
private Document getConfigFromSetupVisit(final SetupVisit visit)
        throws DocumentException, TransformerException {
    XStream stream = new XStream();
    String visitXML = stream.toXML(visit);
    SAXReader read = new SAXReader();
    Document visitDoc = read.read(new StringReader(visitXML));
    Document outputDocument = GinpUtil.transform("/net/sf/ginp/setup/visitToConfig.xsl", visitDoc);

    // necessary because the xsl transform ignores the XSL:output tag
    outputDocument.setDocType(new DefaultDocumentType("ginp", "-//GINP//DTD ginp XML//EN", "ginp.dtd"));

    return outputDocument;
}

From source file:org.alfresco.repo.security.permissions.impl.model.PermissionModel.java

License:Open Source License

private InputStream processModelDocType(InputStream is, String dtdSchemaUrl)
        throws DocumentException, IOException {
    SAXReader reader = new SAXReader();
    // read document without validation
    Document doc = reader.read(is);
    DocumentType docType = doc.getDocType();
    if (docType != null) {
        // replace DOCTYPE setting the full path to the xsd
        docType.setSystemID(dtdSchemaUrl);
    } else {/*from   w  w w  . j ava 2 s .com*/
        // add the DOCTYPE
        docType = new DefaultDocumentType(doc.getRootElement().getName(), dtdSchemaUrl);
        doc.setDocType(docType);
    }

    ByteArrayOutputStream fos = new ByteArrayOutputStream();
    try {
        OutputFormat format = OutputFormat.createPrettyPrint(); // uses UTF-8
        XMLWriter writer = new XMLWriter(fos, format);
        writer.write(doc);
        writer.flush();
    } finally {
        fos.close();
    }

    return new ByteArrayInputStream(fos.toByteArray());
}

From source file:org.codehaus.mojo.hibernate2.MappingsAggregatorMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    try {//  w  ww  . j av a2  s  . c  om
        String version = null;

        if (getBasedir() == null) {
            throw new MojoExecutionException("Required configuration missing: basedir");
        }

        File files[] = getIncludeFiles();
        if (files == null || files.length <= 0) {
            return;
        }
        File f = new File(getOutputFile());
        if (!f.exists()) {
            f.getParentFile().mkdirs();
            f.createNewFile();
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileWriter(f), format);
        writer.setEntityResolver(new HibernateEntityResolver());
        //writer.setResolveEntityRefs(false);
        Document finalDoc = DocumentHelper.createDocument();
        Element rootHM = null;
        for (int i = 0; i < files.length; i++) {
            print("Parsing: " + files[i].getAbsolutePath());
            SAXReader reader = new SAXReader(false);
            reader.setEntityResolver(new HibernateEntityResolver());
            //reader.setIncludeExternalDTDDeclarations(false);
            //reader.setIncludeExternalDTDDeclarations(false);
            Document current = reader.read(files[i]);
            String currentVersion = getVersion(current);
            if (version == null) {
                version = currentVersion;
                finalDoc.setProcessingInstructions(current.processingInstructions());
                finalDoc.setDocType(current.getDocType());
                rootHM = finalDoc.addElement("hibernate-mapping");
            } else if (!version.equals(currentVersion)) {
                //LOG.warn("Mapping in " + files[i].getName() + " is not of the same mapping version as " + files[0].getName() + " mapping, so merge is impossible. Skipping");
                continue;
            }
            for (Iterator iter = current.selectSingleNode("hibernate-mapping").selectNodes("class")
                    .iterator(); iter.hasNext(); rootHM.add((Element) ((Element) iter.next()).clone())) {
            }
        }

        print("Writing aggregate file: " + f.getAbsolutePath());
        writer.write(finalDoc);
        writer.close();
    } catch (Exception ex) {
        throw new MojoExecutionException("Error in executing MappingsAgrregatorBean", ex);
    }
}

From source file:org.olat.ims.qti.editor.beecom.objects.QTIDocument.java

License:Apache License

/**
 * Get the structure as an XML Document.
 * /*from   w w  w  .j a va 2 s.  com*/
 * @return XML Document.
 */
public Document getDocument() {
    final Document tmp = DocumentHelper.createDocument();
    final DocumentType type = new DOMDocumentType();
    type.setElementName(DOCUMENT_ROOT);
    type.setSystemID(DOCUMENT_DTD);

    tmp.setDocType(type);
    final Element questestinterop = tmp.addElement(DOCUMENT_ROOT);
    this.assessment.addToElement(questestinterop);
    return tmp;
}

From source file:org.opencms.configuration.CmsConfigurationManager.java

License:Open Source License

/**
 * Creates the XML document build from the provided configuration.<p>
 * //from   w  w w. jav a 2 s  .com
 * @param configuration the configuration to build the XML for
 * @return the XML document build from the provided configuration
 */
public Document generateXml(I_CmsXmlConfiguration configuration) {

    // create a new document
    Document result = DocumentHelper.createDocument();

    // set the document type        
    DOMDocumentType docType = new DOMDocumentType();
    docType.setElementName(N_ROOT);
    docType.setSystemID(configuration.getDtdUrlPrefix() + configuration.getDtdFilename());
    result.setDocType(docType);

    Element root = result.addElement(N_ROOT);
    // start the XML generation
    configuration.generateXml(root);

    // return the resulting document
    return result;
}

From source file:org.unitime.banner.ant.MergeXml.java

License:Apache License

public void execute() throws BuildException {
    try {/*from   w w  w . j  a va2s.co m*/
        log("Merging " + iTarget + " with " + iSource);
        SAXReader sax = new SAXReader();
        sax.setEntityResolver(new EntityResolver() {
            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                    return new InputSource(getClass().getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
                } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                    return new InputSource(getClass().getClassLoader()
                            .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
                }
                return null;
            }
        });
        sax.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        Document targetDoc = sax.read(new File(iTarget));
        Document sourceDoc = sax.read(new File(iSource));

        merge(targetDoc.getRootElement(), sourceDoc.getRootElement());

        if (new File(iTarget).getName().equals("hibernate.cfg.xml")) {
            targetDoc.setDocType(sourceDoc.getDocType()); // Remove DOCTYPE
            Element sessionFactoryElement = targetDoc.getRootElement().element("session-factory");
            Vector<Element> mappings = new Vector<Element>();
            for (Iterator i = sessionFactoryElement.elementIterator("mapping"); i.hasNext();) {
                Element mappingElement = (Element) i.next();
                mappings.add(mappingElement);
                sessionFactoryElement.remove(mappingElement);
            }
            for (Iterator i = mappings.iterator(); i.hasNext();) {
                Element mappingElement = (Element) i.next();
                sessionFactoryElement.add(mappingElement);
            }
        }

        FileOutputStream fos = new FileOutputStream(iTarget);
        (new XMLWriter(fos, OutputFormat.createPrettyPrint())).write(targetDoc);
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new BuildException(e);
    }
}

From source file:packet_readers.lineage2.listeners.L2JumpListener.java

License:Open Source License

@Override
public void closeImpl() throws IOException {
    if (_jumpTracks.isEmpty())
        return;/*  www. ja  va 2  s .c o m*/

    Document document = DocumentHelper.createDocument();
    document.setDocType(new DefaultDocumentType("list", "jump_nodes.dtd"));
    Element listElement = document.addElement("list");

    for (JumpTrack track : _jumpTracks) {
        Element element = listElement.addElement("jump_track");
        element.addAttribute("id", String.valueOf(track.getId()));
        element.addAttribute("type", track.getChooseType().name());

        write(element, track);
    }

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setIndent("\t");
    XMLWriter writer = new XMLWriter(new FileWriter(getLogFile("jump_tracks ", "xml")), format);
    writer.write(document);
    writer.close();
}