Example usage for org.w3c.dom Element cloneNode

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

Introduction

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

Prototype

public Node cloneNode(boolean deep);

Source Link

Document

Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes.

Usage

From source file:com.wfreitas.camelsoap.SoapClient.java

/**
 * Clone a collection node.//  w  ww  .j  av a  2 s  . co m
 * <p/>
 * Note we have to frig with the OGNL expressions for collections/arrays because the
 * collection entry is represented by [0], [1] etc in the OGNL expression, not the actual
 * element name on the DOM e.g. collection node "order/items/item" (where "item" is the
 * actual collection entry) maps to the OGNL expression "order.items[0]" etc.
 *
 * @param element    The collection/array "entry" sub-branch.
 * @param cloneCount The number of times it needs to be cloned.
 * @param ognl       The OGNL expression for the collection/array. Not including the
 *                   indexing part.
 */
private void cloneCollectionTemplateElement(Element element, int cloneCount, String ognl) {
    if (element == null) {
        return;
    }

    Node insertPoint = element.getNextSibling();
    Node parent = element.getParentNode();

    element.setAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS,
            OGNLUtils.JBOSSESB_SOAP_NS_PREFIX + OGNLUtils.OGNL_ATTRIB, ognl + "[0]");
    for (int i = 0; i < cloneCount; i++) {
        Element clone = (Element) element.cloneNode(true);

        clone.setAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS, OGNLUtils.JBOSSESB_SOAP_NS_PREFIX + IS_CLONE_ATTRIB,
                "true");
        clone.setAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS,
                OGNLUtils.JBOSSESB_SOAP_NS_PREFIX + OGNLUtils.OGNL_ATTRIB,
                ognl + "[" + Integer.toString(i + 1) + "]");
        if (insertPoint == null) {
            parent.appendChild(clone);
        } else {
            parent.insertBefore(clone, insertPoint);
        }
    }
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

@Test
public void testCreateLargeRecordSet() throws Exception {
    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);
    Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream);
    Element entityContainerElement = (Element) xp.evaluate(
            "/merge:EntityMergeRequestMessage/merge:MergeParameters/er-ext:EntityContainer", testRequestMessage,
            XPathConstants.NODE);
    assertNotNull(entityContainerElement);
    Element entityElement = (Element) xp.evaluate("er-ext:Entity[1]", entityContainerElement,
            XPathConstants.NODE);
    assertNotNull(entityElement);/* w w  w  .  j  a  va 2  s .  c  o  m*/
    int entityCount = ((NodeList) xp.evaluate("er-ext:Entity", entityContainerElement, XPathConstants.NODESET))
            .getLength();
    int expectedInitialEntityCount = 6;
    assertEquals(expectedInitialEntityCount, entityCount);
    int recordIncrement = 500;
    for (int i = 0; i < recordIncrement; i++) {
        Element newEntityElement = (Element) entityElement.cloneNode(true);
        entityContainerElement.appendChild(newEntityElement);
    }
    entityCount = ((NodeList) xp.evaluate("er-ext:Entity", entityContainerElement, XPathConstants.NODESET))
            .getLength();
    assertEquals(expectedInitialEntityCount + recordIncrement, entityCount);

    Node entityContainerNode = testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer")
            .item(0);
    assertNotNull(entityContainerNode);

    NodeList entityNodeList = ((Element) entityContainerNode)
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "Entity");
    List<RecordWrapper> records = entityResolutionMessageHandler.createRecordsFromRequestMessage(entityNodeList,
            null);
    assertEquals(expectedInitialEntityCount + recordIncrement, records.size());
}

From source file:fr.cls.atoll.motu.processor.wps.StringList.java

public static void readXML(Element object) {
    // XMLReader parser = XMLReaderFactory.createXMLReader();
    // InputSource inputSource = new InputSource()
    // parser.parse(input);

    try {//from   w  w  w. j  ava  2  s .c o m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Source src = new DOMSource(object);
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tformer = tFactory.newTransformer();

        Result result = new StreamResult(System.out);
        tformer.transform(src, result);
        // doc.getDocumentElement().normalize();
        // System.out.println("Root element " + doc.getDocumentElement().getNodeName());
        // NodeList nodeLst = doc.getElementsByTagName("employee");
        // System.out.println("Information of all employees");

        Element copyElement = (Element) object.cloneNode(true);
        Document doc = db.newDocument();
        Node node = doc.importNode(copyElement, true);
        NodeList nodeList = doc.getElementsByTagName("Arc");
        System.out.println(doc.getElementsByTagName("Curve"));
        // Node node = object;

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:de.betterform.xml.xforms.model.Model.java

private XSModel loadSchema(Element element)
        throws TransformerException, IllegalAccessException, InstantiationException, ClassNotFoundException {
    Element copy = (Element) element.cloneNode(true);
    NamespaceResolver.applyNamespaces(element, copy);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.transform(new DOMSource(copy), new StreamResult(stream));
    byte[] array = stream.toByteArray();

    return loadSchema(new ByteArrayInputStream(array));
}

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));
    }//from  ww w . j  a v a2  s . c om

    // 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

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  ww  w.  j av  a 2s. co  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);/*from w w w .  ja v a  2 s  .  c o m*/

    // 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.  j a  v  a2  s .  co 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

@SuppressWarnings("unchecked")
private void addElementToGroup(final Document xformsDocument, final Element modelSection,
        final Element defaultInstanceElement, final Element formSection, final XSModel schema,
        final XSElementDeclaration element, final String pathToRoot, final SchemaUtil.Occurrence occurs,
        final ResourceBundle resourceBundle) throws FormBuilderException {
    //add it normally
    final String elementName = this.getElementName(element, xformsDocument);
    final String path = (pathToRoot.length() == 0 ? elementName : pathToRoot + "/" + elementName);

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("[addElementToGroup] Start addElement to group " + elementName + " at " + path
                + " parentStack " + this.parentStack);

    if (this.parentStack.contains(element)) {
        throw new FormBuilderException("recursion detected at element " + elementName);
    }/*from   ww w .  j av  a2 s  .  com*/

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("[addElementToGroup] pushing element " + element + " onto parent stack");

    this.parentStack.push(element);

    final Element newDefaultInstanceElement = xformsDocument.createElement(elementName);
    if (element.getConstraintType() != XSConstants.VC_NONE) {
        Node value = xformsDocument.createTextNode(element.getConstraintValue());
        newDefaultInstanceElement.appendChild(value);
    } else if ("boolean".equals(element.getTypeDefinition().getName())) {
        // we have a boolean element without a default value, default to false
        Node value = xformsDocument.createTextNode("false");
        newDefaultInstanceElement.appendChild(value);
    }

    this.addElement(xformsDocument, modelSection, newDefaultInstanceElement, formSection, schema, element, path,
            occurs, resourceBundle);

    Object poppedElement = this.parentStack.pop();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("[addElementToGroup] popped element " + poppedElement + " from parent stack");
        LOGGER.debug("[addElementToGroup] adding " + (occurs.maximum == 1 ? 1 : occurs.minimum + 1)
                + " default instance element for " + elementName + " at path " + path);
    }

    // update the default instance
    if (isRepeated(occurs, element.getTypeDefinition())) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[addElementToGroup] adding " + (occurs.minimum + 1)
                    + " default instance elements for " + elementName + " at path " + path);
        }

        for (int i = 0; i < occurs.minimum + 1; i++) {
            final Element e = (Element) newDefaultInstanceElement.cloneNode(true);
            if (i == occurs.minimum) {
                e.setAttributeNS(NamespaceService.ALFRESCO_URI, NamespaceService.ALFRESCO_PREFIX + ":prototype",
                        "true");
            }
            defaultInstanceElement.appendChild(e);
        }
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[addElementToGroup] adding one default instance element for " + elementName
                    + " at path " + path);
        }

        if (occurs.minimum == 0) {
            newDefaultInstanceElement.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS,
                    NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":nil", "true");
        }
        defaultInstanceElement.appendChild(newDefaultInstanceElement);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("[addGroup] End of addElementToGroup, group = " + elementName);
    }
}

From source file:org.apache.shindig.gadgets.rewrite.ConcatVisitor.java

/**
 * For css:/*from w  w  w . j av  a2  s  .  c om*/
 * Link tags are first split into buckets separated by tags with mediaType == "all"
 * / title attribute different from their previous link tag / nodes that are
 * not 'link' tags.
 * This ensures that the buckets can be processed separately without losing title /
 * "all" mediaType information.
 *
 * Link tags with same mediaType are concatenated within each bucket.
 * This exercise ensures that css information is loaded in the same relative order
 * as that of the original html page, and that the css information within
 * mediaType=="all" is retained and applies to all media types.
 *
 * Look at the areLinkNodesBucketable method for details on mediaType=="all" and
 * title attribute
 *
 * Example: Assume we have the following node list. (all have same parent,
 * nodes between Node6 and Node12 are non link nodes, and hence did not come
 * to revisit() call)
 *    <link href="1.css" rel="stylesheet" type="text/css" media="screen">       -- Node1
 *    <link href="2.css" rel="stylesheet" type="text/css" media="print">        -- Node2
 *    <link href="3.css" rel="stylesheet" type="text/css" media="screen">       -- Node3
 *    <link href="4.css" rel="stylesheet" type="text/css" media="all">          -- Node4
 *    <link href="5.css" rel="stylesheet" type="text/css" media="all">          -- Node5
 *    <link href="6.css" rel="stylesheet" type="text/css" media="screen">       -- Node6
 *    <link href="12.css" rel="stylesheet" type="text/css" media="screen">      -- Node12
 *    <link href="13.css" rel="stylesheet" type="text/css" media="screen">      -- Node13
 *
 *    First we split to buckets bassed on the adjacency and other conditions.
 *    buckets - [ [ Node1, Node2, Node3 ], [ Node4, Node 5 ], [ Node6 ], [ Node12, Node13 ]
 *    Within each bucket we group them based on media type.
 *    batches - [ Node1, Node2, Node3 ] --> [ [Node1, Node3], [Node2] ]
 *            - [ Node4, Node 5 ] --> [ [ Node4, Node 5 ] ]
 *            - [ Node6 ] --> [ [ Node6 ] ]
 *            - [ Node12, Node13 ] --> [ [ Node12, Node13 ] ]
 *
 * Refer Tests for more examples.
 */
public boolean revisit(Gadget gadget, List<Node> nodes) throws RewritingException {
    // Collate Elements into Buckets.
    List<List<Element>> concatBuckets = Lists.newLinkedList();
    List<Element> curBucket = Lists.newLinkedList();
    Iterator<Node> nodeIter = nodes.iterator();
    Element cur = (Element) nodeIter.next();
    curBucket.add(cur);
    while (nodeIter.hasNext()) {
        Element next = (Element) nodeIter.next();
        if ((!split && cur != getSibling(next, true))
                || (type == ConcatUriManager.Type.CSS && !areLinkNodesBucketable(cur, next))) {
            // Break off current bucket and add to list of all.
            concatBuckets.add(curBucket);
            curBucket = Lists.newLinkedList();
        }
        curBucket.add(next);
        cur = next;
    }

    // Add leftovers.
    concatBuckets.add(curBucket);

    // Split the existing buckets based on media types into concat batches.
    List<List<Element>> concatBatches = Lists.newLinkedList();
    Iterator<List<Element>> batchesIter = concatBuckets.iterator();
    while (batchesIter.hasNext()) {
        splitBatchOnMedia(batchesIter.next(), concatBatches);
    }

    // Prepare batches of Uris to send to generate concat Uris
    List<List<Uri>> uriBatches = Lists.newLinkedList();
    batchesIter = concatBatches.iterator();
    while (batchesIter.hasNext()) {
        List<Element> batch = batchesIter.next();
        List<Uri> uris = Lists.newLinkedList();
        if (batch.isEmpty() || !getUris(type, batch, uris)) {
            batchesIter.remove();
            continue;
        }
        uriBatches.add(uris);
    }

    if (uriBatches.isEmpty()) {
        return false;
    }

    // Generate the ConcatUris, then correlate with original elements.
    List<ConcatUriManager.ConcatData> concatUris = uriManager
            .make(ConcatUriManager.ConcatUri.fromList(gadget, uriBatches, type), !split);

    Iterator<List<Element>> elemBatchIt = concatBatches.iterator();
    Iterator<List<Uri>> uriBatchIt = uriBatches.iterator();
    for (ConcatUriManager.ConcatData concatUri : concatUris) {
        List<Element> sourceBatch = elemBatchIt.next();
        List<Uri> sourceUris = uriBatchIt.next();

        // Regardless what happens, inject a copy of the first node,
        // with new (concat) URI, immediately ahead of the first elem.
        Element firstElem = sourceBatch.get(0);
        Element elemConcat = (Element) firstElem.cloneNode(true);
        elemConcat.setAttribute(type.getSrcAttrib(), concatUri.getUri().toString());
        firstElem.getParentNode().insertBefore(elemConcat, firstElem);

        // Now for all Elements, either A) remove them or B) replace each
        // with a <script> node with snippet of code configuring/evaluating
        // the resultant inserted code. This is useful for split-JS in particular,
        // and might also be used in spriting later.
        Iterator<Uri> uriIt = sourceUris.iterator();
        for (Element elem : sourceBatch) {
            Uri elemOrigUri = uriIt.next();
            String snippet = concatUri.getSnippet(elemOrigUri);
            if (!StringUtils.isEmpty(snippet)) {
                Node scriptNode = elem.getOwnerDocument().createElement("script");
                scriptNode.setTextContent(snippet);
                elem.getParentNode().insertBefore(scriptNode, elem);
            }
            elem.getParentNode().removeChild(elem);
        }
    }

    return true;
}