Example usage for org.w3c.dom Document createElementNS

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

Introduction

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

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

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

/**
 * builds a form from a XML schema.// ww w  . j av  a 2s . co m
 *
 * @param inputURI the URI of the Schema to be used
 * @return __UNDOCUMENTED__
 * @throws FormBuilderException __UNDOCUMENTED__
 */
public Document buildForm(String inputURI) throws FormBuilderException {
    try {
        this.loadSchema(inputURI);
        buildTypeTree(schema);

        //refCounter = 0;
        counter = new HashMap();

        Document xForm = createFormTemplate(_rootTagName, _rootTagName + " Form",
                getProperty(CSS_STYLE_PROP, DEFAULT_CSS_STYLE_PROP));

        //this.buildInheritenceTree(schema);
        Element envelopeElement = xForm.getDocumentElement();

        //Element formSection = (Element) envelopeElement.getElementsByTagNameNS(CHIBA_NS, "form").item(0);
        //Element formSection =(Element) envelopeElement.getElementsByTagName("body").item(0);
        //find form element: last element created
        NodeList children = xForm.getDocumentElement().getChildNodes();
        int nb = children.getLength();
        Element formSection = (Element) children.item(nb - 1);

        Element modelSection = (Element) envelopeElement.getElementsByTagNameNS(XFORMS_NS, "model").item(0);

        //add XMLSchema if we use schema types
        if (_useSchemaTypes && modelSection != null) {
            modelSection.setAttributeNS(XFORMS_NS, this.getXFormsNSPrefix() + "schema", inputURI);
        }

        //change stylesheet
        String stylesheet = this.getStylesheet();

        if ((stylesheet != null) && !stylesheet.equals("")) {
            envelopeElement.setAttributeNS(CHIBA_NS, this.getChibaNSPrefix() + "stylesheet", stylesheet);
        }

        // TODO: Commented out because comments aren't output properly by the Transformer.
        //String comment = "This XForm was automatically generated by " + this.getClass().getName() + " on " + (new Date()) + System.getProperty("line.separator") + "    from the '" + rootElementName + "' element from the '" + schema.getSchemaTargetNS() + "' XML Schema.";
        //xForm.insertBefore(xForm.createComment(comment),envelopeElement);
        //xxx XSDNode node = findXSDNodeByName(rootElementTagName,schemaNode.getElementSet());

        //check if target namespace
        //no way to do this with XS API ? load DOM document ?
        //TODO: find a better way to find the targetNamespace
        try {
            Document domDoc = DOMUtil.parseXmlFile(inputURI, true, false);
            if (domDoc != null) {
                Element root = domDoc.getDocumentElement();
                targetNamespace = root.getAttribute("targetNamespace");
                if (targetNamespace != null && targetNamespace.equals(""))
                    targetNamespace = null;
            }
        } catch (Exception ex) {
            LOGGER.error("Schema not loaded as DOM document: " + ex.getMessage());
        }

        //if target namespace & we use the schema types: add it to form ns declarations
        if (_useSchemaTypes && targetNamespace != null && !targetNamespace.equals("")) {
            envelopeElement.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:schema", targetNamespace);
        }

        //TODO: WARNING: in Xerces 2.6.1, parameters are switched !!! (name, namespace)
        //XSElementDeclaration rootElementDecl =schema.getElementDeclaration(targetNamespace, _rootTagName);
        XSElementDeclaration rootElementDecl = schema.getElementDeclaration(_rootTagName, targetNamespace);

        if (rootElementDecl == null) {
            //DEBUG
            rootElementDecl = schema.getElementDeclaration(_rootTagName, targetNamespace);
            if (rootElementDecl != null && LOGGER.isDebugEnabled())
                LOGGER.debug("getElementDeclaration: inversed parameters OK !!!");

            throw new FormBuilderException("Invalid root element tag name [" + _rootTagName
                    + ", targetNamespace=" + targetNamespace + "]");
        }

        Element instanceElement = (Element) modelSection
                .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "instance"));
        this.setXFormsId(instanceElement);

        Element rootElement;

        if (_instanceMode == AbstractSchemaFormBuilder.INSTANCE_MODE_NONE) {
            rootElement = (Element) instanceElement.appendChild(
                    xForm.createElementNS(targetNamespace, getElementName(rootElementDecl, xForm)));

            String prefix = xmlSchemaInstancePrefix.substring(0, xmlSchemaInstancePrefix.length() - 1);
            rootElement.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:" + prefix,
                    XMLSCHEMA_INSTANCE_NAMESPACE_URI);

        } else if (_instanceMode == AbstractSchemaFormBuilder.INSTANCE_MODE_INCLUDED)
        //get the instance element
        {
            boolean ok = true;

            try {
                /*DOMResult result = new DOMResult();
                TransformerFactory trFactory =
                TransformerFactory.newInstance();
                Transformer tr = trFactory.newTransformer();
                tr.transform(_instanceSource, result);
                Document instanceDoc = (Document) result.getNode();*/
                DocumentBuilderFactory docFact = DocumentBuilderFactory.newInstance();
                docFact.setNamespaceAware(true);
                docFact.setValidating(false);
                DocumentBuilder parser = docFact.newDocumentBuilder();
                Document instanceDoc = parser.parse(new InputSource(_instanceSource.getSystemId()));

                //possibility abandonned for the moment:
                //modify the instance to add the correct "xsi:type" attributes wherever needed
                //Document instanceDoc=this.setXMLSchemaAndPSVILoad(inputURI, _instanceSource, targetNamespace);

                if (instanceDoc != null) {
                    Element instanceInOtherDoc = instanceDoc.getDocumentElement();

                    if (instanceInOtherDoc.getNodeName().equals(_rootTagName)) {
                        rootElement = (Element) xForm.importNode(instanceInOtherDoc, true);
                        instanceElement.appendChild(rootElement);

                        //add XMLSchema instance NS
                        String prefix = xmlSchemaInstancePrefix.substring(0,
                                xmlSchemaInstancePrefix.length() - 1);
                        if (!rootElement.hasAttributeNS(XMLNS_NAMESPACE_URI, prefix))
                            rootElement.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:" + prefix,
                                    XMLSCHEMA_INSTANCE_NAMESPACE_URI);

                        //possibility abandonned for the moment:
                        //modify the instance to add the correct "xsi:type" attributes wherever needed
                        //this.addXSITypeAttributes(rootElement);
                    } else {
                        ok = false;
                    }
                } else {
                    ok = false;
                }
            } catch (Exception ex) {
                ex.printStackTrace();

                //if there is an exception we put the empty root element
                ok = false;
            }

            //if there was a problem
            if (!ok) {
                rootElement = (Element) instanceElement.appendChild(xForm.createElement(_rootTagName));
            }
        } else if (_instanceMode == AbstractSchemaFormBuilder.INSTANCE_MODE_HREF)
        //add the xlink:href attribute
        {
            instanceElement.setAttributeNS(SchemaFormBuilder.XLINK_NS, this.getXLinkNSPrefix() + "href",
                    _instanceHref);
        }

        Element formContentWrapper = _wrapper.createGroupContentWrapper(formSection);
        addElement(xForm, modelSection, formContentWrapper, rootElementDecl,
                rootElementDecl.getTypeDefinition(), "/" + getElementName(rootElementDecl, xForm));

        Element submitInfoElement = (Element) modelSection
                .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "submission"));

        //submitInfoElement.setAttributeNS(XFORMS_NS,getXFormsNSPrefix()+"id","save");
        String submissionId = this.setXFormsId(submitInfoElement);

        //action
        if (_action == null) {
            submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "action", "");
        } else {
            submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "action", _action);
        }

        //method
        if ((_submitMethod != null) && !_submitMethod.equals("")) {
            submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "method", _submitMethod);
        } else { //default is "post"
            submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "method",
                    AbstractSchemaFormBuilder.SUBMIT_METHOD_POST);
        }

        //Element submitButton = (Element) formSection.appendChild(xForm.createElementNS(XFORMS_NS,getXFormsNSPrefix()+"submit"));
        Element submitButton = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "submit");
        Element submitControlWrapper = _wrapper.createControlsWrapper(submitButton);
        formContentWrapper.appendChild(submitControlWrapper);
        submitButton.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "submission", submissionId);
        this.setXFormsId(submitButton);

        Element submitButtonCaption = (Element) submitButton
                .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "label"));
        submitButtonCaption.appendChild(xForm.createTextNode("Submit"));
        this.setXFormsId(submitButtonCaption);

        return xForm;
    } catch (ParserConfigurationException x) {
        throw new FormBuilderException(x);
    } catch (java.lang.ClassNotFoundException x) {
        throw new FormBuilderException(x);
    } catch (java.lang.InstantiationException x) {
        throw new FormBuilderException(x);
    } catch (java.lang.IllegalAccessException x) {
        throw new FormBuilderException(x);
    }
}

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

/**
 * __UNDOCUMENTED__//from w  w w  .ja  va  2  s.  co m
 *
 * @param xForm          __UNDOCUMENTED__
 * @param choicesElement __UNDOCUMENTED__
 * @param choiceValues   __UNDOCUMENTED__
 */
protected void addChoicesForSelectControl(Document xForm, Element choicesElement, Vector choiceValues) {
    // sort the enums values and then add them as choices
    //
    // TODO: Should really put the default value (if any) at the top of the list.
    //
    List sortedList = choiceValues.subList(0, choiceValues.size());
    Collections.sort(sortedList);

    Iterator iterator = sortedList.iterator();

    while (iterator.hasNext()) {
        String textValue = (String) iterator.next();
        Element item = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "item");
        this.setXFormsId(item);
        choicesElement.appendChild(item);

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

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

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

protected void addChoicesForSelectSwitchControl(Document xForm, Element choicesElement, Vector choiceValues,
        HashMap case_types) {

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("addChoicesForSelectSwitchControl, values=");
        Iterator it = choiceValues.iterator();
        while (it.hasNext()) {
            //String name=(String) it.next();
            XSTypeDefinition type = (XSTypeDefinition) it.next();
            String name = type.getName();
            LOGGER.debug("  - " + name);
        }/*www . j  a v  a  2 s.  co m*/
    }

    // sort the enums values and then add them as choices
    //
    // TODO: Should really put the default value (if any) at the top of the list.
    //
    /*List sortedList = choiceValues.subList(0, choiceValues.size());
    Collections.sort(sortedList);
    Iterator iterator = sortedList.iterator();*/
    // -> no, already sorted
    Iterator iterator = choiceValues.iterator();
    while (iterator.hasNext()) {
        XSTypeDefinition type = (XSTypeDefinition) iterator.next();
        String textValue = type.getName();
        //String textValue = (String) iterator.next();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("addChoicesForSelectSwitchControl, processing " + textValue);

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

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

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

        /// action in the case

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

        action.setAttributeNS(XMLEVENTS_NS, xmleventsNSPrefix + "event", "xforms-select");

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

        //build the case element
        Element caseElement = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "case");
        String case_id = this.setXFormsId(caseElement);
        case_types.put(textValue, caseElement);

        toggle.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "case", case_id);

        //toggle.setAttributeNS(XFORMS_NS,getXFormsNSPrefix() + "case",bindIdPrefix + "_" + textValue +"_case");
        action.appendChild(toggle);
    }
}

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

/**
 * __UNDOCUMENTED__/*www  . j  ava  2s.c o m*/
 *
 * @param xForm      __UNDOCUMENTED__
 * @param annotation __UNDOCUMENTED__
 * @return __UNDOCUMENTED__
 */
protected Element addHintFromDocumentation(Document xForm, XSAnnotation annotation) {
    if (annotation != null) {
        Element hintElement = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "hint");
        this.setXFormsId(hintElement);

        Text hintText = (Text) hintElement.appendChild(xForm.createTextNode(""));

        //write annotation to empty doc
        Document doc = DOMUtil.newDocument(true, false);
        annotation.writeAnnotation(doc, XSAnnotation.W3C_DOM_DOCUMENT);

        //get "annotation" element
        NodeList annots = doc.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema", "annotation");
        if (annots.getLength() > 0) {
            Element annotEl = (Element) annots.item(0);

            //documentation
            NodeList docos = annotEl.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema",
                    "documentation");
            int nbDocos = docos.getLength();
            for (int j = 0; j < nbDocos; j++) {
                Element doco = (Element) docos.item(j);

                //get text value
                String text = DOMUtil.getTextNodeAsString(doco);
                hintText.appendData(text);

                if (j < nbDocos - 1) {
                    hintText.appendData(" ");
                }
            }
            return hintElement;
        }
        return null;
    }

    return null;
}

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 va2  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.
 *//*w  w w  . j  av  a2s .  c  om*/
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
 *///from  ww  w. j av a  2s.co  m
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 .  ja va  2 s . 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.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
    ////from  w w  w  . j a  v a 2  s. com
    // 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.pentaho.osgi.platform.plugin.deployer.impl.handlers.pluginxml.PluginXmlExternalResourcesHandlerTest.java

@Test
public void testHandleTwoNodes() throws PluginHandlingException, IOException {
    Map<String, String> node1Props = new HashMap<String, String>();
    node1Props.put("context", "requirejs");
    Map<String, String> node2Props = new HashMap<String, String>();
    node2Props.put("context", "requirejs");
    Node node1 = PluginXmlStaticPathsHandlerTest.makeMockNode(node1Props);
    when(node1.getTextContent()).thenReturn("/test/content/1");
    Node node2 = PluginXmlStaticPathsHandlerTest.makeMockNode(node2Props);
    when(node2.getTextContent()).thenReturn("/test/content/2");
    PluginXmlExternalResourcesHandler pluginXmlExternalResourcesHandler = new PluginXmlExternalResourcesHandler();
    pluginXmlExternalResourcesHandler.setJsonUtil(new JSONUtil());
    PluginMetadata pluginMetadata = mock(PluginMetadata.class);
    FileWriter fileWriter = mock(FileWriter.class);
    final StringBuilder sb = new StringBuilder();
    doAnswer(new Answer<Object>() {
        @Override// ww w . j  ava2 s .  c o m
        public Object answer(InvocationOnMock invocation) throws Throwable {
            sb.append(invocation.getArguments()[0]);
            return null;
        }
    }).when(fileWriter).write(anyString());
    when(pluginMetadata.getFileWriter(PluginXmlExternalResourcesHandler.EXTERNAL_RESOURCES_FILE))
            .thenReturn(fileWriter);

    // Setup Blueprint
    Document blueprint = null;
    try {
        blueprint = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        blueprint.appendChild(
                blueprint.createElementNS(PluginXmlStaticPathsHandler.BLUEPRINT_BEAN_NS, "blueprint"));
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        fail();
    }
    when(pluginMetadata.getBlueprint()).thenReturn(blueprint);

    List<Node> nodes = new ArrayList<Node>(Arrays.asList(node1, node2));
    pluginXmlExternalResourcesHandler.handle("plugin.xml", nodes, pluginMetadata);
    String result = sb.toString();
    JSONObject jsonObject = (JSONObject) JSONValue.parse(result);
    assertEquals(1, jsonObject.size());
    List<String> configs = (List<String>) jsonObject.get("requirejs");
    assertNotNull(configs);
    assertEquals(2, configs.size());
    assertEquals("/test/content/1", configs.get(0));
    assertEquals("/test/content/2", configs.get(1));

    NodeList childNodes = blueprint.getDocumentElement().getChildNodes();
    assertEquals(2, childNodes.getLength());
    for (int i = 0; i < childNodes.getLength(); i++) {
        assertEquals("service", childNodes.item(i).getNodeName());
        assertEquals("org.pentaho.platform.pdi.PlatformWebResource",
                childNodes.item(i).getFirstChild().getAttributes().getNamedItem("class").getNodeValue());
    }
}