Example usage for org.w3c.dom Element getAttributeNS

List of usage examples for org.w3c.dom Element getAttributeNS

Introduction

In this page you can find the example usage for org.w3c.dom Element getAttributeNS.

Prototype

public String getAttributeNS(String namespaceURI, String localName) throws DOMException;

Source Link

Document

Retrieves an attribute value by local name and namespace URI.

Usage

From source file:org.apache.ws.security.util.WSSecurityUtil.java

/**
 * Search through a WSS4J results vector for a single signature covering all
 * these elements.//from   ww w . j a  v  a 2 s. com
 * 
 * NOTE: it is important that the given elements are those that are 
 * referenced using wsu:Id. When the signed element is referenced using a
 * transformation such as XPath filtering the validation is carried out 
 * in signature verification itself.
 * 
 * @param results results (e.g., as stored as WSHandlerConstants.RECV_RESULTS on
 *                an Axis MessageContext)
 * @param elements the elements to check
 * @return the identity of the signer
 * @throws WSSecurityException if no suitable signature could be found or if any element
 *                             didn't have a wsu:Id attribute
 */
public static X509Certificate ensureSignedTogether(Iterator results, Element[] elements)
        throws WSSecurityException {
    log.debug("ensureSignedTogether()");

    if (results == null) {
        throw new IllegalArgumentException("No results vector");
    }
    if (elements == null || elements.length == 0) {
        throw new IllegalArgumentException("No elements to check!");
    }

    // Turn the list of required elements into a list of required wsu:Id
    // strings
    String[] requiredIDs = new String[elements.length];
    for (int i = 0; i < elements.length; i++) {
        Element e = (Element) elements[i];
        if (e == null) {
            throw new IllegalArgumentException("elements[" + i + "] is null!");
        }
        requiredIDs[i] = e.getAttributeNS(WSConstants.WSU_NS, "Id");
        if (requiredIDs[i] == null) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "requiredElementNoID",
                    new Object[] { e.getNodeName() });
        }
        log.debug("Required element " + e.getNodeName() + " has wsu:Id " + requiredIDs[i]);
    }

    WSSecurityException fault = null;

    // Search through the results for a SIGN result
    while (results.hasNext()) {
        WSHandlerResult result = (WSHandlerResult) results.next();
        Iterator actions = result.getResults().iterator();

        while (actions.hasNext()) {
            WSSecurityEngineResult resultItem = (WSSecurityEngineResult) actions.next();
            int resultAction = ((java.lang.Integer) resultItem.get(WSSecurityEngineResult.TAG_ACTION))
                    .intValue();

            if (resultAction == WSConstants.SIGN) {
                try {
                    checkSignsAllElements(resultItem, requiredIDs);
                    return (X509Certificate) resultItem.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
                } catch (WSSecurityException ex) {
                    // Store the exception but keep going... there may be a
                    // better signature later
                    log.debug("SIGN result does not sign all required elements", ex);
                    fault = ex;
                }
            }
        }
    }

    if (fault != null)
        throw fault;

    throw new WSSecurityException(WSSecurityException.FAILED_CHECK, "noSignResult");
}

From source file:org.apache.xml.security.transforms.Transform.java

/**
 * @param element <code>ds:Transform</code> element
 * @param BaseURI the URI of the resource where the XML instance was stored
 * @throws InvalidTransformException/*from  w w w  .j  av a 2s . c  o  m*/
 * @throws TransformationException
 * @throws XMLSecurityException
 */
public Transform(Element element, String BaseURI)
        throws InvalidTransformException, TransformationException, XMLSecurityException {
    super(element, BaseURI);

    // retrieve Algorithm Attribute from ds:Transform
    String algorithmURI = element.getAttributeNS(null, Constants._ATT_ALGORITHM);

    if (algorithmURI == null || algorithmURI.length() == 0) {
        Object exArgs[] = { Constants._ATT_ALGORITHM, Constants._TAG_TRANSFORM };
        throw new TransformationException("xml.WrongContent", exArgs);
    }

    Class<? extends TransformSpi> transformSpiClass = transformSpiHash.get(algorithmURI);
    if (transformSpiClass == null) {
        Object exArgs[] = { algorithmURI };
        throw new InvalidTransformException("signature.Transform.UnknownTransform", exArgs);
    }
    try {
        transformSpi = transformSpiClass.newInstance();
    } catch (InstantiationException ex) {
        Object exArgs[] = { algorithmURI };
        throw new InvalidTransformException("signature.Transform.UnknownTransform", exArgs, ex);
    } catch (IllegalAccessException ex) {
        Object exArgs[] = { algorithmURI };
        throw new InvalidTransformException("signature.Transform.UnknownTransform", exArgs, ex);
    }
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

private void addAttributeSet(Document xForm, Element modelSection, Element formSection,
        XSComplexTypeDefinition controlType, XSElementDeclaration owner, String pathToRoot,
        boolean checkIfExtension) {
    XSObjectList attrUses = controlType.getAttributeUses();

    if (attrUses != null) {
        int nbAttr = attrUses.getLength();
        for (int i = 0; i < nbAttr; i++) {
            XSAttributeUse currentAttributeUse = (XSAttributeUse) attrUses.item(i);
            XSAttributeDeclaration currentAttribute = currentAttributeUse.getAttrDeclaration();

            //test if extended !
            if (checkIfExtension && this.doesAttributeComeFromExtension(currentAttributeUse, controlType)) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(//from   w w  w.ja  v a2s .  c o m
                            "This attribute comes from an extension: recopy form controls. \n Model section: ");
                    DOMUtil.prettyPrintDOM(modelSection);
                }

                String attributeName = currentAttributeUse.getName();
                if (attributeName == null || attributeName.equals(""))
                    attributeName = currentAttributeUse.getAttrDeclaration().getName();

                //find the existing bind Id
                //(modelSection is the enclosing bind of the element)
                NodeList binds = modelSection.getElementsByTagNameNS(XFORMS_NS, "bind");
                int j = 0;
                int nb = binds.getLength();
                String bindId = null;
                while (j < nb && bindId == null) {
                    Element bind = (Element) binds.item(j);
                    String nodeset = bind.getAttributeNS(XFORMS_NS, "nodeset");
                    if (nodeset != null) {
                        String name = nodeset.substring(1); //remove "@" in nodeset
                        if (name.equals(attributeName))
                            bindId = bind.getAttributeNS(XFORMS_NS, "id");
                    }
                    j++;
                }

                //find the control
                Element control = null;
                if (bindId != null) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("bindId found: " + bindId);

                    JXPathContext context = JXPathContext.newContext(formSection.getOwnerDocument());
                    Pointer pointer = context
                            .getPointer("//*[@" + this.getXFormsNSPrefix() + "bind='" + bindId + "']");
                    if (pointer != null)
                        control = (Element) pointer.getNode();
                }

                //copy it
                if (control == null) {
                    LOGGER.warn("Corresponding control not found");
                } else {
                    Element newControl = (Element) control.cloneNode(true);
                    //set new Ids to XForm elements
                    this.resetXFormIds(newControl);

                    formSection.appendChild(newControl);
                }

            } else {
                String newPathToRoot;

                if ((pathToRoot == null) || pathToRoot.equals("")) {
                    newPathToRoot = "@" + currentAttribute.getName();
                } else if (pathToRoot.endsWith("/")) {
                    newPathToRoot = pathToRoot + "@" + currentAttribute.getName();
                } else {
                    newPathToRoot = pathToRoot + "/@" + currentAttribute.getName();
                }

                XSSimpleTypeDefinition simpleType = currentAttribute.getTypeDefinition();
                //TODO SRA: UrType ?
                /*if(simpleType==null){
                simpleType=new UrType();
                }*/

                addSimpleType(xForm, modelSection, formSection, simpleType, currentAttributeUse, newPathToRoot);
            }
        }
    }
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

/**
 * add an element to the XForms document: the bind + the control
 * (only the control if "withBind" is false)
 *//*from   www  . jav  a 2  s .co  m*/
private void addElement(Document xForm, Element modelSection, Element formSection,
        XSElementDeclaration elementDecl, XSTypeDefinition controlType, String pathToRoot) {

    if (controlType == null) {
        // TODO!!! Figure out why this happens... for now just warn...
        // seems to happen when there is an element of type IDREFS
        LOGGER.warn("WARNING!!! controlType is null for " + elementDecl + ", " + elementDecl.getName());

        return;
    }

    switch (controlType.getTypeCategory()) {
    case XSTypeDefinition.SIMPLE_TYPE: {
        addSimpleType(xForm, modelSection, formSection, (XSSimpleTypeDefinition) controlType, elementDecl,
                pathToRoot);

        break;
    }
    case XSTypeDefinition.COMPLEX_TYPE: {

        if (controlType.getName() != null && controlType.getName().equals("anyType")) {
            addAnyType(xForm, modelSection, formSection, (XSComplexTypeDefinition) controlType, elementDecl,
                    pathToRoot);

            break;
        } else {

            // find the types which are compatible(derived from) the parent type.
            //
            // This is used if we encounter a XML Schema that permits the xsi:type
            // attribute to specify subtypes for the element.
            //
            // For example, the <address> element may be typed to permit any of
            // the following scenarios:
            // <address xsi:type="USAddress">
            // </address>
            // <address xsi:type="CanadianAddress">
            // </address>
            // <address xsi:type="InternationalAddress">
            // </address>
            //
            // What we want to do is generate an XForm' switch element with cases
            // representing any valid non-abstract subtype.
            //
            // <xforms:select1 xforms:bind="xsi_type_13"
            //        <xforms:label>Address</xforms:label>
            //        <xforms:choices>
            //                <xforms:item>
            //                        <xforms:label>US Address Type</xforms:label>
            //                        <xforms:value>USAddressType</xforms:value>
            //                        <xforms:action ev:event="xforms-select">
            //                                <xforms:toggle xforms:case="USAddressType-case"/>
            //                        </xforms:action>
            //                </xforms:item>
            //                <xforms:item>
            //                        <xforms:label>Canadian Address Type</xforms:label>
            //                        <xforms:value>CanadianAddressType</xforms:value>
            //                        <xforms:action ev:event="xforms-select">
            //                                <xforms:toggle xforms:case="CanadianAddressType-case"/>
            //                        </xforms:action>
            //                </xforms:item>
            //                <xforms:item>
            //                        <xforms:label>International Address Type</xforms:label>
            //                        <xforms:value>InternationalAddressType</xforms:value>
            //                        <xforms:action ev:event="xforms-select">
            //                                <xforms:toggle xforms:case="InternationalAddressType-case"/>
            //                        </xforms:action>
            //                </xforms:item>
            //
            //          </xforms:choices>
            // <xforms:select1>
            // <xforms:trigger>
            //   <xforms:label>validate Address type</xforms:label>
            //   <xforms:action>
            //      <xforms:dispatch id="dispatcher" xforms:name="xforms-activate" xforms:target="select1_0"/>
            //   </xforms:action>
            //</xforms:trigger>
            //
            // <xforms:switch id="address_xsi_type_switch">
            //      <xforms:case id="USAddressType-case" selected="false">
            //          <!-- US Address Type sub-elements here-->
            //      </xforms:case>
            //      <xforms:case id="CanadianAddressType-case" selected="false">
            //          <!-- US Address Type sub-elements here-->
            //      </xforms:case>
            //      ...
            // </xforms:switch>
            //
            //   + change bindings to add:
            //   - a bind for the "@xsi:type" attribute
            //   - for each possible element that can be added through the use of an inheritance, add a "relevant" attribute:
            //   ex: xforms:relevant="../@xsi:type='USAddress'"

            // look for compatible types
            //
            String typeName = controlType.getName();
            boolean relative = true;

            if (typeName != null) {
                TreeSet compatibleTypes = (TreeSet) typeTree.get(controlType.getName());
                //TreeSet compatibleTypes = (TreeSet) typeTree.get(controlType);

                if (compatibleTypes != null) {
                    relative = false;

                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("compatible types for " + typeName + ":");
                        Iterator it1 = compatibleTypes.iterator();
                        while (it1.hasNext()) {
                            //String name = (String) it1.next();
                            XSTypeDefinition compType = (XSTypeDefinition) it1.next();
                            LOGGER.debug("          compatible type name=" + compType.getName());
                        }
                    }

                    Element control = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "select1");
                    String select1_id = this.setXFormsId(control);

                    Element choices = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "choices");
                    this.setXFormsId(choices);

                    //get possible values
                    Vector enumValues = new Vector();
                    //add the type (if not abstract)
                    if (!((XSComplexTypeDefinition) controlType).getAbstract())
                        enumValues.add(controlType);
                    //enumValues.add(typeName);

                    //add compatible types
                    Iterator it = compatibleTypes.iterator();
                    while (it.hasNext()) {
                        enumValues.add(it.next());
                    }

                    if (enumValues.size() > 1) {

                        String caption = createCaption(elementDecl.getName() + " Type");
                        Element controlCaption = (Element) control
                                .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "label"));
                        this.setXFormsId(controlCaption);
                        controlCaption.appendChild(xForm.createTextNode(caption));

                        // multiple compatible types for this element exist
                        // in the schema - allow the user to choose from
                        // between compatible non-abstract types
                        Element bindElement = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "bind");
                        String bindId = this.setXFormsId(bindElement);

                        bindElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "nodeset",
                                pathToRoot + "/@xsi:type");

                        modelSection.appendChild(bindElement);
                        control.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "bind", bindId);

                        //add the "element" bind, in addition
                        Element bindElement2 = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "bind");
                        String bindId2 = this.setXFormsId(bindElement2);
                        bindElement2.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "nodeset", pathToRoot);

                        modelSection.appendChild(bindElement2);

                        if (enumValues.size() < Long.parseLong(getProperty(SELECTONE_LONG_LIST_SIZE_PROP))) {
                            control.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "appearance",
                                    getProperty(SELECTONE_UI_CONTROL_SHORT_PROP));
                        } else {
                            control.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "appearance",
                                    getProperty(SELECTONE_UI_CONTROL_LONG_PROP));

                            // add the "Please select..." instruction item for the combobox
                            // and set the isValid attribute on the bind element to check for the "Please select..."
                            // item to indicate that is not a valid value
                            //
                            String pleaseSelect = "[Select1 " + caption + "]";
                            Element item = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "item");
                            this.setXFormsId(item);
                            choices.appendChild(item);

                            Element captionElement = xForm.createElementNS(XFORMS_NS,
                                    getXFormsNSPrefix() + "label");
                            this.setXFormsId(captionElement);
                            item.appendChild(captionElement);
                            captionElement.appendChild(xForm.createTextNode(pleaseSelect));

                            Element value = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "value");
                            this.setXFormsId(value);
                            item.appendChild(value);
                            value.appendChild(xForm.createTextNode(pleaseSelect));

                            // not(purchaseOrder/state = '[Choose State]')
                            //String isValidExpr = "not(" + bindElement.getAttributeNS(XFORMS_NS, "nodeset") + " = '" + pleaseSelect + "')";
                            // ->no, not(. = '[Choose State]')
                            String isValidExpr = "not( . = '" + pleaseSelect + "')";

                            //check if there was a constraint
                            String constraint = bindElement.getAttributeNS(XFORMS_NS, "constraint");

                            if ((constraint != null) && !constraint.equals("")) {
                                constraint = constraint + " && " + isValidExpr;
                            } else {
                                constraint = isValidExpr;
                            }

                            bindElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "constraint",
                                    constraint);
                        }

                        Element choicesControlWrapper = _wrapper.createControlsWrapper(choices);
                        control.appendChild(choicesControlWrapper);

                        Element controlWrapper = _wrapper.createControlsWrapper(control);
                        formSection.appendChild(controlWrapper);

                        /////////////////                                      ///////////////
                        // add content to select1
                        HashMap case_types = new HashMap();
                        addChoicesForSelectSwitchControl(xForm, choices, enumValues, case_types);

                        /////////////////
                        //add a trigger for this control (is there a way to not need it ?)
                        Element trigger = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "trigger");
                        formSection.appendChild(trigger);
                        this.setXFormsId(trigger);
                        Element label_trigger = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "label");
                        this.setXFormsId(label_trigger);
                        trigger.appendChild(label_trigger);
                        String trigger_caption = createCaption("validate choice");
                        label_trigger.appendChild(xForm.createTextNode(trigger_caption));
                        Element action_trigger = xForm.createElementNS(XFORMS_NS,
                                getXFormsNSPrefix() + "action");
                        this.setXFormsId(action_trigger);
                        trigger.appendChild(action_trigger);
                        Element dispatch_trigger = xForm.createElementNS(XFORMS_NS,
                                getXFormsNSPrefix() + "dispatch");
                        this.setXFormsId(dispatch_trigger);
                        action_trigger.appendChild(dispatch_trigger);
                        dispatch_trigger.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "name", "DOMActivate");
                        dispatch_trigger.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "target", select1_id);

                        /////////////////
                        //add switch
                        Element switchElement = xForm.createElementNS(XFORMS_NS,
                                getXFormsNSPrefix() + "switch");
                        this.setXFormsId(switchElement);

                        Element switchControlWrapper = _wrapper.createControlsWrapper(switchElement);
                        formSection.appendChild(switchControlWrapper);
                        //formSection.appendChild(switchElement);

                        /////////////// add this type //////////////
                        Element firstCaseElement = (Element) case_types.get(controlType.getName());
                        switchElement.appendChild(firstCaseElement);
                        addComplexType(xForm, modelSection, firstCaseElement,
                                (XSComplexTypeDefinition) controlType, elementDecl, pathToRoot, true, false);

                        /////////////// add sub types //////////////
                        it = compatibleTypes.iterator();
                        // add each compatible type within
                        // a case statement
                        while (it.hasNext()) {
                            /*String compatibleTypeName = (String) it.next();
                            //WARNING: order of parameters inversed from the doc for 2.6.0 !!!
                            XSTypeDefinition type =getSchema().getTypeDefinition(
                                    compatibleTypeName,
                                    targetNamespace);*/
                            XSTypeDefinition type = (XSTypeDefinition) it.next();
                            String compatibleTypeName = type.getName();

                            if (LOGGER.isDebugEnabled()) {
                                if (type == null)
                                    LOGGER.debug(">>>addElement: compatible type is null!! type="
                                            + compatibleTypeName + ", targetNamespace=" + targetNamespace);
                                else
                                    LOGGER.debug("   >>>addElement: adding compatible type " + type.getName());
                            }

                            if (type != null && type.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) {

                                //Element caseElement = (Element) xForm.createElementNS(XFORMS_NS,getXFormsNSPrefix() + "case");
                                //caseElement.setAttributeNS(XFORMS_NS,getXFormsNSPrefix() + "id",bindId + "_" + type.getName() +"_case");
                                //String case_id=this.setXFormsId(caseElement);
                                Element caseElement = (Element) case_types.get(type.getName());
                                switchElement.appendChild(caseElement);

                                addComplexType(xForm, modelSection, caseElement, (XSComplexTypeDefinition) type,
                                        elementDecl, pathToRoot, true, true);

                                //////
                                // modify bind to add a "relevant" attribute that checks the value of @xsi:type
                                //
                                if (LOGGER.isDebugEnabled())
                                    DOMUtil.prettyPrintDOM(bindElement2);
                                NodeList binds = bindElement2.getElementsByTagNameNS(XFORMS_NS, "bind");
                                Element thisBind = null;
                                int nb_binds = binds.getLength();
                                int i = 0;
                                while (i < nb_binds && thisBind == null) {
                                    Element subBind = (Element) binds.item(i);
                                    String name = subBind.getAttributeNS(XFORMS_NS, "nodeset");

                                    if (LOGGER.isDebugEnabled())
                                        LOGGER.debug("Testing sub-bind with nodeset " + name);

                                    if (this.isElementDeclaredIn(name, (XSComplexTypeDefinition) type, false)
                                            || this.isAttributeDeclaredIn(name, (XSComplexTypeDefinition) type,
                                                    false)) {
                                        if (LOGGER.isDebugEnabled())
                                            LOGGER.debug("Element/Attribute " + name + " declared in type "
                                                    + type.getName() + ": adding relevant attribute");

                                        //test sub types of this type
                                        TreeSet subCompatibleTypes = (TreeSet) typeTree.get(type.getName());
                                        //TreeSet subCompatibleTypes = (TreeSet) typeTree.get(type);

                                        String newRelevant = null;
                                        if (subCompatibleTypes == null || subCompatibleTypes.isEmpty()) {
                                            //just add ../@xsi:type='type'
                                            newRelevant = "../@xsi:type='" + type.getName() + "'";
                                        } else {
                                            //add ../@xsi:type='type' or ../@xsi:type='otherType' or ...
                                            newRelevant = "../@xsi:type='" + type.getName() + "'";
                                            Iterator it_ct = subCompatibleTypes.iterator();
                                            while (it_ct.hasNext()) {
                                                //String otherTypeName = (String) it_ct.next();
                                                XSTypeDefinition otherType = (XSTypeDefinition) it_ct.next();
                                                String otherTypeName = otherType.getName();
                                                newRelevant = newRelevant + " or ../@xsi:type='" + otherTypeName
                                                        + "'";
                                            }
                                        }

                                        //change relevant attribute
                                        String relevant = subBind.getAttributeNS(XFORMS_NS, "relevant");
                                        if (relevant != null && !relevant.equals("")) {
                                            newRelevant = "(" + relevant + ") and " + newRelevant;
                                        }
                                        if (newRelevant != null && !newRelevant.equals(""))
                                            subBind.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "relevant",
                                                    newRelevant);
                                    }

                                    i++;
                                }
                            }
                        }

                        /*if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug(
                                "###addElement for derived type: bind created:");
                            DOMUtil.prettyPrintDOM(bindElement2);
                        }*/

                        // we're done
                        //
                        break;

                    } else if (enumValues.size() == 1) {
                        // only one compatible type, set the controlType value
                        // and fall through
                        //
                        //controlType = getSchema().getComplexType((String)enumValues.get(0));
                        controlType = getSchema().getTypeDefinition((String) enumValues.get(0),
                                targetNamespace);
                    }
                } else if (LOGGER.isDebugEnabled())
                    LOGGER.debug("No compatible type found for " + typeName);

                //name not null but no compatibleType?
                relative = true;
            }

            if (relative) //create the bind in case it is a repeat
            {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(">>>Adding empty bind for " + typeName);

                // create the <xforms:bind> element and add it to the model.
                Element bindElement = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "bind");
                String bindId = this.setXFormsId(bindElement);
                bindElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "nodeset", pathToRoot);

                modelSection.appendChild(bindElement);
            } else if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("addElement: bind is not relative for " + elementDecl.getName());
            }

            //addComplexType(xForm,modelSection, formSection,(ComplexType)controlType,elementDecl,pathToRoot, relative);
            addComplexType(xForm, modelSection, formSection, (XSComplexTypeDefinition) controlType, elementDecl,
                    pathToRoot, true, false);

            break;
        }
    }

    default: // TODO: add wildcard support
        LOGGER.warn("\nWARNING!!! - Unsupported type [" + elementDecl.getType() + "] for node ["
                + controlType.getName() + "]");
    }
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

/**
 * checkIfExtension: if false, addElement is called wether it is an extension or not
 * if true, if it is an extension, element is recopied (and no additional bind)
 *//*  w  ww.  j  a v  a  2s  .c om*/
private void addGroup(Document xForm, Element modelSection, Element formSection, XSModelGroup group,
        XSComplexTypeDefinition controlType, XSElementDeclaration owner, String pathToRoot, int minOccurs,
        int maxOccurs, boolean checkIfExtension) {
    if (group != null) {

        Element repeatSection = addRepeatIfNecessary(xForm, modelSection, formSection,
                owner.getTypeDefinition(), minOccurs, maxOccurs, pathToRoot);
        Element repeatContentWrapper = repeatSection;

        if (repeatSection != formSection) {
            //selector -> no more needed?
            //this.addSelector(xForm, repeatSection);
            //group wrapper
            repeatContentWrapper = _wrapper.createGroupContentWrapper(repeatSection);
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug(
                    "addGroup from owner=" + owner.getName() + " and controlType=" + controlType.getName());

        XSObjectList particles = group.getParticles();
        for (int counter = 0; counter < particles.getLength(); counter++) {
            XSParticle currentNode = (XSParticle) particles.item(counter);
            XSTerm term = currentNode.getTerm();

            if (LOGGER.isDebugEnabled())
                LOGGER.debug("   : next term = " + term.getName());

            int childMaxOccurs = currentNode.getMaxOccurs();
            if (currentNode.getMaxOccursUnbounded())
                childMaxOccurs = -1;
            int childMinOccurs = currentNode.getMinOccurs();

            if (term instanceof XSModelGroup) {

                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("   term is a group");

                addGroup(xForm, modelSection, repeatContentWrapper, ((XSModelGroup) term), controlType, owner,
                        pathToRoot, childMinOccurs, childMaxOccurs, checkIfExtension);
            } else if (term instanceof XSElementDeclaration) {
                XSElementDeclaration element = (XSElementDeclaration) term;

                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("   term is an element declaration: " + term.getName());

                //special case for types already added because used in an extension
                //do not add it when it comes from an extension !!!
                //-> make a copy from the existing form control
                if (checkIfExtension && this.doesElementComeFromExtension(element, controlType)) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(
                                "This element comes from an extension: recopy form controls.\n Model Section=");
                        DOMUtil.prettyPrintDOM(modelSection);
                    }

                    //find the existing bind Id
                    //(modelSection is the enclosing bind of the element)
                    NodeList binds = modelSection.getElementsByTagNameNS(XFORMS_NS, "bind");
                    int i = 0;
                    int nb = binds.getLength();
                    String bindId = null;
                    while (i < nb && bindId == null) {
                        Element bind = (Element) binds.item(i);
                        String nodeset = bind.getAttributeNS(XFORMS_NS, "nodeset");
                        if (nodeset != null && nodeset.equals(element.getName()))
                            bindId = bind.getAttributeNS(XFORMS_NS, "id");
                        i++;
                    }

                    //find the control
                    Element control = null;
                    if (bindId != null) {
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug("bindId found: " + bindId);

                        JXPathContext context = JXPathContext.newContext(formSection.getOwnerDocument());
                        Pointer pointer = context
                                .getPointer("//*[@" + this.getXFormsNSPrefix() + "bind='" + bindId + "']");
                        if (pointer != null)
                            control = (Element) pointer.getNode();
                    }

                    //copy it
                    if (control == null) {
                        LOGGER.warn("Corresponding control not found");
                    } else {
                        Element newControl = (Element) control.cloneNode(true);
                        //set new Ids to XForm elements
                        this.resetXFormIds(newControl);

                        repeatContentWrapper.appendChild(newControl);
                    }

                } else { //add it normally
                    String elementName = getElementName(element, xForm);

                    String path = pathToRoot + "/" + elementName;

                    if (pathToRoot.equals("")) { //relative
                        path = elementName;
                    }

                    addElement(xForm, modelSection, repeatContentWrapper, element, element.getTypeDefinition(),
                            path);
                }
            } else { //XSWildcard -> ignore ?
                //LOGGER.warn("XSWildcard found in group from "+owner.getName()+" for pathToRoot="+pathToRoot);
            }
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("--- end of addGroup from owner=" + owner.getName());
    }
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

/**
 * Add a repeat section if maxOccurs > 1.
 *//* w w  w .ja  v a  2s .  c o m*/
private Element addRepeatIfNecessary(Document xForm, Element modelSection, Element formSection,
        XSTypeDefinition controlType, int minOccurs, int maxOccurs, String pathToRoot) {
    Element repeatSection = formSection;

    // add xforms:repeat section if this element re-occurs
    //
    if (maxOccurs != 1) {

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("DEBUG: AddRepeatIfNecessary for multiple element for type " + controlType.getName()
                    + ", maxOccurs=" + maxOccurs);

        //repeatSection = (Element) formSection.appendChild(xForm.createElementNS(XFORMS_NS,getXFormsNSPrefix() + "repeat"));
        repeatSection = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "repeat");

        //bind instead of repeat
        //repeatSection.setAttributeNS(XFORMS_NS,getXFormsNSPrefix() + "nodeset",pathToRoot);
        // bind -> last element in the modelSection
        Element bind = DOMUtil.getLastChildElement(modelSection);
        String bindId = null;

        if ((bind != null) && (bind.getLocalName() != null) && bind.getLocalName().equals("bind")) {
            bindId = bind.getAttributeNS(SchemaFormBuilder.XFORMS_NS, "id");
        } else {
            LOGGER.warn("addRepeatIfNecessary: bind not found: " + bind + " (model selection name="
                    + modelSection.getNodeName() + ")");

            //if no bind is found -> modelSection is already a bind, get its parent last child
            bind = DOMUtil.getLastChildElement(modelSection.getParentNode());

            if ((bind != null) && (bind.getLocalName() != null) && bind.getLocalName().equals("bind")) {
                bindId = bind.getAttributeNS(SchemaFormBuilder.XFORMS_NS, "id");
            } else {
                LOGGER.warn("addRepeatIfNecessary: bind really not found");
            }
        }

        repeatSection.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "bind", bindId);
        this.setXFormsId(repeatSection);

        //appearance=full is more user friendly
        repeatSection.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "appearance", "full");

        //triggers
        this.addTriggersForRepeat(xForm, formSection, repeatSection, minOccurs, maxOccurs, bindId);

        Element controlWrapper = _wrapper.createControlsWrapper(repeatSection);
        formSection.appendChild(controlWrapper);

        //add a group inside the repeat?
        Element group = xForm.createElementNS(XFORMS_NS, this.getXFormsNSPrefix() + "group");
        this.setXFormsId(group);
        repeatSection.appendChild(group);
        repeatSection = group;
    }

    return repeatSection;
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

/**
 * add triggers to use the repeat elements (allow to add an element, ...)
 *///w  w  w .  j a  v a2s.c o  m
private void addTriggersForRepeat(Document xForm, Element formSection, Element repeatSection, int minOccurs,
        int maxOccurs, String bindId) {
    ///////////// insert //////////////////
    //trigger insert
    Element trigger_insert = xForm.createElementNS(SchemaFormBuilder.XFORMS_NS,
            SchemaFormBuilder.xformsNSPrefix + "trigger");
    this.setXFormsId(trigger_insert);

    //label insert
    Element triggerLabel_insert = xForm.createElementNS(SchemaFormBuilder.XFORMS_NS,
            SchemaFormBuilder.xformsNSPrefix + "label");
    this.setXFormsId(triggerLabel_insert);
    trigger_insert.appendChild(triggerLabel_insert);
    triggerLabel_insert.setAttributeNS(SchemaFormBuilder.XLINK_NS, SchemaFormBuilder.xlinkNSPrefix + "href",
            "images/add_new.gif");

    Text label_insert = xForm.createTextNode("Insert after selected");
    triggerLabel_insert.appendChild(label_insert);

    //hint insert
    Element hint_insert = xForm.createElementNS(SchemaFormBuilder.XFORMS_NS,
            SchemaFormBuilder.xformsNSPrefix + "hint");
    this.setXFormsId(hint_insert);
    Text hint_insert_text = xForm.createTextNode("inserts a new entry in this collection");
    hint_insert.appendChild(hint_insert_text);
    trigger_insert.appendChild(hint_insert);

    //insert action
    Element action_insert = xForm.createElementNS(SchemaFormBuilder.XFORMS_NS,
            SchemaFormBuilder.xformsNSPrefix + "action");
    trigger_insert.appendChild(action_insert);
    this.setXFormsId(action_insert);

    Element insert = xForm.createElementNS(SchemaFormBuilder.XFORMS_NS,
            SchemaFormBuilder.xformsNSPrefix + "insert");
    action_insert.appendChild(insert);
    this.setXFormsId(insert);

    //insert: bind & other attributes
    if (bindId != null) {
        insert.setAttributeNS(SchemaFormBuilder.XFORMS_NS, SchemaFormBuilder.xformsNSPrefix + "bind", bindId);
    }

    insert.setAttributeNS(SchemaFormBuilder.XFORMS_NS, SchemaFormBuilder.xformsNSPrefix + "position", "after");

    //xforms:at = xforms:index from the "id" attribute on the repeat element
    String repeatId = repeatSection.getAttributeNS(SchemaFormBuilder.XFORMS_NS, "id");

    if (repeatId != null) {
        insert.setAttributeNS(SchemaFormBuilder.XFORMS_NS, SchemaFormBuilder.xformsNSPrefix + "at",
                SchemaFormBuilder.xformsNSPrefix + "index('" + repeatId + "')");
    }

    ///////////// delete //////////////////
    //trigger delete
    Element trigger_delete = xForm.createElementNS(SchemaFormBuilder.XFORMS_NS,
            SchemaFormBuilder.xformsNSPrefix + "trigger");
    this.setXFormsId(trigger_delete);

    //label delete
    Element triggerLabel_delete = xForm.createElementNS(SchemaFormBuilder.XFORMS_NS,
            SchemaFormBuilder.xformsNSPrefix + "label");
    this.setXFormsId(triggerLabel_delete);
    trigger_delete.appendChild(triggerLabel_delete);
    triggerLabel_delete.setAttributeNS(SchemaFormBuilder.XLINK_NS, SchemaFormBuilder.xlinkNSPrefix + "href",
            "images/delete.gif");

    Text label_delete = xForm.createTextNode("Delete selected");
    triggerLabel_delete.appendChild(label_delete);

    //hint delete
    Element hint_delete = xForm.createElementNS(SchemaFormBuilder.XFORMS_NS,
            SchemaFormBuilder.xformsNSPrefix + "hint");
    this.setXFormsId(hint_delete);
    Text hint_delete_text = xForm.createTextNode("deletes selected entry from this collection");
    hint_delete.appendChild(hint_delete_text);
    trigger_delete.appendChild(hint_delete);

    //delete action
    Element action_delete = xForm.createElementNS(SchemaFormBuilder.XFORMS_NS,
            SchemaFormBuilder.xformsNSPrefix + "action");
    trigger_delete.appendChild(action_delete);
    this.setXFormsId(action_delete);

    Element delete = xForm.createElementNS(SchemaFormBuilder.XFORMS_NS,
            SchemaFormBuilder.xformsNSPrefix + "delete");
    action_delete.appendChild(delete);
    this.setXFormsId(delete);

    //delete: bind & other attributes
    if (bindId != null) {
        delete.setAttributeNS(SchemaFormBuilder.XFORMS_NS, SchemaFormBuilder.xformsNSPrefix + "bind", bindId);
    }

    //xforms:at = xforms:index from the "id" attribute on the repeat element
    if (repeatId != null) {
        delete.setAttributeNS(SchemaFormBuilder.XFORMS_NS, SchemaFormBuilder.xformsNSPrefix + "at",
                SchemaFormBuilder.xformsNSPrefix + "index('" + repeatId + "')");
    }

    //add the triggers
    Element wrapper_triggers = _wrapper.createControlsWrapper(trigger_insert);

    if (wrapper_triggers == trigger_insert) { //no wrapper
        formSection.appendChild(trigger_insert);
        formSection.appendChild(trigger_delete);
    } else {
        formSection.appendChild(wrapper_triggers);

        Element insert_parent = (Element) trigger_insert.getParentNode();

        if (insert_parent != null) {
            insert_parent.appendChild(trigger_delete);
        }
    }
}

From source file:org.chiba.xml.xforms.connector.SchemaValidator.java

/**
 * method to get the target namespace of a schema given by an URI:
 * it opens the schema at the given URI, anf looks for the "targetNamespace" attribute
 *
 * @param uri the URI of the schema/*  w  w  w.  ja  v  a2 s.com*/
 * @return the targetNamespace of the schema, or null of none was found
 */
private String getSchemaNamespace(URI uri) throws Exception {
    String ns = null;

    //load schema
    File schemaFile = new File(uri);
    Document doc = DOMUtil.parseXmlFile(schemaFile, true, false);
    if (doc != null) {
        Element schema = doc.getDocumentElement();
        ns = schema.getAttributeNS(XMLSCHEMA_NS, "targetNamespace");
        if (ns == null || ns.equals("")) //try without NS !
            ns = schema.getAttribute("targetNamespace");
    } else
        LOGGER.warn("Schema " + uri.toString() + " could not be parsed");

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("SchemaValidator.getSchemaNamespace for schema " + uri.toString() + ": " + ns);

    return ns;
}

From source file:org.chiba.xml.xforms.constraints.Validator.java

/**
 * Validates the specified instance data node and its descendants.
 *
 * @param instance the instance to be validated.
 * @param path an xpath denoting an arbitrary subtre of the instance.
 * @return <code>true</code> if all relevant instance data nodes are valid
 *         regarding in terms of their <code>constraint</code> and
 *         <code>required</code> properties, otherwise <code>false</code>.
 *//* ww  w  . j  av  a2  s. c  o m*/
public boolean validate(Instance instance, String path) {
    // initialize
    boolean result = true;
    String expressionPath = path;

    if (!path.endsWith("/")) {
        expressionPath = expressionPath + "/";
    }

    // set expression path to contain the specified path and its subtree
    expressionPath = expressionPath + "descendant-or-self::*";

    // evaluate expression path
    JXPathContext context = instance.getInstanceContext();
    Iterator iterator = context.iteratePointers(expressionPath);
    Pointer locationPointer;
    String locationPath;

    while (iterator.hasNext()) {
        locationPointer = (Pointer) iterator.next();
        locationPath = locationPointer.asPath();
        Element element = (Element) locationPointer.getNode();

        // validate element node against type
        String type = element.getAttributeNS(NamespaceCtx.XMLSCHEMA_INSTANCE_NS, "type");
        result &= validateNode(instance, locationPath, type);

        // handle attributes explicitely since JXPath has
        // seriuos problems with namespaced attributes
        NamedNodeMap attributes = element.getAttributes();

        for (int index = 0; index < attributes.getLength(); index++) {
            Attr attr = (Attr) attributes.item(index);

            if (isInstanceAttribute(attr)) {
                // validate attribute node
                result &= validateNode(instance, locationPath + "/@" + attr.getNodeName());
            }
        }
    }

    return result;
}

From source file:org.chiba.xml.xforms.Model.java

private void loadInlineSchemas(List list) throws XFormsException {
    String schemaId = null;/*from  w w  w  .j  a  v  a2s  .  c o m*/
    try {
        NodeList children = this.element.getChildNodes();

        for (int index = 0; index < children.getLength(); index++) {
            Node child = children.item(index);

            if (Node.ELEMENT_NODE == child.getNodeType()
                    && NamespaceCtx.XMLSCHEMA_NS.equals(child.getNamespaceURI())) {
                Element element = (Element) child;
                schemaId = element.hasAttributeNS(null, "id") ? element.getAttributeNS(null, "id")
                        : element.getNodeName();

                XSModel schema = loadSchema(element);

                if (schema == null) {
                    throw new NullPointerException("resource not found");
                }
                list.add(schema);
            }
        }
    } catch (Exception e) {
        throw new XFormsLinkException("could not load inline schema", this.target, schemaId);
    }
}