Example usage for org.dom4j QName getNamespaceURI

List of usage examples for org.dom4j QName getNamespaceURI

Introduction

In this page you can find the example usage for org.dom4j QName getNamespaceURI.

Prototype

public String getNamespaceURI() 

Source Link

Document

DOCUMENT ME!

Usage

From source file:org.orbeon.oxf.xforms.action.actions.XFormsMessageAction.java

License:Open Source License

public void execute(XFormsActionInterpreter actionInterpreter, Element actionElement, Scope actionScope,
        boolean hasOverriddenContext, Item overriddenContext) {

    final XFormsContainingDocument containingDocument = actionInterpreter.containingDocument();

    {/*from  www. ja  v  a  2s. c  o m*/
        final String levelAttribute;
        final QName levelQName;
        {
            final String tempLevelAttribute = actionElement.attributeValue(XFormsConstants.LEVEL_QNAME);
            if (tempLevelAttribute == null) {
                // "The default is "modal" if the attribute is not specified."
                levelQName = XFormsConstants.XFORMS_MODAL_LEVEL_QNAME;
                levelAttribute = levelQName.getName();
            } else {
                levelAttribute = tempLevelAttribute;
                levelQName = Dom4jUtils.extractAttributeValueQName(actionElement, XFormsConstants.LEVEL_QNAME);
            }
        }

        // Get message value
        final String messageValue;
        {
            final String elementValue = XFormsUtils.getElementValue(actionInterpreter.container(),
                    actionInterpreter.actionXPathContext(),
                    actionInterpreter.getSourceEffectiveId(actionElement), actionElement, false, false, null);

            // If we got a null consider the message to be an empty string
            messageValue = elementValue != null ? elementValue : "";
        }

        if (LOG_APPEARANCES.get(levelQName) != null) {
            // Special log appearance

            final IndentedLogger indentedLogger = containingDocument.indentedLogger();
            if (XFormsConstants.XXFORMS_LOG_DEBUG_LEVEL_QNAME.equals(levelQName)) {
                indentedLogger.logDebug("xf:message", messageValue);
            } else if (XFormsConstants.XXFORMS_LOG_INFO_DEBUG_LEVEL_QNAME.equals(levelQName)) {
                indentedLogger.logInfo("xf:message", messageValue);
            } else if (XFormsConstants.XXFORMS_LOG_WARN_DEBUG_LEVEL_QNAME.equals(levelQName)) {
                indentedLogger.logWarning("xf:message", messageValue);
            } else if (XFormsConstants.XXFORMS_LOG_ERROR_DEBUG_LEVEL_QNAME.equals(levelQName)) {
                indentedLogger.logError("xf:message", messageValue);
            }

        } else if (SUPPORTED_APPEARANCES.get(levelQName) != null) {
            // Any other supported appearance are sent to the client

            final String level;
            if (levelQName.getNamespacePrefix().equals("")) {
                level = levelAttribute;
            } else {
                level = "{" + levelQName.getNamespaceURI() + "}" + levelQName.getName();
            }

            // Store message for sending to client
            containingDocument.addMessageToRun(messageValue, level);

            // NOTE: In the future, we *may* want to save and resume the event state before and after
            // displaying a message, in order to possibly provide a behavior which is more consistent with what
            // users may expect regarding actions executed after xf:message.

        } else {
            // Unsupported appearance
            throw new OXFException(
                    "xf:message element's 'level' attribute must have value: 'ephemeral'|'modeless'|'modal'|'xxf:log-debug'|'xxf:log-info'|'xxf:log-warn'|'xxf:log-error'.");
        }
    }
}

From source file:org.orbeon.oxf.xforms.control.XFormsSingleNodeControl.java

License:Open Source License

/**
 * Convenience method to return the local name of a built-in XML Schema or XForms type.
 *
 * @return the local name of the built-in type, or null if not found
 *//*  ww w .  j  a  v a  2s .  c  om*/
public String getBuiltinTypeName() {
    final QName type = getType();

    if (type != null) {
        final boolean isBuiltInSchemaType = type.getNamespaceURI().equals(XMLConstants.XSD_URI);
        final boolean isBuiltInXFormsType = type.getNamespaceURI().equals(XFormsConstants.XFORMS_NAMESPACE_URI);

        if (isBuiltInSchemaType || isBuiltInXFormsType) {
            return type.getName();
        } else {
            return null;
        }
    } else {
        return null;
    }
}

From source file:org.orbeon.oxf.xforms.function.Property.java

License:Open Source License

@Override
public Item evaluateItem(XPathContext xpathContext) throws XPathException {

    final String propertyNameString = argument[0].evaluateAsString(xpathContext).toString();
    final QName propertyNameQName = Dom4jUtils.extractTextValueQName(namespaceMappings, propertyNameString,
            false);//  www.  java  2  s .  c  o m

    // Never return any property containing the string "password" as a first line of defense
    if (propertyNameString.toLowerCase().contains("password")) {
        return null;
    }

    if (VERSION_PROPERTY.equals(propertyNameString)) {
        // Standard "version" property
        return VERSION;
    } else if (CONFORMANCE_LEVEL_PROPERTY.equals(propertyNameString)) {
        // Standard "conformance-level" property
        return CONFORMANCE_LEVEL;
    } else if (XFormsConstants.XXFORMS_NAMESPACE_URI.equals(propertyNameQName.getNamespaceURI())) {
        // Property in the xxforms namespace: return our properties

        // Retrieve property
        final Object value = XFormsProperties.getProperty(getContainingDocument(xpathContext),
                propertyNameQName.getName());
        if (value == null)
            return null;

        // Convert Java object to Saxon object before returning it
        return (Item) XFormsUtils.convertJavaObjectToSaxonObject(value);

    } else {
        throw new XPathException("Invalid property() function parameter: " + propertyNameString);
    }
}

From source file:org.orbeon.oxf.xforms.function.xxforms.XXFormsType.java

License:Open Source License

@Override
public Item evaluateItem(XPathContext xpathContext) throws XPathException {

    final Expression nodesetExpression = argument[0];
    // "If the argument is omitted, it defaults to a node-set with the context node as its only
    // member."//from   w w w  .  j av a2 s.c o  m
    final Item item;
    if (nodesetExpression == null)
        item = xpathContext.getContextItem();
    else
        item = nodesetExpression.iterate(xpathContext).next();

    if (item instanceof AtomicValue) {
        // Atomic type
        final ItemType type = ((Value) item).getItemType(null);
        if (type instanceof BuiltInAtomicType) {
            final BuiltInAtomicType atomicType = (BuiltInAtomicType) type;
            final int fingerprint = atomicType.getFingerprint();

            return new QNameValue(StandardNames.getPrefix(fingerprint), StandardNames.getURI(fingerprint),
                    StandardNames.getLocalName(fingerprint), null);
        } else {
            return null;
        }
    } else if (item instanceof NodeInfo) {
        // Get type from node
        final QName typeQName = InstanceData.getType((NodeInfo) item);
        if (typeQName == null)
            return null;

        // Create Saxon QName
        return new QNameValue("", typeQName.getNamespaceURI(), typeQName.getName(), null);
    } else {
        // Return () if we can't access the node or if it is not an atomic value or a node
        return null;
    }
}

From source file:org.orbeon.oxf.xforms.processor.handlers.xhtml.XHTMLBodyHandler.java

License:Open Source License

public static void registerHandlers(final ElementHandlerController controller,
        final XFormsContainingDocument containingDocument) {

    // xf:input//from  www. j  a  v a  2  s.c om
    controller.registerHandler(XFormsInputHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "input", ANY_MATCHER);

    // xf:output
    controller.registerHandler(XFormsOutputTextHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "output", new AppearanceMatcher(XFormsConstants.XXFORMS_TEXT_APPEARANCE_QNAME));
    controller.registerHandler(XFormsOutputDownloadHandler.class.getName(),
            XFormsConstants.XFORMS_NAMESPACE_URI, "output",
            new AppearanceMatcher(XFormsConstants.XXFORMS_DOWNLOAD_APPEARANCE_QNAME));
    controller.registerHandler(XFormsOutputImageHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "output", new Matcher() {
                public Object match(Attributes attributes, Object handlerContext) {
                    final ElementAnalysis elementAnalysis = getElementAnalysis(attributes, handlerContext);
                    // TODO: aks ElementAnalysis for its mediatype
                    final String mediatypeValue = attributes.getValue("mediatype");
                    return mediatypeValue != null && mediatypeValue.startsWith("image/") ? elementAnalysis
                            : null;
                }
            });
    controller.registerHandler(XFormsOutputHTMLHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "output", new Matcher() {
                public Object match(Attributes attributes, Object handlerContext) {
                    final ElementAnalysis elementAnalysis = getElementAnalysis(attributes, handlerContext);
                    // TODO: aks ElementAnalysis for its mediatype
                    final String mediatypeValue = attributes.getValue("mediatype");
                    return mediatypeValue != null && mediatypeValue.equals("text/html") ? elementAnalysis
                            : null;
                }
            });
    controller.registerHandler(XFormsOutputDefaultHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "output", ANY_MATCHER);

    // xf:trigger
    final Matcher triggerSubmitMinimalMatcher = new Matcher() {
        public ElementAnalysis match(Attributes attributes, Object handlerContext) {
            final ElementAnalysis elementAnalysis = getElementAnalysis(attributes, handlerContext);
            return elementAnalysis != null && !containingDocument.getStaticState().isNoscript() // in noscript mode, use the full appearance
                    && hasAppearance(elementAnalysis, XFormsConstants.XFORMS_MINIMAL_APPEARANCE_QNAME) // minimal appearance
                            ? elementAnalysis
                            : null;
        }
    };
    controller.registerHandler(XFormsTriggerMinimalHandler.class.getName(),
            XFormsConstants.XFORMS_NAMESPACE_URI, "trigger", triggerSubmitMinimalMatcher);
    controller.registerHandler(XFormsTriggerFullHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "trigger", ANY_MATCHER);

    // xf:submit
    controller.registerHandler(XFormsTriggerMinimalHandler.class.getName(),
            XFormsConstants.XFORMS_NAMESPACE_URI, "submit", triggerSubmitMinimalMatcher);
    controller.registerHandler(XFormsTriggerFullHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "submit", ANY_MATCHER);

    // xf:group
    controller.registerHandler(XFormsGroupInternalHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "group", new AppearanceMatcher(XFormsConstants.XXFORMS_INTERNAL_APPEARANCE_QNAME));
    controller.registerHandler(XFormsGroupFieldsetHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "group", new AppearanceMatcher(XFormsConstants.XXFORMS_FIELDSET_APPEARANCE_QNAME));
    controller.registerHandler(XFormsGroupSeparatorHandler.class.getName(),
            XFormsConstants.XFORMS_NAMESPACE_URI, "group", new Matcher() {
                public Object match(Attributes attributes, Object handlerContext) {
                    final ElementAnalysis elementAnalysis = getElementAnalysis(attributes, handlerContext);

                    // XFormsAnnotatorContentHandler adds this appearance if needed
                    // See: https://github.com/orbeon/orbeon-forms/issues/418
                    final String appearanceAttributeValue = attributes
                            .getValue(XFormsConstants.APPEARANCE_QNAME.getName());
                    return XFormsConstants.XXFORMS_SEPARATOR_APPEARANCE_QNAME.getQualifiedName()
                            .equals(appearanceAttributeValue) ? elementAnalysis : null;
                }
            });
    controller.registerHandler(XFormsGroupDefaultHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "group", ANY_MATCHER);

    // xf:switch
    // NOTE: We use the same handlers for switch as we do for group
    controller.registerHandler(XFormsGroupSeparatorHandler.class.getName(),
            XFormsConstants.XFORMS_NAMESPACE_URI, "switch", new Matcher() {
                public Object match(Attributes attributes, Object handlerContext) {
                    final ElementAnalysis elementAnalysis = getElementAnalysis(attributes, handlerContext);

                    // XFormsAnnotatorContentHandler adds this appearance if needed
                    // See: https://github.com/orbeon/orbeon-forms/issues/418
                    final String appearanceAttributeValue = attributes
                            .getValue(XFormsConstants.APPEARANCE_QNAME.getName());
                    return XFormsConstants.XXFORMS_SEPARATOR_APPEARANCE_QNAME.getQualifiedName()
                            .equals(appearanceAttributeValue) ? elementAnalysis : null;
                }
            });
    controller.registerHandler(XFormsGroupDefaultHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "switch", ANY_MATCHER);
    controller.registerHandler(XFormsCaseHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI, "case",
            ANY_MATCHER);

    // xf:repeat
    controller.registerHandler(XFormsRepeatHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "repeat", ANY_MATCHER);
    controller.registerHandler(NullElementHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "repeat-iteration", ANY_MATCHER);

    // xf:secret
    controller.registerHandler(XFormsSecretHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "secret", ANY_MATCHER);

    // xf:upload
    controller.registerHandler(XFormsUploadHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "upload", ANY_MATCHER);

    // xf:range
    controller.registerHandler(XFormsRangeHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "range", ANY_MATCHER);

    // Other controls
    controller.registerHandler(XFormsTextareaHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "textarea", ANY_MATCHER);
    if (!containingDocument.getStaticState().isNoscript())
        controller.registerHandler(XXFormsDialogHandler.class.getName(), XFormsConstants.XXFORMS_NAMESPACE_URI,
                "dialog", ANY_MATCHER);
    else
        controller.registerHandler(NullHandler.class.getName(), XFormsConstants.XXFORMS_NAMESPACE_URI, "dialog",
                ANY_MATCHER);

    // xf:select and xf:select1
    controller.registerHandler(XFormsSelect1InternalHandler.class.getName(),
            XFormsConstants.XFORMS_NAMESPACE_URI, "select",
            new AppearanceMatcher(XFormsConstants.XXFORMS_INTERNAL_APPEARANCE_QNAME));
    controller.registerHandler(XFormsSelect1InternalHandler.class.getName(),
            XFormsConstants.XFORMS_NAMESPACE_URI, "select1",
            new AppearanceMatcher(XFormsConstants.XXFORMS_INTERNAL_APPEARANCE_QNAME));
    controller.registerHandler(XFormsSelectHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "select", ANY_MATCHER);
    controller.registerHandler(XFormsSelect1Handler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI,
            "select1", ANY_MATCHER);

    // Add handlers for LHHA elements
    controller.registerHandler(XFormsLHHAHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI, "label",
            ANY_MATCHER);
    controller.registerHandler(XFormsLHHAHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI, "help",
            ANY_MATCHER);
    controller.registerHandler(XFormsLHHAHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI, "hint",
            ANY_MATCHER);
    controller.registerHandler(XFormsLHHAHandler.class.getName(), XFormsConstants.XFORMS_NAMESPACE_URI, "alert",
            ANY_MATCHER);

    // Add handlers for custom components
    final Seq<QName> componentBindings = containingDocument.getStaticOps().jBindingQNames();
    for (final scala.collection.Iterator<QName> i = componentBindings.iterator(); i.hasNext();) {
        final QName currentQName = i.next();
        controller.registerHandler(XXFormsComponentHandler.class.getName(), currentQName.getNamespaceURI(),
                currentQName.getName(), ANY_MATCHER);
    }

    // xxf:dynamic
    controller.registerHandler(XXFormsDynamicHandler.class.getName(), XFormsConstants.XXFORMS_NAMESPACE_URI,
            "dynamic", ANY_MATCHER);
}

From source file:org.orbeon.oxf.xforms.xbl.XBLTransformer.java

License:Open Source License

/**
 * Apply an XBL transformation, i.e. apply xbl:content, xbl:attr, etc.
 *
 * NOTE: This mutates shadowTreeDocument.
 *//*from  w ww  . j a  v  a2s  .com*/
public static Document transform(final Document shadowTreeDocument, final Element boundElement,
        final boolean excludeNestedHandlers, final boolean excludeNestedLHHA) {

    final DocumentWrapper documentWrapper = new DocumentWrapper(boundElement.getDocument(), null,
            XPathCache.getGlobalConfiguration());

    Dom4jUtils.visitSubtree(shadowTreeDocument.getRootElement(), new Dom4jUtils.VisitorListener() {

        boolean isNestedHandler(Element e) {
            return e.getParent() == boundElement && EventHandlerImpl.isEventHandler(e);
        }

        boolean isNestedLHHA(Element e) {
            return e.getParent() == boundElement && LHHA.isLHHA(e);
        }

        boolean mustFilterOut(Element e) {
            return excludeNestedHandlers && isNestedHandler(e) || excludeNestedLHHA && isNestedLHHA(e);
        }

        public void startElement(Element element) {

            // Handle xbl:content

            final boolean isXBLContent = element.getQName().equals(XBL_CONTENT_QNAME);
            final List<Node> resultingNodes;
            if (isXBLContent) {
                final String includesAttribute = element.attributeValue(XFormsConstants.INCLUDES_QNAME);
                final String scopeAttribute = element.attributeValue(XFormsConstants.XXBL_SCOPE_QNAME);
                final List<Node> contentToInsert;
                if (includesAttribute == null) {
                    // All bound node content must be copied over (except nested handlers if requested)
                    final List<Node> elementContent = Dom4jUtils.content(boundElement);
                    final List<Node> clonedContent = new ArrayList<Node>();
                    for (final Node node : elementContent) {
                        if (node instanceof Element) {
                            final Element currentElement = (Element) node;
                            if (!mustFilterOut(currentElement))
                                clonedContent.add(Dom4jUtils.copyElementCopyParentNamespaces(currentElement));
                        } else if (!(node instanceof Namespace)) {
                            clonedContent.add(Dom4jUtils.createCopy(node));
                        }
                    }

                    contentToInsert = clonedContent;
                } else {
                    // Apply CSS selector

                    // Convert CSS to XPath
                    final String xpathExpression = CSSParser.toXPath(includesAttribute);

                    final NodeInfo boundElementInfo = documentWrapper.wrap(boundElement);

                    // TODO: don't use getNamespaceContext() as this is already computed for the bound element
                    final List<Object> elements = XPathCache.evaluate(boundElementInfo, xpathExpression,
                            new NamespaceMapping(Dom4jUtils.getNamespaceContext(element)), null, null, null,
                            null, null, null);// TODO: locationData

                    if (elements.size() > 0) {
                        // Clone all the resulting elements
                        contentToInsert = new ArrayList<Node>(elements.size());
                        for (Object o : elements) {
                            final NodeInfo currentNodeInfo = (NodeInfo) o;
                            final Element currentElement = (Element) ((VirtualNode) currentNodeInfo)
                                    .getUnderlyingNode();

                            if (!mustFilterOut(currentElement))
                                contentToInsert.add(Dom4jUtils.copyElementCopyParentNamespaces(currentElement));
                        }
                    } else {
                        // Clone all the element's children if any
                        // See: http://www.w3.org/TR/xbl/#the-content
                        contentToInsert = new ArrayList<Node>(element.nodeCount());
                        for (Object o : element.elements()) {
                            final Element currentElement = (Element) o;
                            if (!mustFilterOut(currentElement))
                                contentToInsert.add(Dom4jUtils.copyElementCopyParentNamespaces(currentElement));
                        }
                    }
                }

                // Insert content if any
                if (contentToInsert != null && contentToInsert.size() > 0) {
                    final List<Node> parentContent = Dom4jUtils.content(element.getParent());
                    final int elementIndex = parentContent.indexOf(element);
                    parentContent.addAll(elementIndex, contentToInsert);
                }

                // Remove <xbl:content> from shadow tree
                element.detach();

                resultingNodes = contentToInsert;

                if (!StringUtils.isBlank(scopeAttribute)) {
                    // If author specified scope attribute, use it
                    setAttribute(resultingNodes, XFormsConstants.XXBL_SCOPE_QNAME, scopeAttribute, null);
                } else {
                    // By default, set xxbl:scope="outer" on resulting elements
                    setAttribute(resultingNodes, XFormsConstants.XXBL_SCOPE_QNAME, "outer", null);
                }
            } else {
                // Element is simply kept
                resultingNodes = Collections.singletonList((Node) element);
            }

            // Handle attribute forwarding
            final Attribute xblAttr = element.attribute(XBL_ATTR_QNAME); // standard xbl:attr (custom syntax)
            final Attribute xxblAttr = element.attribute(XXBL_ATTR_QNAME); // extension xxbl:attr (XPath expression)
            if (xblAttr != null) {
                // Detach attribute (not strictly necessary?)
                xblAttr.detach();
                // Get attribute value
                final String xblAttrString = xblAttr.getValue();
                final StringTokenizer st = new StringTokenizer(xblAttrString);
                while (st.hasMoreTokens()) {
                    final String currentValue = st.nextToken();

                    final int equalIndex = currentValue.indexOf('=');
                    if (equalIndex == -1) {
                        // No a=b pair, just a single QName
                        final QName valueQName = Dom4jUtils.extractTextValueQName(element, currentValue, true);
                        if (!valueQName.getNamespaceURI().equals(XFormsConstants.XBL_NAMESPACE_URI)) {
                            // This is not xbl:text, copy the attribute
                            setAttribute(resultingNodes, valueQName, boundElement.attributeValue(valueQName),
                                    boundElement);
                        } else {
                            // This is xbl:text
                            // "The xbl:text value cannot occur by itself in the list"
                        }

                    } else {
                        // a=b pair
                        final QName leftSideQName;
                        {
                            final String leftSide = currentValue.substring(0, equalIndex);
                            leftSideQName = Dom4jUtils.extractTextValueQName(element, leftSide, true);
                        }
                        final QName rightSideQName;
                        {
                            final String rightSide = currentValue.substring(equalIndex + 1);
                            rightSideQName = Dom4jUtils.extractTextValueQName(element, rightSide, true);
                        }

                        final boolean isLeftSideXBLText = leftSideQName.getNamespaceURI()
                                .equals(XFormsConstants.XBL_NAMESPACE_URI);
                        final boolean isRightSideXBLText = rightSideQName.getNamespaceURI()
                                .equals(XFormsConstants.XBL_NAMESPACE_URI);

                        final String rightSideValue;
                        final Element namespaceElement;
                        if (!isRightSideXBLText) {
                            // Get attribute value
                            rightSideValue = boundElement.attributeValue(rightSideQName);
                            namespaceElement = boundElement;
                        } else {
                            // Get text value

                            // "any text nodes (including CDATA nodes and whitespace text nodes) that are
                            // explicit children of the bound element must have their data concatenated"
                            rightSideValue = boundElement.getText();// must use getText() and not stringValue()
                            namespaceElement = null;
                        }

                        if (rightSideValue != null) {
                            // NOTE: XBL doesn't seem to says what should happen if the source attribute is not
                            // found! We assume the rule is ignored in this case.
                            if (!isLeftSideXBLText) {
                                // Set attribute value
                                setAttribute(resultingNodes, leftSideQName, rightSideValue, namespaceElement);
                            } else {
                                // Set text value

                                // "value of the attribute on the right-hand side are to be represented as text
                                // nodes underneath the shadow element"

                                // TODO: "If the element has any child nodes in the DOM (any nodes, including
                                // comment nodes, whitespace text nodes, or even empty CDATA nodes) then the pair
                                // is in error and UAs must ignore it, meaning the attribute value is not forwarded"

                                setText(resultingNodes, rightSideValue);
                            }
                        }
                    }
                    // TODO: handle xbl:lang?
                    // TODO: handle type specifiers?
                }
            } else if (xxblAttr != null) {
                // Detach attribute (not strictly necessary?)
                xxblAttr.detach();
                // Get attribute value
                final String xxblAttrString = xxblAttr.getValue();

                final NodeInfo boundElementInfo = documentWrapper.wrap(boundElement);

                // TODO: don't use getNamespaceContext() as this is already computed for the bound element
                final List<Object> nodeInfos = XPathCache.evaluate(boundElementInfo, xxblAttrString,
                        new NamespaceMapping(Dom4jUtils.getNamespaceContext(element)), null, null, null, null,
                        null, null);// TODO: locationData

                if (nodeInfos.size() > 0) {
                    for (Object nodeInfo : nodeInfos) {
                        final NodeInfo currentNodeInfo = (NodeInfo) nodeInfo;
                        if (currentNodeInfo.getNodeKind() == org.w3c.dom.Node.ATTRIBUTE_NODE) {
                            // This is an attribute
                            final Attribute currentAttribute = (Attribute) ((VirtualNode) currentNodeInfo)
                                    .getUnderlyingNode();
                            setAttribute(resultingNodes, currentAttribute.getQName(),
                                    currentAttribute.getValue(), currentAttribute.getParent());
                        }
                    }
                }
            }

            // Prefix resulting xhtml:*/(@id |@for)

            // NOTE: We could also do the prefixing in the handlers, when the page is output.
            //
            // * Benefit of prefixing here: done statically
            // * Drawback of prefixing here: in the future if we try to reuse simple shadow trees this won't work

            //                    {
            //                        if (resultingNodes != null && resultingNodes.size() > 0) {
            //                            for (Iterator i = resultingNodes.iterator(); i.hasNext();) {
            //                                final Node node = (Node) i.next();
            //                                if (node instanceof Element) {
            //                                    Dom4jUtils.visitSubtree((Element) node, new Dom4jUtils.VisitorListener() {
            //                                        public void startElement(Element element) {
            //                                            if (XMLConstants.XHTML_NAMESPACE_URI.equals(element.getNamespaceURI())) {
            //                                                // Found XHTML element
            //
            //                                                // Update @id and @for if any
            //                                                final Attribute idAttribute = element.attribute("id");
            //                                                if (idAttribute != null) {
            //                                                    idAttribute.setValue(prefix + idAttribute.getValue());
            //                                                }
            //                                                final Attribute forAttribute = element.attribute("for");
            //                                                if (forAttribute != null) {
            //                                                    forAttribute.setValue(prefix + forAttribute.getValue());
            //                                                }
            //                                            }
            //                                        }
            //
            //                                        public void endElement(Element element) {
            //                                        }
            //
            //                                        public void text(Text text) {
            //                                        }
            //                                    });
            //                                }
            //                            }
            //                        }
            //                    }
        }

        private void setAttribute(List<Node> nodes, QName attributeQName, String attributeValue,
                Element namespaceElement) {
            if (nodes != null && nodes.size() > 0) {
                for (final Node node : nodes) {
                    if (node instanceof Element) {
                        final Element element = ((Element) node);
                        // Copy missing namespaces, so that copying things like ref="foo:bar" work as expected
                        Dom4jUtils.copyMissingNamespaces(namespaceElement, element);
                        element.addAttribute(attributeQName, attributeValue);
                    }
                }
            }
        }

        private void setText(List<Node> nodes, String value) {
            if (nodes != null && nodes.size() > 0) {
                for (final Node node : nodes) {
                    if (node instanceof Element) {
                        node.setText(value);
                    }
                }
            }
        }

        public void endElement(Element element) {
        }

        public void text(Text text) {
        }
    }, true);

    return shadowTreeDocument;
}

From source file:org.orbeon.oxf.xforms.XFormsModelBinds.java

License:Open Source License

public Item evaluateBindByType(RuntimeBind bind, int position, QName mipType) throws XPathException {

    if (mipType.equals(XFormsConstants.RELEVANT_QNAME)) {
        // Relevant
        final Boolean relevant = evaluateRelevantMIP(bind, position);
        return (relevant != null) ? BooleanValue.get(relevant) : null;
    } else if (mipType.equals(XFormsConstants.READONLY_QNAME)) {
        // Readonly
        final Boolean readonly = evaluateReadonlyMIP(bind, position);
        return (readonly != null) ? BooleanValue.get(readonly) : null;
    } else if (mipType.equals(XFormsConstants.REQUIRED_QNAME)) {
        // Required
        final Boolean required = evaluateRequiredMIP(bind, position);
        return (required != null) ? BooleanValue.get(required) : null;
    } else if (mipType.equals(XFormsConstants.TYPE_QNAME)) {
        // Type//from ww w .j a  va2 s. c  o m
        final NamespaceMapping namespaceMapping = bind.staticBind.namespaceMapping();
        final QName type = bind.evaluateTypeQName(namespaceMapping.mapping);
        return (type != null)
                ? new QNameValue(type.getNamespacePrefix(), type.getNamespaceURI(), type.getName(), null)
                : null;
    } else if (mipType.equals(XFormsConstants.CONSTRAINT_QNAME)) {
        // Constraint
        // TODO: Add support for other constraint levels.
        if (bind.staticBind.constraintsByLevel().nonEmpty())
            return BooleanValue.get(failedConstraintMIPs(StaticBind.jErrorLevel(), bind, position).isEmpty());
        else
            return null;
    } else if (mipType.equals(XFormsConstants.CALCULATE_QNAME)) {
        // Calculate
        final String result = evaluateCalculateBind(bind, position);
        return (result != null) ? new StringValue(result) : null;
    } else if (mipType.equals(XFormsConstants.XXFORMS_DEFAULT_QNAME)) {
        // xxf:default
        final String result = evaluateXXFormsDefaultBind(bind, position);
        return (result != null) ? new StringValue(result) : null;
    } else {
        // Try custom MIPs
        final String result = evaluateCustomMIP(bind, Model.buildCustomMIPName(mipType.getQualifiedName()),
                position);
        return (result != null) ? new StringValue(result) : null;
    }
}

From source file:org.orbeon.oxf.xforms.XFormsModelBinds.java

License:Open Source License

private boolean validateType(RuntimeBind bind, NodeInfo currentNodeInfo, boolean required) {

    final boolean typeValid;
    {//from  w w  w .  j  a v a 2  s .c o m
        // NOTE: xf:bind/@type is a literal type value, and it is the same that applies to all nodes pointed to by xf:bind/@ref
        final QName typeQName = bind.typeQName;

        final String typeNamespaceURI = typeQName.getNamespaceURI();
        final String typeLocalname = typeQName.getName();

        // Get value to validate if not already computed above

        final String nodeValue = DataModel.getValue(currentNodeInfo);

        // TODO: "[...] these datatypes can be used in the type model item property without the addition of the
        // XForms namespace qualifier if the namespace context has the XForms namespace as the default
        // namespace."

        final boolean isBuiltInSchemaType = XMLConstants.XSD_URI.equals(typeNamespaceURI);
        final boolean isBuiltInXFormsType = XFormsConstants.XFORMS_NAMESPACE_URI.equals(typeNamespaceURI);
        final boolean isBuiltInXXFormsType = XFormsConstants.XXFORMS_NAMESPACE_URI.equals(typeNamespaceURI);

        if (isBuiltInXFormsType && Model.jXFormsSchemaTypeNames().contains(typeLocalname)) {
            // xf:dayTimeDuration, xf:yearMonthDuration, xf:email, xf:card-number
            if (xformsValidator == null) {
                xformsValidator = new XFormsModelSchemaValidator("oxf:/org/orbeon/oxf/xforms/xforms-types.xsd");
                xformsValidator.loadSchemas(containingDocument);
            }

            final String validationError = xformsValidator.validateDatatype(nodeValue, typeNamespaceURI,
                    typeLocalname, typeQName.getQualifiedName(), bind.staticBind.locationData());

            typeValid = validationError == null;

        } else if (isBuiltInXFormsType && nodeValue.length() == 0) {
            // Don't consider the node invalid if the string is empty with xf:* types
            typeValid = true;
        } else if (isBuiltInSchemaType || isBuiltInXFormsType) {
            // Built-in schema or XForms type

            // Use XML Schema namespace URI as Saxon doesn't know anything about XForms types
            final String newTypeNamespaceURI = XMLConstants.XSD_URI;

            // Get type information
            final int requiredTypeFingerprint = StandardNames.getFingerprint(newTypeNamespaceURI,
                    typeLocalname);
            if (requiredTypeFingerprint == -1) {
                throw new ValidationException("Invalid schema type '" + bind.staticBind.dataTypeOrNull() + "'",
                        bind.staticBind.locationData());

                // TODO: xxx check what XForms event must be dispatched
            }

            // Need an evaluator to check and convert type below
            final XPathEvaluator xpathEvaluator;
            try {
                xpathEvaluator = new XPathEvaluator();
                // NOTE: Not sure declaring namespaces here is necessary just to perform the cast
                final IndependentContext context = (IndependentContext) xpathEvaluator.getStaticContext();
                for (final Map.Entry<String, String> entry : bind.staticBind.namespaceMapping().mapping
                        .entrySet()) {
                    context.declareNamespace(entry.getKey(), entry.getValue());
                }
            } catch (Exception e) {
                throw OrbeonLocationException.wrapException(e, bind.staticBind.locationData());

                // TODO: xxx check what XForms event must be dispatched
            }

            // Try to perform casting
            // TODO: Should we actually perform casting? This for example removes leading and trailing space around tokens. Is that expected?
            final StringValue stringValue = new StringValue(nodeValue);
            final XPathContext xpContext = new XPathContextMajor(stringValue, xpathEvaluator.getExecutable());
            final ConversionResult result = stringValue.convertPrimitive(
                    (BuiltInAtomicType) BuiltInType.getSchemaType(requiredTypeFingerprint), true, xpContext);

            // Set error on node if necessary
            typeValid = !(result instanceof ValidationFailure);
        } else if (isBuiltInXXFormsType) {
            // Built-in extension types
            final boolean isOptionalAndEmpty = !required && "".equals(nodeValue);
            if (typeLocalname.equals("xml")) {
                // xxf:xml type
                typeValid = isOptionalAndEmpty || XMLUtils.isWellFormedXML(nodeValue);
            } else if (typeLocalname.equals("xpath2")) {
                // xxf:xpath2 type

                // Find element which scopes namespaces
                final NodeInfo namespaceNodeInfo;
                if (currentNodeInfo.getNodeKind() == Node.ELEMENT_NODE)
                    namespaceNodeInfo = currentNodeInfo;
                else
                    namespaceNodeInfo = currentNodeInfo.getParent();

                if (namespaceNodeInfo != null && namespaceNodeInfo.getNodeKind() == Node.ELEMENT_NODE) {
                    // ASSUMPTION: Binding to dom4j-backed node (which InstanceData assumes too)
                    final Element namespaceElement = XML.unwrapElement(namespaceNodeInfo);
                    final NamespaceMapping namespaceMapping = new NamespaceMapping(
                            Dom4jUtils.getNamespaceContextNoDefault(namespaceElement));
                    typeValid = isOptionalAndEmpty || XPath.isXPath2Expression(nodeValue, namespaceMapping,
                            bind.staticBind.locationData(), indentedLogger);
                } else {
                    // This means that we are bound to a node which is not an element and which does not have a
                    // parent element. This could be a detached attribute, or an element node, etc. Unsure if we
                    // would have made it this far anyway! We can't validate the expression so we only consider
                    // the "optional-and-empty" case.
                    typeValid = isOptionalAndEmpty;
                }
            } else {
                throw new ValidationException("Invalid schema type '" + bind.staticBind.dataTypeOrNull() + "'",
                        bind.staticBind.locationData());

                // TODO: xxx check what XForms event must be dispatched
            }

        } else if (model.hasSchema()) {
            // Other type and there is a schema

            // There are possibly types defined in the schema
            final String validationError = model.getSchemaValidator().validateDatatype(nodeValue,
                    typeNamespaceURI, typeLocalname, typeQName.getQualifiedName(),
                    bind.staticBind.locationData());

            typeValid = validationError == null;
        } else {
            throw new ValidationException("Invalid schema type '" + bind.staticBind.dataTypeOrNull() + "'",
                    bind.staticBind.locationData());

            // TODO: xxx check what XForms event must be dispatched
        }
    }
    return typeValid;
}

From source file:org.orbeon.oxf.xforms.XFormsModelSchemaValidator.java

License:Open Source License

/**
 * Validate an element following the XML Schema "lax" mode.
 *
 * @param element   element to validate/*www . j a  v a 2s . c  o m*/
 */
private boolean validateElementLax(final Element element) {

    final String elementURI;
    final String elementName;

    // NOTE: We do some special processing for xsi:type to find if there is a type declared for it. If not, we do
    // lax processing. However, it is not clear whether we should apply lax processing in this case or not. Maybe if
    // an xsi:type is specified and not found, the element should just be invalid.
    // TODO: should pass true?
    final QName xsiType = Dom4jUtils.extractAttributeValueQName(element, XMLConstants.XSI_TYPE_QNAME, false);
    if (xsiType != null) {
        // Honor xsi:type
        elementURI = xsiType.getNamespaceURI();
        elementName = xsiType.getName();
    } else {
        // Use element name
        elementURI = element.getNamespaceURI();
        elementName = element.getName();
    }

    boolean isValid = true;
    {
        // Find expression for element type
        final Expression expression;
        {
            // Find schema for type namespace
            final XMLSchemaSchema schema = ((XMLSchemaGrammar) schemaGrammar).getByNamespace(elementURI);
            if (schema != null) {
                // Try to find the expression in the schema
                final ElementDeclExp elementDeclExp = schema.elementDecls.get(elementName);
                if (elementDeclExp != null) {
                    // Found element type
                    expression = elementDeclExp;
                } else if (xsiType != null) {
                    // Try also complex type
                    expression = schema.complexTypes.get(elementName);
                } else {
                    // No type found
                    expression = null;
                }
            } else {
                // No schema so no expression
                expression = null;
            }
        }

        if (expression != null) {
            // Found type for element, so validate element
            final Acceptor acceptor = documentDeclaration.createAcceptor();
            isValid &= validateElement(element, acceptor, null, true);
        } else {
            // Element does not have type, so try to validate attributes and children elements

            // Attributes
            if (false) {
                // TODO: find out way of validating an attribute only
                // TODO: should we also look at schema.attributeGroups?
                final List attributesList = element.attributes();
                for (final Iterator iterator = attributesList.iterator(); iterator.hasNext();) {
                    final Attribute attribute = (Attribute) iterator.next();
                    final String attributeURI = attribute.getNamespaceURI();
                    final String attributeName = attribute.getName();
                    //                        final String attributeQName = attribute.getQualifiedName();
                    //                        final String attributeValue = attribute.getValue();

                    // Find expression for element type
                    final Expression attributeExpression;
                    {
                        // Find schema for type namespace
                        final XMLSchemaSchema schema = ((XMLSchemaGrammar) schemaGrammar)
                                .getByNamespace(attributeURI);
                        if (schema != null) {
                            attributeExpression = schema.attributeDecls.get(attributeName);
                        } else {
                            attributeExpression = null;
                        }
                    }
                    if (attributeExpression != null) {
                        //                            final ExpressionAcceptor expressionAcceptor = new SimpleAcceptor(documentDeclaration, attributeExpression, null, null);
                        //                            // Validate attribute value
                        //                            final StringRef errorStringRef = new StringRef();
                        //                            final DatatypeRef datatypeRef = new DatatypeRef();
                        //
                        //                            if (!expressionAcceptor.onAttribute2(attributeURI, attributeName, attributeQName, attributeValue, validationContext, errorStringRef, datatypeRef)) {
                        //                                if (errorStringRef.str == null) // not sure if this can happen
                        //                                    errorStringRef.str = "Error validating attribute";
                        //                                addSchemaError(attribute, errorStringRef.str);
                        //                            }

                        //                            if (!expressionAcceptor.onText2(attributeValue, validationContext, errorStringRef, datatypeRef)) {
                        //                                if (errorStringRef.str == null) // not sure if this can happen
                        //                                    errorStringRef.str = "Error validating attribute";
                        //                                addSchemaError(attribute, errorStringRef.str);
                        //                            }
                        //
                        //                            // Check final acceptor state
                        //                            if (!expressionAcceptor.isAcceptState(errorStringRef)) {
                        //                                if (errorStringRef.str == null) // not sure if this can happen
                        //                                    errorStringRef.str = "Error validating attribute";
                        //                                addSchemaError(attribute, errorStringRef.str);
                        //                            }
                    }
                }
            }

            // Validate children elements
            for (final Iterator iterator = element.elementIterator(); iterator.hasNext();) {
                final Element childElement = (Element) iterator.next();
                isValid &= validateElementLax(childElement);
            }
        }
    }
    return isValid;
}

From source file:org.orbeon.oxf.xml.dom4j.Dom4jUtils.java

License:Open Source License

/**
 * Encode a QName to an exploded QName (also known as a "Clark name") String.
 *///  w w  w .j av  a  2 s  . c  o  m
public static String qNameToExplodedQName(QName qName) {
    return (qName == null) ? null : XMLUtils.buildExplodedQName(qName.getNamespaceURI(), qName.getName());
}