Example usage for org.w3c.dom DOMImplementation createDocumentType

List of usage examples for org.w3c.dom DOMImplementation createDocumentType

Introduction

In this page you can find the example usage for org.w3c.dom DOMImplementation createDocumentType.

Prototype

public DocumentType createDocumentType(String qualifiedName, String publicId, String systemId)
        throws DOMException;

Source Link

Document

Creates an empty DocumentType node.

Usage

From source file:Main.java

/** 
 * Creates empty DOM Document using JAXP factoring. E.g.:
 * <p><pre>//from  ww w  .  j a va  2s.  c  om
 * Document doc = createDocument("book", null, null, null);
 * </pre><p>
 * creates new DOM of a well-formed document with root element named book.
 *
 * @param rootQName qualified name of root element. e.g. <code>myroot</code> or <code>ns:myroot</code>
 * @param namespaceURI URI of root element namespace or <code>null</code>
 * @param doctypePublicID public ID of DOCTYPE or <code>null</code>
 * @param doctypeSystemID system ID of DOCTYPE or <code>null</code> if no DOCTYPE 
 *        required and doctypePublicID is also <code>null</code>
 *
 * @throws DOMException if new DOM with passed parameters can not be created
 * @throws FactoryConfigurationError Application developers should never need to directly catch errors of this type.     
 *
 * @return new DOM Document
 */
public static Document createDocument(String rootQName, String namespaceURI, String doctypePublicID,
        String doctypeSystemID) throws DOMException {

    DOMImplementation impl = getDOMImplementation();

    if (doctypePublicID != null && doctypeSystemID == null) {
        throw new IllegalArgumentException("System ID cannot be null if public ID specified. "); //NOI18N
    }

    DocumentType dtd = null;
    if (doctypeSystemID != null) {
        dtd = impl.createDocumentType(rootQName, doctypePublicID, doctypeSystemID);
    }

    return impl.createDocument(namespaceURI, rootQName, dtd);
}

From source file:DomUtil.java

/**
 * Creates a new document.//from   ww  w .  ja va 2  s.  co  m
 * 
 * @param qualifiedName the qualified name of the document type to be 
 *        created
 * @param publicId the external subset public identifier
 * @param systemId the external subset system identifier
 * @param namespaceUri the namespace URI of the document element to create
 */
public static Document createDocument(String qualifiedName, String publicId, String systemId,
        String namespaceUri) {
    DOMImplementation dom = DomUtil.getDocumentBuilder().getDOMImplementation();
    DocumentType docType = dom.createDocumentType(qualifiedName, publicId, systemId);
    Document document = dom.createDocument(namespaceUri, qualifiedName, docType);
    if (namespaceUri != null) {
        document.getDocumentElement().setAttribute("xmlns", namespaceUri);
    }
    return document;
}

From source file:Main.java

/**
 * Creates an empty DOM document. E.g.://w  w  w .ja v a 2  s  . com
 * <pre>
 * Document doc = createDocument("book", null, null, null);
 * </pre> creates new DOM of a well-formed document with root element named
 * book.
 *
 * @param rootQName       qualified name of root element, for example
 *                        <code>myroot</code> or <code>ns:myroot</code>
 * @param namespaceURI    URI of root element namespace or <code>null</code>
 * @param doctypePublicID public ID of DOCTYPE or <code>null</code>
 * @param doctypeSystemID system ID of DOCTYPE or <code>null</code> if no
 *                        DOCTYPE required and doctypePublicID is also
 *                        <code>null</code>
 *
 * @throws DOMException              if new DOM with passed parameters can
 *                                   not be created
 * @throws FactoryConfigurationError Application developers should never
 *                                   need to directly catch errors of this
 *                                   type.
 *
 * @return new DOM Document
 */
public static Document createDocument(String rootQName, String namespaceURI, String doctypePublicID,
        String doctypeSystemID) throws DOMException {
    DOMImplementation impl = getDOMImplementation();

    if ((doctypePublicID != null) && (doctypeSystemID == null)) {
        throw new IllegalArgumentException("System ID cannot be null if public ID specified. "); //NOI18N
    }

    DocumentType dtd = null;

    if (doctypeSystemID != null) {
        dtd = impl.createDocumentType(rootQName, doctypePublicID, doctypeSystemID);
    }

    return impl.createDocument(namespaceURI, rootQName, dtd);
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.WMSRequestHandler.java

private Document createKBDescribeLayerResponse(DataWrapper dw, List<DescribeLayerData> describeLayerData)
        throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);/*from  w w  w  .  j  a v a  2s  .c  om*/
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    DOMImplementation di = db.getDOMImplementation();

    // <!DOCTYPE WMS_DescribeLayerResponse SYSTEM "http://schemas.opengis.net/wms/1.1.1/WMS_DescribeLayerResponse.dtd">
    // [ <WMS_DescribeLayerResponse version="1.1.1" > (...) </WMS_DescribeLayerResponse>]        
    DocumentType dt = di.createDocumentType("WMS_DescribeLayerResponse", null,
            CallWMSServlet.DESCRIBELAYER_DTD);
    Document dom = di.createDocument(null, "WMS_DescribeLayerResponse", dt);
    Element rootElement = dom.getDocumentElement();
    rootElement.setAttribute("version", "1.1.1"); //describeLayer version in kbconfig?

    String spAbbrUrl = dw.getOgcrequest().getServiceProviderName();

    String personalUrl = this.user.getPersonalURL(dw.getRequest(), spAbbrUrl);

    Integer[] orgIds = this.user.getOrganizationIds();

    WFSProviderDAO wfsProviderDao = new WFSProviderDAO();
    String[] validLayerNames = wfsProviderDao.getAuthorizedFeatureTypeNames(orgIds, null, false);
    //it is not possible to use getSeviceProviderURLS because that will call getValidObjects implementation of WMSRequestHandler
    //therefore build spInfo here in loop
    //also, B3PLayering is not relevant here, because describeLayer should not be subject to pricing
    List spInfo = new ArrayList();
    for (String name : validLayerNames) {
        SpLayerSummary layerInfo = wfsProviderDao.getAuthorizedFeatureTypeSummary(name, orgIds, false);
        if (layerInfo == null) {
            continue;
        }
        spInfo.add(layerInfo);
    }

    for (DescribeLayerData resp : describeLayerData) {
        for (LayerDescription descr : resp.getDescribeLayerResponse().getLayerDescs()) {
            Element layerDescriptionElement = dom.createElement("LayerDescription");
            if (spAbbrUrl != null && !spAbbrUrl.equals("")) {
                layerDescriptionElement.setAttribute("name", descr.getName());
            } else {
                layerDescriptionElement.setAttribute("name",
                        OGCCommunication.attachSp(resp.getWmsPrefix(), descr.getName()));
            }
            descr.getOwsURL();

            //additional info should only be returned for WMS layer that has corresponding WFS type that is served by Kaartenbalie
            String wfsPrefix = getAuthorizedWFSPrefix(spInfo, descr);
            if (wfsPrefix != null) {
                layerDescriptionElement.setAttribute("wfs", personalUrl);
                layerDescriptionElement.setAttribute("owsType", descr.getOwsType());
                layerDescriptionElement.setAttribute("owsURL", personalUrl);

                Element queryElement = dom.createElement("Query");
                queryElement.setAttribute("typeName", OGCCommunication.attachSp(wfsPrefix, descr.getName()));
                layerDescriptionElement.appendChild(queryElement);
            }
            rootElement.appendChild(layerDescriptionElement);
        }
    }
    return dom;
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.GetCapabilitiesRequestHandler.java

/**
 * Processes the parameters and creates a DocumentBuilder from the given
 * parameters. This DocumentBuilder will be used to create a XML based
 * String which can be returned to the client.
 *
 * @param dw DataWrapper which contains all information that has to be sent
 * to the client//from  w w w . ja  v a  2 s. c o m
 * @param user User the user which invoked the request
 *
 * @return byte[]
 *
 * @throws Exception
 * @throws IOException
 */
// <editor-fold defaultstate="" desc="getRequest(DataWrapper dw, User user) method.">
public void getRequest(DataWrapper dw, User user) throws IOException, Exception {
    dw.setHeader("Content-Disposition", "inline; filename=\"GetCapabilities.xml\";");
    dw.setContentType(OGCConstants.WMS_PARAM_WMS_XML);

    String spAbbrUrl = dw.getOgcrequest().getServiceProviderName();
    ByteArrayOutputStream output = null;

    if (user != null) {
        this.user = user;
        this.url = user.getPersonalURL(dw.getRequest(), spAbbrUrl);
    }

    if (url == null) {
        throw new Exception("No personal url for user found.");
    }

    /*
     * Only used if specific param is given (used for configuration)
     */
    boolean isAdmin = false;
    if ("true".equalsIgnoreCase(dw.getOgcrequest().getParameter("_VIEWER_CONFIG"))) {
        Set userRoles = user.getRoles();
        Iterator rolIt = userRoles.iterator();
        while (rolIt.hasNext()) {
            Roles role = (Roles) rolIt.next();
            if (role.getRole().equalsIgnoreCase(Roles.ADMIN)) {
                /* de gebruiker is een beheerder */
                isAdmin = true;
                break;
            }
        }
    }

    /*
     * Only used if specific param is given (used for monitoring)
     */
    if ("true".equalsIgnoreCase(dw.getOgcrequest().getParameter("_FORCE_FETCH"))) {
        forceFetch(dw, isAdmin);
    }

    ServiceProvider s = getServiceProvider(isAdmin, spAbbrUrl);

    if (user != null) {
        s.setOrganizationCode(user.getOrganisationCodes());
        s.setExpireDate(user.getTimeout());
        s.setUserName(user.getName());
        s.setGivenName(user.getFirstName() + " " + user.getSurname());
        s.setPersonalCode(user.getPersonalURL());
    }
    HashMap conversionValues = new HashMap();
    conversionValues.put("url", url);
    s.convertValues2KB(conversionValues);

    /*
     * Create a DocumentBuilderFactory from which a new document can be created
     */
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    DOMImplementation di = db.getDOMImplementation();

    // <!DOCTYPE WMT_MS_Capabilities SYSTEM "http://schemas.opengeospatial.net/wms/1.1.1/WMS_MS_Capabilities.dtd"
    // [
    // <!ELEMENT VendorSpecificCapabilities EMPTY>
    // ]>  <!-- end of DOCTYPE declaration -->
    DocumentType dt = di.createDocumentType("WMT_MS_Capabilities", null, CallWMSServlet.CAPABILITIES_DTD);
    Document dom = di.createDocument(null, "WMT_MS_Capabilities", dt);
    Element rootElement = dom.getDocumentElement();
    rootElement = s.toElement(dom, rootElement);
    rootElement.setAttribute("version", "1.1.1");

    /*
     * Create a new output format to which this document should be translated and
     * serialize the tree to an XML document type
     */
    OutputFormat format = new OutputFormat(dom, KBConfiguration.CHARSET, true);
    format.setIndenting(true);
    output = new ByteArrayOutputStream();
    XMLSerializer serializer = new XMLSerializer(output, format);
    serializer.serialize(dom);

    DOMValidator dv = new DOMValidator();
    dv.parseAndValidate(new ByteArrayInputStream(output.toString().getBytes(KBConfiguration.CHARSET)));

    dw.write(output);
}

From source file:nl.b3p.kaartenbalie.service.servlet.CallWMSServlet.java

private void handleRequestExceptionAsXML(Exception ex, DataWrapper data) throws IOException {
    ByteArrayOutputStream output = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);// w  ww . ja va2 s  .  c o  m
    dbf.setNamespaceAware(true);
    DocumentBuilder db = null;
    try {
        db = dbf.newDocumentBuilder();
    } catch (Exception e) {
        log.error("error: ", e);
        throw new IOException("Exception occured during creation of error message: " + e);
    }

    DOMImplementation di = db.getDOMImplementation();

    // <!DOCTYPE ServiceExceptionReport SYSTEM "http://schemas.opengeospatial.net/wms/1.1.1/exception_1_1_1.dtd"
    // <!-- end of DOCTYPE declaration -->
    DocumentType dt = di.createDocumentType("ServiceExceptionReport", null, CallWMSServlet.EXCEPTION_DTD);
    Document dom = di.createDocument(null, "ServiceExceptionReport", dt);
    Element rootElement = dom.getDocumentElement();
    rootElement.setAttribute("version", "1.1.1");

    Element serviceExceptionElement = dom.createElement("ServiceException");

    String exceptionName = ex.getClass().getName();
    String message = ex.getMessage();
    Throwable cause = ex.getCause();

    serviceExceptionElement.setAttribute("code", exceptionName);
    CDATASection cdata = null;
    if (cause != null) {
        cdata = dom.createCDATASection(message + " - " + cause);
    } else {
        cdata = dom.createCDATASection(message);
    }

    serviceExceptionElement.appendChild(cdata);
    rootElement.appendChild(serviceExceptionElement);

    OutputFormat format = new OutputFormat(dom);
    format.setIndenting(true);
    output = new ByteArrayOutputStream();
    XMLSerializer serializer = new XMLSerializer(output, format);
    serializer.serialize(dom);

    DOMValidator dv = new DOMValidator();
    try {
        dv.parseAndValidate(new ByteArrayInputStream(output.toString().getBytes(KBConfiguration.CHARSET)));
    } catch (Exception e) {
        log.error("error: ", e);
        throw new IOException("Exception occured during validation of error message: " + e);
    }

    data.setHeader("Content-Disposition", "inline; filename=\"ServiceException.xml\";");
    data.write(output);
}

From source file:org.htmlcleaner.XWikiDOMSerializer.java

/**
 * @param documentDocumentBuilder the {@link DocumentBuilder} instance to use, DocumentBuilder is not garantied to
 * be thread safe so at most the safe instance should be used only in the same thread
 * @param rootNode the HTML Cleaner root node to serialize
 * @return the W3C Document object//  ww  w .ja  va2  s.c  o  m
 * @throws ParserConfigurationException if there's an error during serialization
 */
public Document createDOM(DocumentBuilder documentDocumentBuilder, TagNode rootNode)
        throws ParserConfigurationException {
    DOMImplementation impl = documentDocumentBuilder.getDOMImplementation();

    // Copied from the source code of HTML Cleaner.

    Document document;

    //
    // Where a DOCTYPE is supplied in the input, ensure that this is in the output DOM. See issue #27
    //
    // Note that we may want to fix incorrect DOCTYPEs in future; there are some fairly
    // common patterns for errors with the older HTML4 doctypes.
    //
    if (rootNode.getDocType() != null) {
        String qualifiedName = rootNode.getDocType().getPart1();
        String publicId = rootNode.getDocType().getPublicId();
        String systemId = rootNode.getDocType().getSystemId();

        //
        // If there is no qualified name, set it to html. See bug #153.
        //
        if (qualifiedName == null) {
            qualifiedName = HTML_TAG_NAME;
        }

        DocumentType documentType = impl.createDocumentType(qualifiedName, publicId, systemId);

        //
        // While the qualified name is "HTML" for some DocTypes, we want the actual document root name to be "html".
        // See bug #116
        //
        if (qualifiedName.equals("HTML")) {
            qualifiedName = HTML_TAG_NAME;
        }
        document = impl.createDocument(rootNode.getNamespaceURIOnPath(""), qualifiedName, documentType);
    } else {
        document = documentDocumentBuilder.newDocument();
        Element rootElement = document.createElement(rootNode.getName());
        document.appendChild(rootElement);
    }

    //
    // Copy across root node attributes - see issue 127. Thanks to rasifiel for the patch
    //
    Map<String, String> attributes = rootNode.getAttributes();
    Iterator<Map.Entry<String, String>> entryIterator = attributes.entrySet().iterator();
    while (entryIterator.hasNext()) {
        Map.Entry<String, String> entry = entryIterator.next();
        String attrName = entry.getKey();
        String attrValue = entry.getValue();
        if (escapeXml) {
            attrValue = Utils.escapeXml(attrValue, props, true);
        }

        document.getDocumentElement().setAttribute(attrName, attrValue);

        //
        // Flag the attribute as an ID attribute if appropriate. Thanks to Chris173
        //
        if (attrName.equalsIgnoreCase("id")) {
            document.getDocumentElement().setIdAttribute(attrName, true);
        }
    }

    createSubnodes(document, document.getDocumentElement(), rootNode.getAllChildren());

    return document;
}