Example usage for org.w3c.dom Element setAttributeNS

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

Introduction

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

Prototype

public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;

Source Link

Document

Adds a new attribute.

Usage

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 w w  w. j a v a2  s  .  c o  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

/**
 * Add a repeat section if maxOccurs > 1.
 *//* ww  w  .  j av  a2  s  . co 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

/**
 * if "createBind", a bind is created, otherwise bindId is used
 *///w ww . jav  a 2 s .c  om
private void addSimpleType(Document xForm, Element modelSection, Element formSection,
        XSTypeDefinition controlType, String owningElementName, XSObject owner, String pathToRoot,
        int minOccurs, int maxOccurs) {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("addSimpleType for " + controlType.getName() + " (owningElementName=" + owningElementName
                + ")");

    // 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);
    bindElement = (Element) modelSection.appendChild(bindElement);
    bindElement = startBindElement(bindElement, controlType, minOccurs, maxOccurs);

    // add a group if a repeat !
    if (owner instanceof XSElementDeclaration && maxOccurs != 1) {
        Element groupElement = createGroup(xForm, modelSection, formSection, (XSElementDeclaration) owner);
        //set content
        Element groupWrapper = groupElement;
        if (groupElement != modelSection) {
            groupWrapper = _wrapper.createGroupContentWrapper(groupElement);
        }
        formSection = groupWrapper;
    }

    //eventual repeat
    Element repeatSection = addRepeatIfNecessary(xForm, modelSection, formSection, controlType, minOccurs,
            maxOccurs, pathToRoot);

    // create the form control element
    //put a wrapper for the repeat content, but only if it is really a repeat
    Element contentWrapper = repeatSection;

    if (repeatSection != formSection) {
        //content of repeat
        contentWrapper = _wrapper.createGroupContentWrapper(repeatSection);

        //if there is a repeat -> create another bind with "."
        Element bindElement2 = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "bind");
        String bindId2 = this.setXFormsId(bindElement2);
        bindElement2.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "nodeset", ".");

        //recopy other attributes: required  and type
        // ->no, attributes shouldn't be copied
        /*String required = "required";
        String type = "type";
        if (bindElement.hasAttributeNS(XFORMS_NS, required)) {
        bindElement2.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + required,
                                    bindElement.getAttributeNS(XFORMS_NS, required));
        }
        if (bindElement.hasAttributeNS(XFORMS_NS, type)) {
        bindElement2.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + type,
                                    bindElement.getAttributeNS(XFORMS_NS, type));
        }*/

        bindElement.appendChild(bindElement2);
        bindId = bindId2;
    }

    String caption = createCaption(owningElementName);

    //Element formControl = (Element) contentWrapper.appendChild(createFormControl(xForm,caption,controlType,bindId,bindElement,minOccurs,maxOccurs));
    Element formControl = createFormControl(xForm, caption, controlType, bindId, bindElement, minOccurs,
            maxOccurs);
    Element controlWrapper = _wrapper.createControlsWrapper(formControl);
    contentWrapper.appendChild(controlWrapper);

    // if this is a repeatable then set ref to point to current element
    // not sure if this is a workaround or this is just the way XForms works...
    //
    if (!repeatSection.equals(formSection)) {
        formControl.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "ref", ".");
    }

    Element hint = createHint(xForm, owner);

    if (hint != null) {
        formControl.appendChild(hint);
    }

    //add selector if repeat
    //if (repeatSection != formSection)
    //this.addSelector(xForm, (Element) formControl.getParentNode());
    //
    // TODO: Generate help message based on datatype and restrictions
    endFormControl(formControl, controlType, minOccurs, maxOccurs);
    endBindElement(bindElement);
}

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

/**
 * add triggers to use the repeat elements (allow to add an element, ...)
 *///from w  w  w  .j ava 2s.co 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.tools.schemabuilder.AbstractSchemaFormBuilder.java

private Element createFormControl(Document xForm, String caption, XSTypeDefinition controlType, String bindId,
        Element bindElement, int minOccurs, int maxOccurs) {
    // Select1 xform control to use:
    // Will use one of the following: input, textarea, selectOne, selectBoolean, selectMany, range
    // secret, output, button, do not apply
    //// w ww . j  a  va 2 s  .  c o m
    // select1: enumeration or keyref constrained value
    // select: list
    // range: union (? not sure about this)
    // textarea : ???
    // input: default
    //
    Element formControl = null;

    if (controlType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) {
        XSSimpleTypeDefinition simpleType = (XSSimpleTypeDefinition) controlType;
        if (simpleType.getItemType() != null) //list
        {
            formControl = createControlForListType(xForm, simpleType, caption, bindElement);
        } else { //other simple type
            // need to check constraints to determine which form control to use
            //
            // use the selectOne control
            //
            //XSObjectList enumerationFacets = simpleType.getFacets(XSSimpleTypeDefinition.FACET_ENUMERATION);
            //if(enumerationFacets.getLength()>0){
            if (simpleType.isDefinedFacet(XSSimpleTypeDefinition.FACET_ENUMERATION)) {
                formControl = createControlForEnumerationType(xForm, simpleType, caption, bindElement);
            }
            /*if (enumerationFacets.hasMoreElements()) {
            formControl = createControlForEnumerationType(xForm, (SimpleType)controlType, caption,
                                              bindElement);
            } */
        }
    } else if (controlType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE
            && controlType.getName().equals("anyType")) {
        formControl = createControlForAnyType(xForm, caption, controlType);
    }

    if (formControl == null) {
        // default situation - use an input control
        //
        formControl = createControlForAtomicType(xForm, caption, (XSSimpleTypeDefinition) controlType);
    }

    startFormControl(formControl, controlType);
    formControl.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "bind", bindId);

    //put the label before
    // no -> put in the "createControlFor..." methods

    /*Element captionElement=xForm.createElementNS(XFORMS_NS,getXFormsNSPrefix() + "label");
       this.setXFormsId(captionElement);
       captionElement.appendChild(xForm.createTextNode(caption));
       if(formControl.hasChildNodes())
       {
       Node first=formControl.getFirstChild();
       captionElement = (Element) formControl.insertBefore(captionElement, first);
       }
       else
       captionElement = (Element) formControl.appendChild(captionElement);        */

    // TODO: Enhance alert statement based on facet restrictions.
    // TODO: Enhance to support minOccurs > 1 and maxOccurs > 1.
    // TODO: Add i18n/l10n suppport to this - use java MessageFormatter...
    //
    //       e.g. Please provide a valid value for 'Address'. 'Address' is a mandatory decimal field.
    //
    Element alertElement = (Element) formControl
            .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "alert"));
    this.setXFormsId(alertElement);

    StringBuffer alert = new StringBuffer("Please provide a valid value for '" + caption + "'.");

    Element enveloppe = xForm.getDocumentElement();

    if (minOccurs != 0) {
        alert.append(" '" + caption + "' is a required '"
                + createCaption(this.getXFormsTypeName(enveloppe, controlType)) + "' value.");
    } else {
        alert.append(" '" + caption + "' is an optional '"
                + createCaption(this.getXFormsTypeName(enveloppe, controlType)) + "' value.");
    }

    alertElement.appendChild(xForm.createTextNode(alert.toString()));

    return formControl;
}

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

private Document createFormTemplate(String formId, String formName, String stylesheet)
        throws ParserConfigurationException {
    Document xForm = documentBuilder.newDocument();

    Element envelopeElement = _wrapper.createEnvelope(xForm);

    // set required namespace attributes
    envelopeElement.setAttributeNS(XMLNS_NAMESPACE_URI,
            "xmlns:" + getChibaNSPrefix().substring(0, getChibaNSPrefix().length() - 1), CHIBA_NS);
    envelopeElement.setAttributeNS(XMLNS_NAMESPACE_URI,
            "xmlns:" + getXFormsNSPrefix().substring(0, getXFormsNSPrefix().length() - 1), XFORMS_NS);
    envelopeElement.setAttributeNS(XMLNS_NAMESPACE_URI,
            "xmlns:" + getXLinkNSPrefix().substring(0, getXLinkNSPrefix().length() - 1), XLINK_NS);
    //XMLEvent//from w  ww.  ja v a2  s .co m
    envelopeElement.setAttributeNS(XMLNS_NAMESPACE_URI,
            "xmlns:" + xmleventsNSPrefix.substring(0, xmleventsNSPrefix.length() - 1), XMLEVENTS_NS);
    //XML Schema Instance
    envelopeElement.setAttributeNS(XMLNS_NAMESPACE_URI,
            "xmlns:" + xmlSchemaInstancePrefix.substring(0, xmlSchemaInstancePrefix.length() - 1),
            XMLSCHEMA_INSTANCE_NAMESPACE_URI);
    //base
    if (_base != null && !_base.equals("")) {
        envelopeElement.setAttributeNS(XML_NAMESPACE_URI, "xml:base", _base);
    }

    //model element
    Element modelElement = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "model");
    this.setXFormsId(modelElement);
    Element modelWrapper = _wrapper.createModelWrapper(modelElement);
    envelopeElement.appendChild(modelWrapper);

    //form control wrapper -> created by wrapper
    //Element formWrapper = xForm.createElement("body");
    //envelopeElement.appendChild(formWrapper);
    Element formWrapper = _wrapper.createFormWrapper(envelopeElement);

    return xForm;
}

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

/**
 * Get a fully qualified name for this element, and eventually declares a new prefix for the namespace if
 * it was not declared before//w  ww.  j a v a  2  s.co  m
 *
 * @param element
 * @param xForm
 * @return
 */
private String getElementName(XSElementDeclaration element, Document xForm) {
    String elementName = element.getName();
    String namespace = element.getNamespace();
    if (namespace != null && !namespace.equals("")) {
        String prefix;
        if ((prefix = (String) namespacePrefixes.get(namespace)) == null) {
            String basePrefix = (namespace.substring(namespace.lastIndexOf('/', namespace.length() - 2) + 1));
            int i = 1;
            prefix = basePrefix;
            while (namespacePrefixes.containsValue(prefix)) {
                prefix = basePrefix + (i++);
            }
            namespacePrefixes.put(namespace, prefix);
            Element envelope = xForm.getDocumentElement();
            envelope.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:" + prefix, namespace);
        }
        elementName = prefix + ":" + elementName;
    }
    return elementName;
}

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

/**
 * validate the instance according to the schema specified on the model
 *
 * @return false if the instance is not valid
 *//*  w  w w .j  a v  a  2 s.c  om*/
public boolean validateSchema(Model model, Node instance) throws XFormsException {
    boolean valid = true;
    String message;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("SchemaValidator.validateSchema: validating instance");

    //needed if we want to load schemas from Model + set it as "schemaLocation" attribute
    String schemas = model.getElement().getAttributeNS(NamespaceConstants.XFORMS_NS, "schema");
    if (schemas != null && !schemas.equals("")) {
        //          valid=false;

        //add schemas to element
        //shouldn't it be done on a copy of the doc ?
        Element el = null;
        if (instance.getNodeType() == Node.ELEMENT_NODE)
            el = (Element) instance;
        else if (instance.getNodeType() == Node.DOCUMENT_NODE)
            el = ((Document) instance).getDocumentElement();
        else {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("instance node type is: " + instance.getNodeType());
        }

        String prefix = NamespaceResolver.getPrefix(el, XMLSCHEMA_INSTANCE_NS);
        //test if with targetNamespace or not
        //if more than one schema : namespaces are mandatory ! (optional only for 1)
        StringTokenizer tokenizer = new StringTokenizer(schemas, " ", false);
        String schemaLocations = null;
        String noNamespaceSchemaLocation = null;
        while (tokenizer.hasMoreElements()) {
            String token = (String) tokenizer.nextElement();
            //check that it is an URL
            URI uri = null;
            try {
                uri = new java.net.URI(token);
            } catch (java.net.URISyntaxException ex) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(token + " is not an URI");
            }

            if (uri != null) {
                String ns;
                try {
                    ns = this.getSchemaNamespace(uri);

                    if (ns != null && !ns.equals("")) {
                        if (schemaLocations == null)
                            schemaLocations = ns + " " + token;
                        else
                            schemaLocations = schemaLocations + " " + ns + " " + token;

                        ///add the namespace declaration if it is not on the instance?
                        //TODO: how to know with which prefix ?
                        String nsPrefix = NamespaceResolver.getPrefix(el, ns);
                        if (nsPrefix == null) { //namespace not declared !
                            LOGGER.warn("SchemaValidator: targetNamespace " + ns + " of schema " + token
                                    + " is not declared in instance: declaring it as default...");
                            el.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX, ns);
                        }
                    } else if (noNamespaceSchemaLocation == null)
                        noNamespaceSchemaLocation = token;
                    else { //we have more than one schema without namespace
                        LOGGER.warn("SchemaValidator: There is more than one schema without namespace !");
                    }
                } catch (Exception ex) {
                    LOGGER.warn(
                            "Exception while trying to load schema: " + uri.toString() + ": " + ex.getMessage(),
                            ex);
                    //in case there was an exception: do nothing, do not set the schema
                }
            }
        }
        //write schemaLocations found
        if (schemaLocations != null && !schemaLocations.equals(""))
            el.setAttributeNS(XMLSCHEMA_INSTANCE_NS, prefix + ":schemaLocation", schemaLocations);
        if (noNamespaceSchemaLocation != null)
            el.setAttributeNS(XMLSCHEMA_INSTANCE_NS, prefix + ":noNamespaceSchemaLocation",
                    noNamespaceSchemaLocation);

        //save and parse the doc
        ValidationErrorHandler handler = null;
        File f;
        try {
            //save document
            f = File.createTempFile("instance", ".xml");
            f.deleteOnExit();
            TransformerFactory trFact = TransformerFactory.newInstance();
            Transformer trans = trFact.newTransformer();
            DOMSource source = new DOMSource(el);
            StreamResult result = new StreamResult(f);
            trans.transform(source, result);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Validator.validateSchema: file temporarily saved in " + f.getAbsolutePath());

            //parse it with error handler to validate it
            handler = new ValidationErrorHandler();
            SAXParserFactory parserFact = SAXParserFactory.newInstance();
            parserFact.setValidating(true);
            parserFact.setNamespaceAware(true);
            SAXParser parser = parserFact.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            //validation activated
            reader.setFeature("http://xml.org/sax/features/validation", true);
            //schema validation activated
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            //used only to validate the schema, not the instance
            //reader.setFeature( "http://apache.org/xml/features/validation/schema-full-checking", true);
            //validate only if there is a grammar
            reader.setFeature("http://apache.org/xml/features/validation/dynamic", true);

            parser.parse(f, handler);
        } catch (Exception ex) {
            LOGGER.warn("Validator.validateSchema: Exception in XMLSchema validation: " + ex.getMessage(), ex);
            //throw new XFormsException("XMLSchema validation failed. "+message);
        }

        //if no exception
        if (handler != null && handler.isValid())
            valid = true;
        else {
            message = handler.getMessage();
            //TODO: find a way to get the error message displayed
            throw new XFormsException("XMLSchema validation failed. " + message);
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Validator.validateSchema: result=" + valid);

    }

    return valid;
}

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

private static void addAttributes(Element relevantElement, NodeImpl instanceNode) {
    NamedNodeMap instanceAttributes = instanceNode.getAttributes();

    for (int index = 0; index < instanceAttributes.getLength(); index++) {
        NodeImpl instanceAttr = (NodeImpl) instanceAttributes.item(index);

        if (isEnabled(instanceAttr)) {
            if (instanceAttr.getNamespaceURI() == null) {
                relevantElement.setAttribute(instanceAttr.getNodeName(), instanceAttr.getNodeValue());
            } else {
                relevantElement.setAttributeNS(instanceAttr.getNamespaceURI(), instanceAttr.getNodeName(),
                        instanceAttr.getNodeValue());
            }//from w  w w.  jav a  2s.c  o  m
        }
    }
}

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

/**
 * Allows to set or overwrite a instance's src URI.
 * <p/>/*from  w  w  w .  j a  v a2 s. co m*/
 * This method can be used to provide a parametrized URI to the URI resolver which handles the instance's src URI.
 *
 * @param id     the id of the instance.
 * @param srcURI the source URI.
 * @throws XFormsException if no document is present or the specified instance does not exist.
 * @see org.chiba.xml.xforms.connector.URIResolver
 */
public void setInstanceURI(String id, String srcURI) throws XFormsException {
    Element instanceElement = findElement(XFormsConstants.INSTANCE, id);

    if (instanceElement == null) {
        throw new XFormsException("instance element '" + id + "' not found");
    }

    String xformsPrefix = NamespaceCtx.getPrefix(instanceElement, NamespaceCtx.XFORMS_NS);
    instanceElement.setAttributeNS(NamespaceCtx.XFORMS_NS, xformsPrefix + ":src", srcURI);
}