Example usage for org.w3c.dom Element getAttributeNS

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

Introduction

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

Prototype

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

Source Link

Document

Retrieves an attribute value by local name and namespace URI.

Usage

From source file:com.codename1.android.AndroidLayoutImporter.java

protected void convertElement(Element inputSrcElement, Element out) throws UnsupportedElementException {
    String id = inputSrcElement.getAttributeNS(NS_ANDROID, "id");
    if (id != null) {
        id = id.substring(id.indexOf("/") + 1);
        out.setAttribute("name", id.replaceAll("[^a-zA-Z0-9]", ""));
    }//from   ww  w. ja v a  2s . c  o  m

    //out.setAttribute("uiid", "android."+inputSrcElement.getTagName());
    out.setAttribute("type", "Container");
    out.setAttribute("layout", "FlowLayout");

    Node inputParentNode = inputSrcElement.getParentNode();
    if (inputParentNode != null && inputParentNode instanceof Element) {
        Element inputParent = (Element) inputParentNode;
        if ("FrameLayout".equals(inputParent.getTagName())) {
            out.setAttribute("layout", "BorderLayout");
            String gravity = inputSrcElement.getAttributeNS(NS_ANDROID, "layout_gravity");
            String layoutConstraint = "CENTER";
            switch (gravity) {
            case "top":
                layoutConstraint = "NORTH";
                break;
            case "left":
                layoutConstraint = "WEST";
                break;
            case "right":
                layoutConstraint = "EAST";
                break;
            case "bottom":
                layoutConstraint = "SOUTH";
                break;
            case "fill_vertical":
            case "center_vertical":
            case "center_horizontal":
            case "fill_horizontal":
            case "center":
            case "fill":

                layoutConstraint = "CENTER";
                break;
            default:
                layoutConstraint = "CENTER";
            }
            Element layoutConstraintEl = out.getOwnerDocument().createElement("layoutConstraint");
            layoutConstraintEl.setAttribute("value", layoutConstraint);
            out.appendChild(layoutConstraintEl);
        }
    }

    switch (inputSrcElement.getTagName()) {
    case "LinearLayout":
        convertLinearLayout(inputSrcElement, out);
        break;

    case "android.support.v7.widget.RecyclerView":
        convertRecyclerView(inputSrcElement, out);
        break;

    case "FrameLayout":
        convertFrameLayout(inputSrcElement, out);
        break;

    case "android.support.design.widget.CoordinatorLayout":
        convertCoordinatorLayout(inputSrcElement, out);
        break;

    case "android.support.design.widget.CollapsingToolbarLayout":
        convertCollapsingToolbarLayout(inputSrcElement, out);
        break;

    case "android.support.design.widget.AppBarLayout":
        convertAppBarLayout(inputSrcElement, out);
        break;

    case "android.support.v7.widget.Toolbar":
        convertToolbar(inputSrcElement, out);
        break;

    case "android.support.design.widget.FloatingActionButton":
        convertFloatingActionButton(inputSrcElement, out);
        break;

    case "include": {
        try {
            convertInclude(inputSrcElement, out);
        } catch (IOException ex) {
            Logger.getLogger(AndroidLayoutImporter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(AndroidLayoutImporter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(AndroidLayoutImporter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
        break;

    case "android.support.v4.widget.NestedScrollView":
        convertNestedScrollView(inputSrcElement, out);
        break;

    case "ListView":
        convertListView(inputSrcElement, out);
        break;

    case "ProgressBar":
        convertProgressBar(inputSrcElement, out);
        break;

    case "TextView":
        convertTextView(inputSrcElement, out);
        break;

    case "Button":
        convertButton(inputSrcElement, out);
        break;

    case "ScrollView":
        convertScrollView(inputSrcElement, out);
        break;

    case "EditText":
        convertEditText(inputSrcElement, out);
        break;

    case "CheckBox":
        convertCheckBox(inputSrcElement, out);
        break;

    case "View":
        convertView(inputSrcElement, out);
        break;

    case "merge":
        convertMerge(inputSrcElement, out);
        break;

    case "RadioGroup":
        convertRadioGroup(inputSrcElement, out);
        break;

    case "RadioButton":
        convertRadioButton(inputSrcElement, out);
        break;

    case "Spinner":
        convertSpinner(inputSrcElement, out);
        break;

    case "RelativeLayout":
        convertRelativeLayout(inputSrcElement, out);
        break;

    case "ImageButton":
        convertImageButton(inputSrcElement, out);
        break;

    case "ImageView":
        convertImageView(inputSrcElement, out);
        break;

    case "SeekBar":
        convertSeekBar(inputSrcElement, out);
        break;

    case "QuickContactBadge":
        convertQuickContactBadge(inputSrcElement, out);
        break;

    case "ViewAnimator":
        convertViewAnimator(inputSrcElement, out);
        break;

    case "ViewStub":
        convertViewStub(inputSrcElement, out);
        break;

    case "Space":
        convertSpace(inputSrcElement, out);
        break;

    default:
        if (suppressUnsupportedElementExceptions) {
            this.convertOther(inputSrcElement, out);
        } else {
            throw new UnsupportedElementException(inputSrcElement);
        }

    }

    convertChildren(inputSrcElement, out);

    if (out.hasAttribute("layout") && "BorderLayout".equals(out.getAttribute("layout"))) {
        // Make sure that border layout children have appropriate constraint
        Set<String> allowable = new HashSet<String>(
                Arrays.asList(new String[] { "NORTH", "SOUTH", "EAST", "WEST", "CENTER" }));
        Map<String, Element> childMap = new HashMap<String, Element>();
        List<ElementConstraint> childList = getBorderLayoutChildren(out);
        Set<ElementConstraint> used = new HashSet<ElementConstraint>();
        for (ElementConstraint ec : childList) {
            if (ec.constraint != null && allowable.contains(ec.constraint)
                    && !childMap.containsKey(ec.constraint)) {
                childMap.put(ec.constraint, ec.el);
                used.add(ec);
            }
        }

        childList.removeAll(used);

        if (!childList.isEmpty()) {
            // We weren't able to place all of the elements in the border layout
            // this is either because we filled all of the slots, or there were two
            // in some slots

            // Let's simplify things for now by just adding all of the extras in a 
            // BoxLayout.Y inside the CENTER
            Element center = out.getOwnerDocument().createElement("component");
            center.setAttribute("type", "Container");
            applyBoxLayoutX(center);
            Element centerConstraint = out.getOwnerDocument().createElement("layoutConstraint");
            centerConstraint.setAttribute("value", "CENTER");
            center.appendChild(centerConstraint);
            if (childMap.containsKey("CENTER")) {
                //System.out.println("Removing center from "+childMap);
                out.removeChild(childMap.get("CENTER"));
                center.appendChild(childMap.get("CENTER"));
            }

            for (ElementConstraint ec : childList) {
                removeLayoutConstraint(ec.el);

                out.removeChild(ec.el);
                center.appendChild(ec.el);
            }
            out.appendChild(center);

        }
    } else if (out.hasAttribute("layout")) {
        // Not a boxlayout.
        NodeList children = out.getChildNodes();
        int len = children.getLength();
        for (int i = 0; i < len; i++) {
            Node n = children.item(i);
            if (n instanceof Element) {
                removeLayoutConstraint((Element) n);
            }
        }
    }

    applyStyles(inputSrcElement, out);
}

From source file:com.codename1.android.AndroidLayoutImporter.java

private void convertLinearLayout(Element inputEl, Element outputEl) {
    outputEl.setAttribute("type", "Container");
    String orientation = inputEl.getAttributeNS(NS_ANDROID, "orientation");
    outputEl.setAttribute("layout", "BoxLayout");
    if (orientation.equals("vertical")) {
        outputEl.setAttribute("boxLayoutAxis", "Y");
    } else {/*from  ww w .j  a  va 2s  . c o m*/
        outputEl.setAttribute("boxLayoutAxis", "X");
    }

}

From source file:org.adeptnet.auth.saml.SAMLClient.java

private void initMap() {
    if (!map.isEmpty()) {
        return;/*from   ww  w . j a  va2  s .  c om*/
    }
    final InputStream is = org.apache.xml.security.Init.class.getResourceAsStream("resource/config.xml");
    if (is == null) {
        LOG.error("cannot read resource/config.xml");
        return;
    }
    try {
        /* read library configuration file */
        final DocumentBuilder db = createDocumentBuilder(false, true);
        final Document doc = db.parse(is);
        Node node = doc.getFirstChild();
        for (; node != null; node = node.getNextSibling()) {
            if ("Configuration".equals(node.getLocalName())) {
                break;
            }
        }
        if (node == null) {
            LOG.error("Error in reading configuration file - Configuration element not found");
            return;
        }
        for (Node el = node.getFirstChild(); el != null; el = el.getNextSibling()) {
            if (Node.ELEMENT_NODE != el.getNodeType()) {
                continue;
            }
            if (!"JCEAlgorithmMappings".equals(el.getLocalName())) {
                continue;
            }
            final Node algorithmsNode = ((Element) el).getElementsByTagName("Algorithms").item(0);
            if (algorithmsNode == null) {
                continue;
            }

            final Element[] algorithms = selectNodes(algorithmsNode.getFirstChild(), Init.CONF_NS, "Algorithm");
            for (final Element element : algorithms) {
                final String algoClass = element.getAttributeNS(null, "AlgorithmClass");
                if (!"Signature".equals(algoClass)) {
                    continue;
                }
                final String uri = element.getAttributeNS(null, "URI");
                final String name = element.getAttributeNS(null, "JCEName");
                map.put(name, uri);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(String.format("Mapping %s - %s", name, uri));
                }
            }
        }
    } catch (ParserConfigurationException | SAXException | IOException | DOMException ex) {
        LOG.error(ex.getMessage(), ex);
    }
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

@SuppressWarnings("unchecked")
public static void rebuildInstance(final Node prototypeNode, final Node oldInstanceNode,
        final Node newInstanceNode,

        final HashMap<String, String> schemaNamespaces) {
    final JXPathContext prototypeContext = JXPathContext.newContext(prototypeNode);
    prototypeContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);
    final JXPathContext instanceContext = JXPathContext.newContext(oldInstanceNode);
    instanceContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);

    for (final String prefix : schemaNamespaces.keySet()) {
        prototypeContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
        instanceContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
    }/*w w  w.  j a  v  a 2  s.  co m*/

    // Evaluate non-recursive XPaths for all prototype elements at this level
    final Iterator<Pointer> it = prototypeContext.iteratePointers("*");
    while (it.hasNext()) {
        final Pointer p = it.next();
        Element proto = (Element) p.getNode();
        String path = p.asPath();
        // check if this is a prototype element with the attribute set
        boolean isPrototype = proto.hasAttributeNS(NamespaceService.ALFRESCO_URI, "prototype")
                && proto.getAttributeNS(NamespaceService.ALFRESCO_URI, "prototype").equals("true");

        // We shouldn't locate a repeatable child with a fixed path
        if (isPrototype) {
            path = path.replaceAll("\\[(\\d+)\\]", "[position() >= $1]");
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating prototyped nodes " + path);
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating child node with positional path " + path);
            }
        }

        Document newInstanceDocument = newInstanceNode.getOwnerDocument();

        // Locate the corresponding nodes in the instance document
        List<Node> l = (List<Node>) instanceContext.selectNodes(path);

        // If the prototype node isn't a prototype element, copy it in as a missing node, complete with all its children. We won't need to recurse on this node
        if (l.isEmpty()) {
            if (!isPrototype) {
                LOGGER.debug("[rebuildInstance] copying in missing node " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));

                // Clone the prototype node and all its children
                Element clone = (Element) proto.cloneNode(true);
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }
            }
        } else {
            // Otherwise, append the matches from the old instance document in order
            for (Node old : l) {
                Element oldEl = (Element) old;

                // Copy the old instance element rather than cloning it, so we don't copy over attributes
                Element clone = null;
                String nSUri = oldEl.getNamespaceURI();
                if (nSUri == null) {
                    clone = newInstanceDocument.createElement(oldEl.getTagName());
                } else {
                    clone = newInstanceDocument.createElementNS(nSUri, oldEl.getTagName());
                }
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }

                // Copy over child text if this is not a complex type
                boolean isEmpty = true;
                for (Node n = old.getFirstChild(); n != null; n = n.getNextSibling()) {
                    if (n instanceof Text) {
                        clone.appendChild(newInstanceDocument.importNode(n, false));
                        isEmpty = false;
                    } else if (n instanceof Element) {
                        break;
                    }
                }

                // Populate the nil attribute. It may be true or false
                if (proto.hasAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, "nil")) {
                    clone.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":nil", String.valueOf(isEmpty));
                }

                // Copy over attributes present in the prototype
                NamedNodeMap attributes = proto.getAttributes();
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attribute = (Attr) attributes.item(i);
                    String localName = attribute.getLocalName();
                    if (localName == null) {
                        String name = attribute.getName();
                        if (oldEl.hasAttribute(name)) {
                            clone.setAttributeNode(
                                    (Attr) newInstanceDocument.importNode(oldEl.getAttributeNode(name), false));
                        } else {
                            LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                    + attribute.getNodeName() + " to "
                                    + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                            clone.setAttributeNode((Attr) attribute.cloneNode(false));
                        }
                    } else {
                        String namespace = attribute.getNamespaceURI();
                        if (!((!isEmpty
                                && (namespace.equals(NamespaceConstants.XMLSCHEMA_INSTANCE_NS)
                                        && localName.equals("nil"))
                                || (namespace.equals(NamespaceService.ALFRESCO_URI)
                                        && localName.equals("prototype"))))) {
                            if (oldEl.hasAttributeNS(namespace, localName)) {
                                clone.setAttributeNodeNS((Attr) newInstanceDocument
                                        .importNode(oldEl.getAttributeNodeNS(namespace, localName), false));
                            } else {
                                LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                        + attribute.getNodeName() + " to "
                                        + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                                clone.setAttributeNodeNS((Attr) attribute.cloneNode(false));
                            }
                        }
                    }
                }

                // recurse on children
                rebuildInstance(proto, oldEl, clone, schemaNamespaces);
            }
        }

        // Now add in a new copy of the prototype
        if (isPrototype) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] appending " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));
            }
            newInstanceNode.appendChild(proto.cloneNode(true));
        }
    }
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

public static void removePrototypeNodes(final Node instanceDocumentElement) {
    final Map<String, LinkedList<Element>> prototypes = new HashMap<String, LinkedList<Element>>();
    final NodeList children = instanceDocumentElement.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        if (!(children.item(i) instanceof Element)) {
            continue;
        }/*from  www.j  a v a  2s.  c om*/
        final String nodeName = children.item(i).getNodeName();
        if (!prototypes.containsKey(nodeName)) {
            prototypes.put(nodeName, new LinkedList<Element>());
        }
        prototypes.get(nodeName).add((Element) children.item(i));
    }

    for (LinkedList<Element> l : prototypes.values()) {
        for (Element e : l) {
            if (e.hasAttributeNS(NamespaceService.ALFRESCO_URI, "prototype")) {
                assert "true".equals(e.getAttributeNS(NamespaceService.ALFRESCO_URI, "prototype"));
                e.removeAttributeNS(NamespaceService.ALFRESCO_URI, "prototype");

                if (l.getLast().equals(e)) {
                    e.getParentNode().removeChild(e);
                }
            }
            if (e.getParentNode() != null) {
                Schema2XForms.removePrototypeNodes(e);
            }
        }
    }
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

private void addAttributeSet(final Document xformsDocument, final Element modelSection,
        final Element defaultInstanceElement, final Element formSection, final XSModel schema,
        final XSComplexTypeDefinition controlType, final XSElementDeclaration owner, final String pathToRoot,
        final boolean checkIfExtension, final ResourceBundle resourceBundle) throws FormBuilderException {
    XSObjectList attrUses = controlType.getAttributeUses();

    if (attrUses == null) {
        return;/*from   w  w  w. j a va2 s  . c  o m*/
    }
    for (int i = 0; i < attrUses.getLength(); i++) {
        final XSAttributeUse currentAttributeUse = (XSAttributeUse) attrUses.item(i);
        final XSAttributeDeclaration currentAttribute = currentAttributeUse.getAttrDeclaration();

        String attributeName = currentAttributeUse.getName();
        if (attributeName == null || attributeName.length() == 0) {
            attributeName = currentAttributeUse.getAttrDeclaration().getName();
        }

        //test if extended !
        if (checkIfExtension && SchemaUtil.doesAttributeComeFromExtension(currentAttributeUse, controlType)) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(
                        "[addAttributeSet] This attribute comes from an extension: recopy form controls. Model section =\n"
                                + XMLUtil.toString(modelSection));
            }

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

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

                JXPathContext context = JXPathContext.newContext(formSection.getOwnerDocument());
                final Pointer pointer = context
                        .getPointer("//*[@" + NamespaceConstants.XFORMS_PREFIX + ":bind='" + bindId + "']");
                if (pointer != null) {
                    control = (Element) pointer.getNode();
                } else if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("[addAttributeSet] unable to resolve pointer for: //*[@"
                            + NamespaceConstants.XFORMS_PREFIX + ":bind='" + bindId + "']");
                }
            }

            if (LOGGER.isDebugEnabled()) {
                if (control == null) {
                    LOGGER.debug("[addAttributeSet] control = <not found>");
                } else {
                    LOGGER.debug("[addAttributeSet] control = " + control.getTagName());
                }
            }

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

                formSection.appendChild(newControl);
            }
        } else {
            String attrNamespace = currentAttribute.getNamespace();
            String namespacePrefix = "";
            if (attrNamespace != null && attrNamespace.length() > 0) {
                String prefix = NamespaceResolver.getPrefix(xformsDocument.getDocumentElement(), attrNamespace);
                if (prefix != null && prefix.length() > 0) {
                    namespacePrefix = prefix + ":";
                }
            }

            final String newPathToRoot = (pathToRoot == null || pathToRoot.length() == 0
                    ? "@" + namespacePrefix + currentAttribute.getName()
                    : (pathToRoot.endsWith("/")
                            ? pathToRoot + "@" + namespacePrefix + currentAttribute.getName()
                            : pathToRoot + "/@" + namespacePrefix + currentAttribute.getName()));

            if (LOGGER.isDebugEnabled())
                LOGGER.debug("[addAttributeSet] adding attribute " + attributeName + " at " + newPathToRoot);

            try {
                String defaultValue = (currentAttributeUse.getConstraintType() == XSConstants.VC_NONE ? null
                        : currentAttributeUse.getConstraintValue());
                // make sure boolean attributes have a default value
                if (defaultValue == null && "boolean".equals(currentAttribute.getTypeDefinition().getName())) {
                    defaultValue = "false";
                }

                if (namespacePrefix.length() > 0) {
                    defaultInstanceElement.setAttributeNS(this.targetNamespace, attributeName, defaultValue);
                } else {
                    defaultInstanceElement.setAttribute(attributeName, defaultValue);
                }
            } catch (Exception e) {
                throw new FormBuilderException("error retrieving default value for attribute " + attributeName
                        + " at " + newPathToRoot, e);
            }
            this.addSimpleType(xformsDocument, modelSection, formSection, schema,
                    currentAttribute.getTypeDefinition(), currentAttributeUse, newPathToRoot, resourceBundle);
        }
    }
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

private Element addElementWithMultipleCompatibleTypes(final Document xformsDocument, Element modelSection,
        final Element defaultInstanceElement, final Element formSection, final XSModel schema,
        final XSElementDeclaration elementDecl, final TreeSet<XSTypeDefinition> compatibleTypes,
        final String pathToRoot, final ResourceBundle resourceBundle, final SchemaUtil.Occurrence occurs)
        throws FormBuilderException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("[addElementWithMultipleCompatibleTypes] adding element " + elementDecl + " at path "
                + pathToRoot);//www  . j  av a  2s  .  com

    // look for compatible types
    final XSTypeDefinition controlType = elementDecl.getTypeDefinition();

    //get possible values
    final List<XSTypeDefinition> enumValues = new LinkedList<XSTypeDefinition>();
    //add the type (if not abstract)
    if (!((XSComplexTypeDefinition) controlType).getAbstract()) {
        enumValues.add(controlType);
    }

    //add compatible types
    enumValues.addAll(compatibleTypes);

    // multiple compatible types for this element exist
    // in the schema - allow the user to choose from
    // between compatible non-abstract types
    boolean isRepeated = isRepeated(occurs, controlType);
    Element bindElement = this.createBind(xformsDocument, pathToRoot + "/@xsi:type");
    String bindId = bindElement.getAttributeNS(null, "id");
    modelSection.appendChild(bindElement);
    this.startBindElement(bindElement, schema, controlType, null, occurs);

    //add the "element" bind, in addition
    final Element bindElement2 = this.createBind(xformsDocument,
            pathToRoot + (isRepeated ? "[position() != last()]" : ""));
    modelSection.appendChild(bindElement2);
    this.startBindElement(bindElement2, schema, controlType, null, occurs);

    // add content to select1
    final Map<String, Element> caseTypes = this.addChoicesForSelectSwitchControl(xformsDocument, formSection,
            enumValues, bindId);

    //add switch
    final Element switchElement = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
            NamespaceConstants.XFORMS_PREFIX + ":switch");
    switchElement.setAttributeNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":bind",
            bindId);
    switchElement.setAttributeNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":appearance",
            "full");

    formSection.appendChild(switchElement);

    if (!((XSComplexTypeDefinition) controlType).getAbstract()) {
        final Element firstCaseElement = caseTypes.get(controlType.getName());
        switchElement.appendChild(firstCaseElement);
        final Element firstGroupElement = this.addComplexType(xformsDocument, modelSection,
                defaultInstanceElement, firstCaseElement, schema, (XSComplexTypeDefinition) controlType,
                elementDecl, pathToRoot, SchemaUtil.getOccurrence(elementDecl), true, false, resourceBundle);
        firstGroupElement.setAttributeNS(NamespaceConstants.XFORMS_NS,
                NamespaceConstants.XFORMS_PREFIX + ":appearance", "");
    }

    defaultInstanceElement.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS,
            NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":type",
            (((XSComplexTypeDefinition) controlType).getAbstract() ? compatibleTypes.first().getName()
                    : controlType.getName()));
    defaultInstanceElement.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS,
            NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":nil", "true");

    /////////////// add sub types //////////////
    // add each compatible type within
    // a case statement
    for (final XSTypeDefinition type : compatibleTypes) {
        final String compatibleTypeName = type.getName();

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(type == null
                    ? ("[addElementWithMultipleCompatibleTypes] compatible type is null!! type = "
                            + compatibleTypeName + ", targetNamespace = " + this.targetNamespace)
                    : ("[addElementWithMultipleCompatibleTypes] adding compatible type " + type.getName()));
        }

        if (type == null || type.getTypeCategory() != XSTypeDefinition.COMPLEX_TYPE) {
            continue;
        }

        final Element caseElement = caseTypes.get(type.getName());
        switchElement.appendChild(caseElement);

        // ALF-9524 fix, add an extra element to the instance for each type that extends the abstract parent
        Element newDefaultInstanceElement = xformsDocument.createElement(getElementName(type, xformsDocument));

        Attr nodesetAttr = modelSection.getAttributeNodeNS(NamespaceConstants.XFORMS_NS, "nodeset");
        // construct the nodeset that is used in bind for abstract type
        String desiredBindNodeset = getElementName(elementDecl, xformsDocument)
                + (isRepeated ? "[position() != last()]" : "");

        // check the current bind
        if (nodesetAttr == null || !nodesetAttr.getValue().equals(desiredBindNodeset)) {
            // look for desired bind in children
            Element newModelSection = DOMUtil.getElementByAttributeValueNS(modelSection,
                    NamespaceConstants.XFORMS_NS, "bind", NamespaceConstants.XFORMS_NS, "nodeset",
                    desiredBindNodeset);

            if (newModelSection == null) {
                // look for absolute path
                desiredBindNodeset = "/" + desiredBindNodeset;
                newModelSection = DOMUtil.getElementByAttributeValueNS(modelSection,
                        NamespaceConstants.XFORMS_NS, "bind", NamespaceConstants.XFORMS_NS, "nodeset",
                        desiredBindNodeset);
            }

            modelSection = newModelSection;
        }

        // create the extra bind for each child of abstract type
        Element bindElement3 = this.createBind(xformsDocument, getElementName(type, xformsDocument));
        modelSection.appendChild(bindElement3);
        bindElement3 = this.startBindElement(bindElement3, schema, controlType, elementDecl, occurs);

        // add the relevant attribute that checks the value of parent' @xsi:type
        bindElement3.setAttributeNS(NamespaceConstants.XFORMS_NS,
                NamespaceConstants.XFORMS_PREFIX + ":relevant", "../@xsi:type='" + type.getName() + "'");

        final Element groupElement = this.addComplexType(xformsDocument, modelSection,
                newDefaultInstanceElement, caseElement, schema, (XSComplexTypeDefinition) type, elementDecl,
                pathToRoot, SchemaUtil.getOccurrence(elementDecl), true, true, resourceBundle);
        groupElement.setAttributeNS(NamespaceConstants.XFORMS_NS,
                NamespaceConstants.XFORMS_PREFIX + ":appearance", "");

        defaultInstanceElement.appendChild(newDefaultInstanceElement.cloneNode(true));

        // modify bind to add a "relevant" attribute that checks the value of @xsi:type
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[addElementWithMultipleCompatibleTypes] Model section =\n"
                    + XMLUtil.toString(bindElement3));
        }

        final NodeList binds = bindElement3.getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "bind");
        for (int i = 0; i < binds.getLength(); i++) {
            final Element subBind = (Element) binds.item(i);
            String name = subBind.getAttributeNS(NamespaceConstants.XFORMS_NS, "nodeset");

            // ETHREEOH-3308 fix
            name = repeatableNamePattern.matcher(name).replaceAll("");

            if (!subBind.getParentNode().getAttributes().getNamedItem("id").getNodeValue()
                    .equals(bindElement3.getAttribute("id"))) {
                continue;
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[addElementWithMultipleCompatibleTypes] Testing sub-bind with nodeset " + name);
            }

            Pair<String, String> parsed = parseName(name, xformsDocument);

            if (!SchemaUtil.isElementDeclaredIn(parsed.getFirst(), parsed.getSecond(),
                    (XSComplexTypeDefinition) type, false)
                    && !SchemaUtil.isAttributeDeclaredIn(parsed.getFirst(), parsed.getSecond(),
                            (XSComplexTypeDefinition) type, false)) {
                continue;
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[addElementWithMultipleCompatibleTypes] Element/Attribute " + name
                        + " declared in type " + type.getName() + ": adding relevant attribute");
            }

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

            String newRelevant = "../../@xsi:type='" + type.getName() + "'";
            if (this.typeTree.containsKey(type.getName())) {
                for (XSTypeDefinition otherType : this.typeTree.get(type.getName())) {
                    newRelevant = newRelevant + " or ../../@xsi:type='" + otherType.getName() + "'";
                }
            }

            //change relevant attribute
            final String relevant = subBind.getAttributeNS(NamespaceConstants.XFORMS_NS, "relevant");
            if (relevant != null && relevant.length() != 0) {
                newRelevant = ("(" + relevant + ") and " + newRelevant);
            }
            subBind.setAttributeNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":relevant",
                    newRelevant);
        }
    }
    return switchElement;
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

/**
 *//* w w  w. jav a2  s  .  c  o m*/
private void addGroup(final Document xformsDocument, final Element modelSection,
        final Element defaultInstanceElement, final Element formSection, final XSModel schema,
        final XSModelGroup group, final XSComplexTypeDefinition controlType, final XSElementDeclaration owner,
        final String pathToRoot, final SchemaUtil.Occurrence occurs, final boolean checkIfExtension,
        final ResourceBundle resourceBundle) throws FormBuilderException {
    if (group == null) {
        return;
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("[addGroup] Start of addGroup, from owner = " + owner.getName() + " and controlType = "
                + controlType.getName());
        LOGGER.debug("[addGroup] group before =\n" + XMLUtil.toString(formSection));
    }

    final Element repeatSection = this.addRepeatIfNecessary(xformsDocument, modelSection, formSection,
            owner.getTypeDefinition(), pathToRoot, occurs);

    final XSObjectList particles = group.getParticles();
    for (int counter = 0; counter < particles.getLength(); counter++) {
        final XSParticle currentNode = (XSParticle) particles.item(counter);
        XSTerm term = currentNode.getTerm();
        final SchemaUtil.Occurrence childOccurs = new SchemaUtil.Occurrence(currentNode);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[addGroup] next term = " + term.getName() + ", occurs = " + childOccurs);
        }

        if (term instanceof XSModelGroup) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[addGroup] term is a group");
            }

            this.addGroup(xformsDocument, modelSection, defaultInstanceElement, repeatSection, schema,
                    ((XSModelGroup) term), controlType, owner, pathToRoot, childOccurs, checkIfExtension,
                    resourceBundle);
        } else if (term instanceof XSElementDeclaration) {
            XSElementDeclaration element = (XSElementDeclaration) term;

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[addGroup] term is an element declaration: " + term.getName());
            }

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

                //find the existing bind Id
                //(modelSection is the enclosing bind of the element)
                NodeList binds = modelSection.getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "bind");
                String bindId = null;
                for (int i = 0; i < binds.getLength() && bindId == null; i++) {
                    Element bind = (Element) binds.item(i);
                    String nodeset = bind.getAttributeNS(NamespaceConstants.XFORMS_NS, "nodeset");

                    Pair<String, String> parsed = parseName(nodeset, xformsDocument);

                    if (nodeset != null
                            && EqualsHelper.nullSafeEquals(parsed.getSecond(), element.getNamespace())
                            && parsed.getFirst().equals(element.getName())) {
                        bindId = bind.getAttributeNS(null, "id");
                    }
                }

                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("[addGroup] found bindId " + bindId + " for element " + element.getName());

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

                    final JXPathContext context = JXPathContext.newContext(formSection.getOwnerDocument());
                    final Pointer pointer = context
                            .getPointer("//*[@" + NamespaceConstants.XFORMS_PREFIX + ":bind='" + bindId + "']");
                    if (pointer != null) {
                        control = (Element) pointer.getNode();
                    } else if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("[addGroup] unable to resolve pointer for: //*[@"
                                + NamespaceConstants.XFORMS_PREFIX + ":bind='" + bindId + "']");
                    }
                }

                if (LOGGER.isDebugEnabled()) {
                    if (control == null) {
                        LOGGER.debug("[addGroup] control = <not found>");
                    } else {
                        LOGGER.debug("[addGroup] control = " + control.getTagName());
                    }
                }

                //copy it
                if (control == null) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("Corresponding control not found");

                    this.addElementToGroup(xformsDocument, modelSection, defaultInstanceElement, repeatSection,
                            schema, element, pathToRoot, childOccurs, resourceBundle);
                } else {
                    Element newControl = (Element) control.cloneNode(true);
                    //set new Ids to XForm elements
                    this.resetXFormIds(newControl);

                    repeatSection.appendChild(newControl);
                }
            } else {
                this.addElementToGroup(xformsDocument, modelSection, defaultInstanceElement, repeatSection,
                        schema, element, pathToRoot, childOccurs, resourceBundle);
            }
        } else {
            LOGGER.warn("Unhandled term " + term + " found in group from " + owner.getName()
                    + " for pathToRoot = " + pathToRoot);
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("[addGroup] group after =\n" + XMLUtil.toString(formSection));
        LOGGER.debug("[addGroup] End of addGroup, from owner = " + owner.getName() + " and controlType = "
                + controlType.getName());
    }
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

/**
 * Add a repeat section if maxOccurs > 1.
 *///  ww w .  j  av  a  2  s  .c  om
private Element addRepeatIfNecessary(final Document xformsDocument, final Element modelSection,
        final Element formSection, final XSTypeDefinition controlType, final String pathToRoot,
        final SchemaUtil.Occurrence o) {

    // add xforms:repeat section if this element re-occurs
    if ((o.isOptional()
            && (controlType instanceof XSSimpleTypeDefinition || "anyType".equals(controlType.getName())))
            || (o.maximum == 1 && o.minimum == 1)
            || (controlType instanceof XSComplexTypeDefinition && pathToRoot.equals(""))) {
        return formSection;
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("[addRepeatIfNecessary] for multiple element for type " + controlType.getName()
                + ", maxOccurs = " + o.maximum);
    }

    final Element repeatSection = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
            NamespaceConstants.XFORMS_PREFIX + ":repeat");

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

    // ALF-9524 fix, previously we've added extra bind element, so last child is not correct for repeatable switch
    String attribute = bind.getAttribute(NamespaceConstants.XFORMS_PREFIX + ":relevant");
    if (controlType instanceof XSComplexTypeDefinition
            && ((XSComplexTypeDefinition) controlType).getDerivationMethod() == XSConstants.DERIVATION_EXTENSION
            && attribute != null && !attribute.isEmpty()) {
        bind = modelSection;
    }

    String bindId = null;

    if (bind != null && bind.getLocalName() != null && "bind".equals(bind.getLocalName())) {
        bindId = bind.getAttributeNS(null, "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".equals(bind.getLocalName())) {
            bindId = bind.getAttributeNS(null, "id");
        } else {
            LOGGER.warn("[addRepeatIfNecessary] bind really not found");
        }
    }

    repeatSection.setAttributeNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":bind",
            bindId);
    this.setXFormsId(repeatSection);

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

    formSection.appendChild(repeatSection);

    //add a group inside the repeat?
    final Element group = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
            NamespaceConstants.XFORMS_PREFIX + ":group");
    group.setAttributeNS(NamespaceConstants.XFORMS_NS, NamespaceConstants.XFORMS_PREFIX + ":appearance",
            "repeated");
    this.setXFormsId(group);
    repeatSection.appendChild(group);
    return group;
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

/**
 *///from   www.j av  a  2s.  c  om
private Element addSimpleType(final Document xformsDocument, final Element modelSection, Element formSection,
        final XSModel schema, final XSTypeDefinition controlType, final String owningElementName,
        final XSObject owner, final String pathToRoot, final SchemaUtil.Occurrence occurs,
        final ResourceBundle resourceBundle) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("[addSimpleType] for " + controlType.getName() + " (owningElementName = "
                + owningElementName + ")," + " occurs = [" + occurs + "]");
        if (owner != null) {
            LOGGER.debug("[addSimpleType] owner is " + owner.getClass() + ", name is " + owner.getName());
        }
    }

    // create the <xforms:bind> element and add it to the model.
    boolean isRepeated = isRepeated(occurs, controlType);
    Element bindElement = this.createBind(xformsDocument,
            pathToRoot + (isRepeated ? "[position() != last()]" : ""));
    String bindId = bindElement.getAttributeNS(null, "id");
    modelSection.appendChild(bindElement);
    bindElement = this.startBindElement(bindElement, schema, controlType, owner, occurs);

    // add a group if a repeat !
    if (owner instanceof XSElementDeclaration && occurs.isRepeated()) {
        final Element groupElement = this.createGroup(xformsDocument, modelSection, formSection,
                (XSElementDeclaration) owner, resourceBundle);
        groupElement.setAttributeNS(NamespaceConstants.XFORMS_NS,
                NamespaceConstants.XFORMS_PREFIX + ":appearance", "repeated");

        //set content
        formSection = groupElement;
    }

    //eventual repeat
    final Element repeatSection = this.addRepeatIfNecessary(xformsDocument, modelSection, formSection,
            controlType, pathToRoot, occurs);

    // create the form control element
    //put a wrapper for the repeat content, but only if it is really a repeat
    if (repeatSection != formSection) {
        //if there is a repeat -> create another bind with "."
        final Element bindElement2 = this.createBind(xformsDocument, ".");
        final String bindId2 = bindElement2.getAttributeNS(null, "id");
        bindElement.appendChild(bindElement2);
        bindElement = bindElement2;
        bindId = bindId2;
    }

    final String caption = (owner != null ? this.createCaption(owner, resourceBundle)
            : this.createCaption(owningElementName));
    final Element formControl = this.createFormControl(xformsDocument, schema, caption, controlType, owner,
            bindId, bindElement, occurs, resourceBundle);
    repeatSection.appendChild(formControl);

    // 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(NamespaceConstants.XFORMS_NS,
    //NamespaceConstants.XFORMS_PREFIX + ":ref",
    //".");

    //add selector if repeat
    //if (repeatSection != formSection)
    //this.addSelector(xformsDocument, (Element) formControl.getParentNode());

    return formSection;
}