Example usage for org.dom4j Element getNamespaceURI

List of usage examples for org.dom4j Element getNamespaceURI

Introduction

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

Prototype

String getNamespaceURI();

Source Link

Document

Returns the URI mapped to the namespace of this element if one exists otherwise an empty String is returned.

Usage

From source file:org.orbeon.oxf.transformer.xupdate.TemplatesHandlerImpl.java

License:Open Source License

private Statement[] parseStatements(List nodes) {
    List statements = new ArrayList();
    for (Iterator i = nodes.iterator(); i.hasNext();) {
        Node node = (Node) i.next();
        if (node.getNodeType() == Node.TEXT_NODE) {
            if (!"".equals(node.getText().trim()))
                statements.add(new Text(node.getText().trim()));
        } else if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            NamespaceContext namespaceContext = new SimpleNamespaceContext(
                    Dom4jUtils.getNamespaceContext(element));
            if (XUpdateConstants.XUPDATE_NAMESPACE_URI.equals(element.getNamespaceURI())) {
                if (element.getName().equals("remove")) {
                    statements.add(new Remove((LocationData) element.getData(),
                            element.attributeValue("select"), namespaceContext));
                } else if (element.getName().equals("update")) {
                    statements/*from  w  w  w.  j a va 2  s . co  m*/
                            .add(new Update((LocationData) element.getData(), element.attributeValue("select"),
                                    namespaceContext, parseStatements(element.content())));
                } else if (element.getName().equals("append")) {
                    statements.add(new Append((LocationData) element.getData(),
                            element.attributeValue("select"), namespaceContext, element.attributeValue("child"),
                            parseStatements(element.content())));
                } else if (element.getName().equals("insert-before")) {
                    statements.add(
                            new InsertBefore((LocationData) element.getData(), element.attributeValue("select"),
                                    namespaceContext, parseStatements(element.content())));
                } else if (element.getName().equals("insert-after")) {
                    statements.add(
                            new InsertAfter((LocationData) element.getData(), element.attributeValue("select"),
                                    namespaceContext, parseStatements(element.content())));
                } else if (element.getName().equals("for-each")) {
                    statements
                            .add(new ForEach((LocationData) element.getData(), element.attributeValue("select"),
                                    namespaceContext, parseStatements(element.content())));
                } else if (element.getName().equals("while")) {
                    statements.add(new While((LocationData) element.getData(), element.attributeValue("select"),
                            namespaceContext, parseStatements(element.content())));
                } else if (element.getName().equals("value-of")) {
                    statements.add(new ValueOf((LocationData) element.getData(),
                            element.attributeValue("select"), namespaceContext));
                } else if (element.getName().equals("copy-of")) {
                    statements.add(new CopyOf((LocationData) element.getData(),
                            element.attributeValue("select"), namespaceContext));
                } else if (element.getName().equals("node-set")) {
                    statements.add(new NodeSet((LocationData) element.getData(),
                            element.attributeValue("select"), namespaceContext));
                } else if (element.getName().equals("attribute")) {
                    statements.add(new Attribute((LocationData) element.getData(), parseQName(element),
                            parseStatements(element.content())));
                } else if (element.getName().equals("namespace")) {
                    statements.add(new Namespace((LocationData) element.getData(),
                            element.attributeValue("name"), element.attributeValue("select"), namespaceContext,
                            parseStatements(element.content())));
                } else if (element.getName().equals("element")) {
                    statements.add(new DynamicElement((LocationData) element.getData(), parseQName(element),
                            parseStatements(element.content())));
                } else if (element.getName().equals("if")) {
                    statements.add(new If((LocationData) element.getData(), element.attributeValue("test"),
                            namespaceContext, parseStatements(element.content())));
                } else if (element.getName().equals("choose")) {
                    List whenTests = new ArrayList();
                    List whenNamespaceContext = new ArrayList();
                    List whenStatements = new ArrayList();
                    for (Iterator j = element.elements("when").iterator(); j.hasNext();) {
                        Element whenElement = (Element) j.next();
                        whenTests.add(whenElement.attributeValue("test"));
                        whenNamespaceContext
                                .add(new SimpleNamespaceContext(Dom4jUtils.getNamespaceContext(whenElement)));
                        whenStatements.add(parseStatements(whenElement.content()));
                    }
                    Element otherwiseElement = element.element("otherwise");
                    statements.add(new Choose((LocationData) element.getData(),
                            (String[]) whenTests.toArray(new String[whenTests.size()]),
                            (NamespaceContext[]) whenNamespaceContext
                                    .toArray(new NamespaceContext[whenNamespaceContext.size()]),
                            (Statement[][]) whenStatements.toArray(new Statement[whenStatements.size()][]),
                            otherwiseElement == null ? null : parseStatements(otherwiseElement.content())));
                } else if (element.getName().equals("variable")) {
                    statements.add(new Variable((LocationData) element.getData(), parseQName(element),
                            element.attributeValue("select"), namespaceContext,
                            parseStatements(element.content())));
                } else if (element.getName().equals("assign")) {
                    statements.add(new Assign((LocationData) element.getData(), parseQName(element),
                            element.attributeValue("select"), namespaceContext,
                            parseStatements(element.content())));
                } else if (element.getName().equals("function")) {
                    statements.add(new Function((LocationData) element.getData(), parseQName(element),
                            parseStatements(element.content())));
                } else if (element.getName().equals("param")) {
                    statements.add(new Param((LocationData) element.getData(), parseQName(element),
                            element.attributeValue("select"), namespaceContext,
                            parseStatements(element.content())));
                } else if (element.getName().equals("message")) {
                    statements.add(
                            new Message((LocationData) element.getData(), parseStatements(element.content())));
                } else if (element.getName().equals("error")) {
                    statements.add(
                            new Error((LocationData) element.getData(), parseStatements(element.content())));
                } else {
                    throw new ValidationException(
                            "Unsupported XUpdate element '" + element.getQualifiedName() + "'",
                            (LocationData) element.getData());
                }
            } else {
                Element staticElement = new NonLazyUserDataElement(element.getQName());
                List childNodes = new ArrayList();
                for (Iterator j = element.attributes().iterator(); j.hasNext();)
                    staticElement.add((org.dom4j.Attribute) ((org.dom4j.Attribute) j.next()).clone());
                for (Iterator j = element.content().iterator(); j.hasNext();) {
                    Node child = (Node) j.next();
                    if (child instanceof org.dom4j.Namespace) {
                        staticElement.add((Node) child.clone());
                    } else {
                        childNodes.add(child);
                    }
                }
                statements.add(new StaticElement((LocationData) element.getData(), staticElement,
                        parseStatements(childNodes)));
            }
        } else if (node.getNodeType() == Node.NAMESPACE_NODE) {
            // Ignore namespace declarations
        } else {
            throw new OXFException("Unsupported node: " + node.getNodeTypeName());
        }
    }
    return (Statement[]) statements.toArray(new Statement[statements.size()]);
}

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

License:Open Source License

/**
 * Obtain the single-node binding for an enclosing xf:group, xf:repeat, or xf:switch. It takes one
 * mandatory string parameter containing the id of an enclosing grouping XForms control. For xf:repeat, the
 * context returned is the context of the current iteration.
 *
 * @param contextId  enclosing context id
 * @return           the item//from w  ww  . jav a 2  s  .  c o  m
 */
public Item getContextForId(String contextId) {
    BindingContext currentBindingContext = this.head;
    do {
        final Element bindingElement = currentBindingContext.getControlElement();
        if (bindingElement != null && XFormsControlFactory.isContainerControl(bindingElement.getNamespaceURI(),
                bindingElement.getName())) {
            // We are a grouping control
            final String elementId = currentBindingContext.elementId();
            if (contextId.equals(elementId)) {
                // Found matching binding context for regular grouping control
                return currentBindingContext.getSingleItem();
            }
        } else if (bindingElement == null) {
            // We a likely repeat iteration
            if (isRepeatIterationBindingContext(currentBindingContext)
                    && currentBindingContext.parent().elementId().equals(contextId)) {
                // Found matching repeat iteration
                return currentBindingContext.getSingleItem();
            }
        }
        currentBindingContext = currentBindingContext.parent();
    } while (currentBindingContext != null);
    // It is required that there is an enclosing container control
    throw new ValidationException("No enclosing container XForms control found for id: " + contextId,
            this.head.locationData());
}

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

License:Open Source License

private boolean validateElement(final Element element, final Acceptor acceptor, final IDConstraintChecker icc,
        final boolean isReportErrors) {

    boolean isElementValid = true;

    // Create StartTagInfo
    final StartTagInfo startTagInfo;
    {/*from ww  w.  ja v a 2 s . c o m*/
        final String uri = element.getNamespaceURI();
        final String name = element.getName();
        final String qName = element.getQualifiedName();
        final List attributesList = element.attributes();
        final AttributesImpl attributes = new AttributesImpl();

        for (Object anAttributesList : attributesList) {
            final Attribute attribute = (Attribute) anAttributesList;
            final String attributeURI = attribute.getNamespaceURI();
            final String attributeName = attribute.getName();
            final String attributeQName = attribute.getQualifiedName();
            final String attributeValue = attribute.getValue();
            attributes.addAttribute(attributeURI, attributeName, attributeQName, null, attributeValue);
        }
        validationContext.setCurrentElement(element);
        startTagInfo = new StartTagInfo(uri, name, qName, attributes, validationContext);
    }

    final StringRef stringRef = new StringRef();

    // Get child acceptor
    final Acceptor childAcceptor;
    {
        Acceptor tempChildAcceptor = acceptor.createChildAcceptor(startTagInfo, null);
        if (tempChildAcceptor == null) {
            if (isReportErrors) {
                tempChildAcceptor = acceptor.createChildAcceptor(startTagInfo, stringRef);
                addSchemaError(element, stringRef.str);
                isElementValid = false;
            } else {
                return false;
            }
        }
        childAcceptor = tempChildAcceptor;
    }

    // Handle id errors
    if (icc != null && isReportErrors) {
        icc.onNextAcceptorReady(startTagInfo, childAcceptor, element);
        isElementValid &= handleIDErrors(icc);
    }

    // Validate children
    final DatatypeRef datatypeRef = new DatatypeRef();
    final boolean childrenValid = validateChildren(element, childAcceptor, startTagInfo, icc, datatypeRef,
            isReportErrors);
    if (!childrenValid) {
        if (isReportErrors)
            isElementValid = false;
        else
            return false;
    }

    // TODO: MSV doesn't allow getting the type if validity check fails. However, we would like to obtain datatype validity in XForms.
    if (!childAcceptor.isAcceptState(null)) {
        if (isReportErrors) {
            childAcceptor.isAcceptState(stringRef);
            addSchemaError(element, stringRef.str);
            isElementValid = false;
        } else {
            return false;
        }
    } else {
        // Attempt to set datatype name
        setDataType(datatypeRef, element);
    }

    // Handle id errors
    if (icc != null && isReportErrors) {
        icc.endElement(element, datatypeRef.types);
        isElementValid &= handleIDErrors(icc);
    }

    // Get back to parent acceptor
    if (!acceptor.stepForward(childAcceptor, null)) {
        if (isReportErrors) {
            acceptor.stepForward(childAcceptor, stringRef);
            addSchemaError(element, stringRef.str);
            isElementValid = false;
        } else {
            return false;
        }
    }

    if (isReportErrors) {
        // Element may be invalid or not
        return isElementValid;
    } else {
        // This element is valid
        return true;
    }
}

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//from  w  ww.jav a2s . 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.ElementHandlerController.java

License:Open Source License

/**
 * Get an ElementHandler based on a dom4j element.
 *
 * @param element   element//from  www  .  j a va  2s  .c  o  m
 * @return          handler if found
 */
public ElementHandler getHandler(Element element) {
    final HandlerInfo handlerInfo = getHandler(element.getNamespaceURI(),
            XMLUtils.buildExplodedQName(element.getNamespaceURI(), element.getName()),
            XMLUtils.getSAXAttributes(element));

    return (handlerInfo != null) ? handlerInfo.elementHandler : null;
}

From source file:org.xmpp.component.SlowRespondingThreadNameComponent.java

License:Open Source License

/**
 * Processes the tinder:debug requests./*from   w  w w  .  j  a  v a  2s .c o m*/
 */
@Override
protected IQ handleIQGet(IQ request) throws Exception {
    final Element element = request.getChildElement();
    if (!DEBUG_NAMESPACE.equals(element.getNamespaceURI())) {
        log.debug("Can not process {}", request.toXML());
        return null;
    }

    if (ELEMENTNAME_SLOWRESPONSE.equals(element.getName())) {
        log.debug("Waiting 4000 millis before responding to: {}", request.toXML());
        Thread.sleep(4000);
        log.debug("Responding to {} now.", request.toXML());
        return IQ.createResultIQ(request);
    }

    if (ELEMENTNAME_THREADNAME.equals(element.getName())) {
        final String threadName = Thread.currentThread().getName();
        final IQ response = IQ.createResultIQ(request);
        response.setChildElement(ELEMENTNAME_THREADNAME, DEBUG_NAMESPACE).addText(threadName);
        log.debug("Responding to {} with {}", request.toXML(), response.toXML());
        return response;
    }

    log.debug("Cannot process {}", request.toXML());
    return null;
}

From source file:org.xmpp.packet.Message.java

License:Open Source License

/**
 * Returns the first child element of this packet that matches the
 * given name and namespace. If no matching element is found,
 * <tt>null</tt> will be returned. This is a convenience method to avoid
 * manipulating this underlying packet's Element instance directly.<p>
 *
 * Child elements in extended namespaces are used to extend the features
 * of XMPP. Examples include a "user is typing" indicator and invitations to
 * group chat rooms. Although any valid XML can be included in a child element
 * in an extended namespace, many common features have been standardized
 * as <a href="http://www.jabber.org/jeps">Jabber Enhancement Proposals</a>
 * (JEPs).//from   www .  j av a2  s  . c  om
 *
 * @param name the element name.
 * @param namespace the element namespace.
 * @return the first matching child element, or <tt>null</tt> if there
 *      is no matching child element.
 */
public Element getChildElement(String name, String namespace) {
    for (Iterator i = element.elementIterator(name); i.hasNext();) {
        Element element = (Element) i.next();
        if (element.getNamespaceURI().equals(namespace)) {
            return element;
        }
    }
    return null;
}

From source file:org.xmpp.packet.PacketError.java

License:Open Source License

/**
 * Returns the error condition.//from ww w.j  a  va 2s .  co  m
 *
 * @return the error condition.
 * @see Condition
 */
public Condition getCondition() {
    for (Iterator i = element.elementIterator(); i.hasNext();) {
        Element el = (Element) i.next();
        if (el.getNamespaceURI().equals(ERROR_NAMESPACE) && !el.getName().equals("text")) {
            return Condition.fromXMPP(el.getName());
        }
    }
    // Looking for XMPP condition failed. See if a legacy error code exists,
    // which can be mapped into an XMPP error condition.
    String code = element.attributeValue("code");
    if (code != null) {
        try {
            return Condition.fromLegacyCode(Integer.parseInt(code));
        } catch (Exception e) {
            // Ignore -- unable to map legacy code into a valid condition
            // so return null.
        }
    }
    return null;
}

From source file:org.xmpp.packet.PacketError.java

License:Open Source License

/**
 * Sets the error condition./* w  w  w  .ja v  a 2 s  . c  o m*/
 *
 * @param condition the error condition.
 * @see Condition
 */
public void setCondition(Condition condition) {
    if (condition == null) {
        throw new NullPointerException("Condition cannot be null");
    }
    // Set the error code for legacy support.
    element.addAttribute("code", Integer.toString(condition.getLegacyCode()));

    Element conditionElement = null;
    for (Iterator i = element.elementIterator(); i.hasNext();) {
        Element el = (Element) i.next();
        if (el.getNamespaceURI().equals(ERROR_NAMESPACE) && !el.getName().equals("text")) {
            conditionElement = el;
        }
    }
    if (conditionElement != null) {
        element.remove(conditionElement);
    }

    conditionElement = docFactory.createElement(condition.toXMPP(), ERROR_NAMESPACE);
    element.add(conditionElement);
}

From source file:z.pn.xmpp.net.StanzaHandler.java

License:Open Source License

/**
 * /*from  w w  w .j  a v  a 2s  .c om*/
 * ??  ??IQ
 * @author Mars zhang
 * @created 2016212 ?12:51:02
 * @param doc
 * @return
 */
private IQ getIQ(Element doc) {
    Element query = doc.element("query");
    if (query != null && "jabber:iq:roster".equals(query.getNamespaceURI())) {
        return new Roster(doc);
    } else {
        return new IQ(doc, false);
    }
}