Example usage for org.w3c.dom Document lookupPrefix

List of usage examples for org.w3c.dom Document lookupPrefix

Introduction

In this page you can find the example usage for org.w3c.dom Document lookupPrefix.

Prototype

public String lookupPrefix(String namespaceURI);

Source Link

Document

Look up the prefix associated to the given namespace URI, starting from this node.

Usage

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

/**
 * Generate the XForm based on a user supplied XML Schema.
 *
 * @param instanceDocument The document source for the XML Schema.
 * @param schemaDocument Schema document
 * @param rootElementName Name of the root element
 * @param resourceBundle Strings to use/* w  w  w .j ava2 s. co  m*/
 * @return The Document containing the XForm.
 * @throws org.chiba.tools.schemabuilder.FormBuilderException
 *          If an error occurs building the XForm.
 */
public Pair<Document, XSModel> buildXForm(final Document instanceDocument, final Document schemaDocument,
        String rootElementName, final ResourceBundle resourceBundle) throws FormBuilderException {
    final XSModel schema = SchemaUtil.parseSchema(schemaDocument, true);
    this.typeTree = SchemaUtil.buildTypeTree(schema);

    //refCounter = 0;
    this.counter.clear();

    final Document xformsDocument = this.createFormTemplate(rootElementName);

    //find form element: last element created
    final Element formSection = (Element) xformsDocument.getDocumentElement().getLastChild();
    final Element modelSection = (Element) xformsDocument.getDocumentElement()
            .getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "model").item(0);

    //add XMLSchema if we use schema types      
    final Element importedSchemaDocumentElement = (Element) xformsDocument
            .importNode(schemaDocument.getDocumentElement(), true);
    importedSchemaDocumentElement.setAttributeNS(null, "id", "schema-1");

    NodeList nl = importedSchemaDocumentElement.getChildNodes();
    boolean hasExternalSchema = false;

    for (int i = 0; i < nl.getLength(); i++) {
        Node current = nl.item(i);
        if (current.getNamespaceURI() != null
                && current.getNamespaceURI().equals(NamespaceConstants.XMLSCHEMA_NS)) {
            String localName = current.getLocalName();
            if (localName.equals("include") || localName.equals("import")) {
                hasExternalSchema = true;
                break;
            }
        }
    }

    // ALF-8105 / ETWOTWO-1384: Only embed the schema if it does not reference externals
    if (!hasExternalSchema) {
        modelSection.appendChild(importedSchemaDocumentElement);
    }

    //check if target namespace
    final StringList schemaNamespaces = schema.getNamespaces();
    final HashMap<String, String> schemaNamespacesMap = new HashMap<String, String>();
    if (schemaNamespaces.getLength() != 0) {
        // will return null if no target namespace was specified
        this.targetNamespace = schemaNamespaces.item(0);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("[buildXForm] using targetNamespace " + this.targetNamespace);

        for (int i = 0; i < schemaNamespaces.getLength(); i++) {
            if (schemaNamespaces.item(i) == null) {
                continue;
            }
            final String prefix = addNamespace(xformsDocument.getDocumentElement(),
                    schemaDocument.lookupPrefix(schemaNamespaces.item(i)), schemaNamespaces.item(i));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[buildXForm] adding namespace " + schemaNamespaces.item(i) + " with prefix "
                        + prefix + " to xform and default instance element");
            }
            schemaNamespacesMap.put(prefix, schemaNamespaces.item(i));
        }
    }

    //if target namespace & we use the schema types: add it to form ns declarations
    //   if (this.targetNamespace != null && this.targetNamespace.length() != 0)
    //       envelopeElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
    //                  "xmlns:schema",
    //                  this.targetNamespace);

    final XSElementDeclaration rootElementDecl = schema.getElementDeclaration(rootElementName,
            this.targetNamespace);
    if (rootElementDecl == null) {
        throw new FormBuilderException("Invalid root element tag name [" + rootElementName
                + ", targetNamespace = " + this.targetNamespace + "]");
    }

    rootElementName = this.getElementName(rootElementDecl, xformsDocument);
    final Element instanceElement = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
            NamespaceConstants.XFORMS_PREFIX + ":instance");
    modelSection.appendChild(instanceElement);
    this.setXFormsId(instanceElement);

    final Element defaultInstanceDocumentElement = xformsDocument.createElement(rootElementName);
    addNamespace(defaultInstanceDocumentElement, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
    if (this.targetNamespace != null) {
        final String targetNamespacePrefix = schemaDocument.lookupPrefix(this.targetNamespace);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[buildXForm] adding target namespace " + this.targetNamespace + " with prefix "
                    + targetNamespacePrefix + " to xform and default instance element");
        }

        addNamespace(defaultInstanceDocumentElement, targetNamespacePrefix, this.targetNamespace);
        addNamespace(xformsDocument.getDocumentElement(), targetNamespacePrefix, this.targetNamespace);
    }

    Element prototypeInstanceElement = null;
    if (instanceDocument == null || instanceDocument.getDocumentElement() == null) {
        instanceElement.appendChild(defaultInstanceDocumentElement);
    } else {
        Element instanceDocumentElement = instanceDocument.getDocumentElement();
        if (!instanceDocumentElement.getNodeName().equals(rootElementName)) {
            throw new IllegalArgumentException("instance document root tag name invalid.  " + "expected "
                    + rootElementName + ", got " + instanceDocumentElement.getNodeName());
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("[buildXForm] importing rootElement from other document");

        prototypeInstanceElement = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
                NamespaceConstants.XFORMS_PREFIX + ":instance");
        modelSection.appendChild(prototypeInstanceElement);
        this.setXFormsId(prototypeInstanceElement, "instance_prototype");
        prototypeInstanceElement.appendChild(defaultInstanceDocumentElement);
    }

    final Element rootGroup = this.addElement(xformsDocument, modelSection, defaultInstanceDocumentElement,
            formSection, schema, rootElementDecl, "/" + this.getElementName(rootElementDecl, xformsDocument),
            new SchemaUtil.Occurrence(1, 1), resourceBundle);
    if (rootGroup.getNodeName() != NamespaceConstants.XFORMS_PREFIX + ":group") {
        throw new FormBuilderException("Expected root form element to be a " + NamespaceConstants.XFORMS_PREFIX
                + ":group, not a " + rootGroup.getNodeName() + ".  Ensure that "
                + this.getElementName(rootElementDecl, xformsDocument)
                + " is a concrete type that has no extensions.  "
                + "Types with extensions are not supported for " + "the root element of a form.");
    }
    this.setXFormsId(rootGroup, "alfresco-xforms-root-group");

    if (prototypeInstanceElement != null) {
        Schema2XForms.rebuildInstance(prototypeInstanceElement, instanceDocument, instanceElement,
                schemaNamespacesMap);
    }

    this.createSubmitElements(xformsDocument, modelSection, rootGroup);
    this.createTriggersForRepeats(xformsDocument, rootGroup);

    final Comment comment = xformsDocument.createComment(
            "This XForm was generated by " + this.getClass().getName() + " on " + (new Date()) + " from the '"
                    + rootElementName + "' element of the '" + this.targetNamespace + "' XML Schema.");
    xformsDocument.getDocumentElement().insertBefore(comment,
            xformsDocument.getDocumentElement().getFirstChild());
    xformsDocument.normalizeDocument();

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("[buildXForm] Returning XForm =\n" + XMLUtil.toString(xformsDocument));

    return new Pair<Document, XSModel>(xformsDocument, schema);
}

From source file:org.deegree.portal.owswatch.validator.CSWGetRecordsValidator.java

@Override
protected ValidatorResponse validateXmlServiceException(HttpMethodBase method) {

    Document doc = null;
    String lastMessage = null;/*from www  .  j  a v  a 2 s  .co m*/
    Status status = null;

    try {
        InputStream stream = method.getResponseBodyAsStream();
        stream.reset();
        doc = instantiateParser().parse(stream);
    } catch (Exception e) {
        status = Status.RESULT_STATE_INVALID_XML;
        lastMessage = "Error: MalFormed XML Response";
        return new ValidatorResponse(lastMessage, status);
    }
    try {
        NamespaceContext cnxt = CommonNamespaces.getNamespaceContext();
        URI owsns = CommonNamespaces.OWSNS;
        String prefix = doc.lookupPrefix(owsns.toASCIIString());
        StringBuilder builder = new StringBuilder(100);
        builder.append("./");
        if (prefix != null && prefix.length() > 0) {
            builder.append(prefix).append(":");
            cnxt.addNamespace(prefix, owsns);
        }

        builder.append("Exception");
        status = Status.RESULT_STATE_SERVICE_UNAVAILABLE;
        lastMessage = XMLTools.getNodeAsString(doc.getDocumentElement(), builder.toString(), cnxt,
                "Service Unavailable. Unknown error");
        return new ValidatorResponse(lastMessage, status);
    } catch (XMLParsingException e) {
        lastMessage = "Service Unavailable";
        status = Status.RESULT_STATE_SERVICE_UNAVAILABLE;
        return new ValidatorResponse(lastMessage, status);
    }
}

From source file:org.kuali.rice.ken.xpath.XPathTest.java

@Test
public void testXPathWithValidatedDOMDocNamespace() throws Exception {
    LOG.debug("TEST");
    Document doc = getDocument(true, true);
    LOG.info("Default namespace: " + doc.lookupNamespaceURI(null));
    LOG.info("default prefix: " + doc.lookupPrefix(doc.lookupNamespaceURI(null)));
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(Util.getNotificationNamespaceContext(doc));
    String channelName = (String) xpath.evaluate("/nreq:notification/nreq:channel", doc.getDocumentElement(),
            XPathConstants.STRING);
    assertEquals("Test Channel #1", channelName);
}