Example usage for org.dom4j Document getDocType

List of usage examples for org.dom4j Document getDocType

Introduction

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

Prototype

DocumentType getDocType();

Source Link

Document

DOCUMENT ME!

Usage

From source file:architecture.common.xml.XmlWriter.java

License:Apache License

/**
 * <p>/* ww  w.  j a  v  a  2s.co m*/
 * This will print the <code>Document</code> to the current Writer.
 * </p>
 *
 * <p>
 * Warning: using your own Writer may cause the writer's preferred character
 * encoding to be ignored. If you use encodings other than UTF8, we
 * recommend using the method that takes an OutputStream instead.
 * </p>
 *
 * <p>
 * Note: as with all Writers, you may need to flush() yours after this
 * method returns.
 * </p>
 *
 * @param doc
 *            <code>Document</code> to format.
 * @throws IOException
 *             - if there's any problem writing.
 **/
public void write(Document doc) throws IOException {
    writeDeclaration();

    if (doc.getDocType() != null) {
        indent();
        writeDocType(doc.getDocType());
    }

    for (int i = 0, size = doc.nodeCount(); i < size; i++) {
        Node node = doc.node(i);
        writeNode(node);
    }
    writePrintln();

    if (autoFlush) {
        flush();
    }
}

From source file:com.alibaba.antx.config.resource.util.SvnIndexPageParser.java

License:Open Source License

public List parse(Resource resource) {
    Document doc;
    boolean xml = true;

    doc = getXmlDocument(resource);//from ww  w  .  j ava  2  s.  c  o m

    if (doc == null) {
        doc = getHtmlDocument(resource);
        xml = false;
    }

    List items = null;

    if (doc != null && xml) {
        DocumentType docType = doc.getDocType();

        if (docType != null && "svn".equalsIgnoreCase(docType.getName())) {
            items = new ArrayList();

            addNodes(items, doc.selectNodes("//dir/@name"), true);
            addNodes(items, doc.selectNodes("//file/@name"), false);
        }
    } else if (doc != null && !xml) {
        Node title = doc.selectSingleNode("//head/title");

        if (title != null && title.getText() != null && title.getText().indexOf("Revision") > 0) {
            List nodes = doc.selectNodes("//ul/li/a/@href");

            items = new ArrayList();

            for (Iterator i = nodes.iterator(); i.hasNext();) {
                Node node = (Node) i.next();
                String name = node.getText();

                try {
                    name = URLDecoder.decode(name, getCharset(resource));
                } catch (UnsupportedEncodingException e) {
                }

                Item item = getItem(name);

                if (item != null) {
                    items.add(item);
                }
            }
        }
    }

    return items;
}

From source file:com.blocks.framework.utils.date.XMLDom4jUtils.java

License:Open Source License

/**
 * dtd/*from w ww.  jav a 2s. c o m*/
 *
 * @param document
 *            
 * @param dtdPublicId
 *            dtd
 * @return boolean true,false
 */
public static boolean checkDocumentType(Document document, String dtdPublicId) {
    DocumentType documentType = document.getDocType();
    if (documentType != null) {
        String publicId = documentType.getPublicID();
        return publicId != null && publicId.equals(dtdPublicId);
    }
    return true;
}

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 {// w ww.  ja va  2 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:com.tedi.engine.XMLOutput.java

License:Open Source License

/**
 * Handles functionality of formatting and writing document.
 * /*  www.  j a v a 2s  . c o m*/
 * @param doc
 *            The document
 * @return the cleaned document.
 * @throws Exception
 */
private String cleanDocument(Document doc) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Cleaning the document object.");
    }
    String docStr = "";
    // --COMMENTED OUT 10-10-2005
    // JBG----------------------------------------------------------------------------------
    // if (dtd != null && dtd.length()>0) {
    // xmlUtils.setDocument(doc);
    // try {
    // AbstractSchemaDescriptor schema =
    // AbstractSchemaDescriptor.createDescriptor(absoluteDTD_URL.toString());
    // schema.processSchema(doc.getRootElement().getName());
    // xmlUtils.setSchema(schema);
    // xmlUtils.cleanDocument();
    // }
    // catch (Exception e) {
    // execResults.addMessage(ExecutionResults.M_WARNING,
    // ExecutionResults.J2EE_TARGET_ERR,
    // "Error removing optional attributes/elements: " + e.getMessage());
    // }
    // }
    // ----------------------------------------------------------------------------------------------------------------
    cleanElement(doc.getRootElement());
    StringWriter sw = new StringWriter();
    OutputFormat format = isCompact ? OutputFormat.createCompactFormat() : OutputFormat.createPrettyPrint();
    format.setExpandEmptyElements(false);
    XMLWriter writer = new XMLWriter(sw, format);
    writer.setMaximumAllowedCharacter(127);
    writer.write(doc);
    writer.close();
    docStr = sw.toString();
    if (isSuppressDocType && doc.getDocType() != null) {
        int ndx = docStr.indexOf("<" + doc.getRootElement().getName());
        docStr = docStr.substring(ndx);
    }
    return docStr;
}

From source file:com.xpn.xwiki.internal.xml.XMLWriter.java

License:Open Source License

/**
 * Write the <code>{@link Document}</code> declaration, and its <code>{@link DocumentType}</code> if available to
 * the output stream./*from  w w w  .  j  a  va 2  s.c o m*/
 * 
 * @param doc <code>{@link Document}</code> to be started, may specify a <code>{@link DocumentType}</code>.
 * @throws IOException a problem occurs during writing
 */
public void writeDocumentStart(Document doc) throws IOException {
    writeDeclaration();

    if (doc.getDocType() != null) {
        indent();
        writeDocType(doc.getDocType());
    }
}

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  ww w . j  a v a  2 s.co m
        // 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 w w .  j a v  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.codehaus.mojo.hibernate2.MappingsAggregatorMojo.java

License:Apache License

private String getVersion(Document current) {
    String docType = current.getDocType().getText();
    if (docType == null || "".equals(docType.trim())) {
        return "";
    }//from  w w  w.  j a va 2 s  .c om
    if (docType.indexOf("hibernate-mapping-2.0.dtd") > 0) {
        return "2.0";
    }
    if (docType.indexOf("hibernate-mapping-1.1.dtd") > 0) {
        return "1.1";
    } else {
        return null;
    }
}

From source file:org.dom4j.samples.validate.SAXValidatorDemo.java

License:Open Source License

protected void validate(String url, boolean validateOnParse) throws Exception {
    println("Parsing: " + url + " with validation mode: " + validateOnParse);

    XMLErrorHandler errorHandler = new XMLErrorHandler();

    if (validateOnParse) {
        // validate as we parse
        SAXReader reader = new SAXReader(true);
        reader.setErrorHandler(errorHandler);

        try {//w  w w  . j a  v a 2 s . c  o m
            Document document = reader.read(url);
            println("Document: " + url + " is valid!");
        } catch (DocumentException e) {
            println("Document: " + url + " is not valid");
            println("Exception: " + e);
        }
    } else {
        // parse without validating, then do that later
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);

        println("Document URI: " + document.getName());

        // now lets set a doc type if one isn't set
        DocumentType docType = document.getDocType();
        if (docType == null) {
            println("Adding an NITF doc type");
            document.addDocType("nitf", null, "nitf.dtd");
        }

        // now lets validate
        try {
            SAXValidator validator = new SAXValidator();
            validator.setErrorHandler(errorHandler);
            validator.validate(document);

            println("Document: " + url + " is valid!");
        } catch (SAXException e) {
            println("Document: " + url + " is not valid");
            println("Exception: " + e);
        }
    }

    // now lets output any errors as XML
    Element errors = errorHandler.getErrors();
    if (errors.hasContent()) {
        XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
        writer.write(errors);
    }
}