Example usage for org.w3c.dom Element getNodeName

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

Introduction

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

Prototype

public String getNodeName();

Source Link

Document

The name of this node, depending on its type; see the table above.

Usage

From source file:netinf.common.communication.MessageEncoderXML.java

@Override
public NetInfMessage decodeMessage(byte[] payload) {
    ByteArrayInputStream inputStream = new ByteArrayInputStream(payload);

    try {/*from w  w w  .j a va2s .c o m*/
        Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
        Element documentElement = xml.getDocumentElement();

        String messageName = documentElement.getNodeName();

        Node serializeFormatElement = getFirstElementByTagName(documentElement, EL_SERIALIZE_FORMAT);
        if (serializeFormatElement == null) {
            throw new NetInfUncheckedException("NetInfMessage lacks required field: " + EL_SERIALIZE_FORMAT);
        }

        SerializeFormat serializeFormat = SerializeFormat
                .getSerializeFormat(serializeFormatElement.getTextContent());

        NetInfMessage message;
        if (messageName.equals(RSGetRequest.class.getSimpleName())) {
            message = decodeRSGetRequest(documentElement, serializeFormat);
        } else if (messageName.equals(RSGetResponse.class.getSimpleName())) {
            message = decodeRSGetResponse(documentElement, serializeFormat);
        } else if (messageName.equals(TCChangeTransferRequest.class.getSimpleName())) {
            message = decodeTCChangeTransferRequest(documentElement, serializeFormat);
        } else if (messageName.equals(TCChangeTransferResponse.class.getSimpleName())) {
            message = decodeTCChangeTransferResponse(documentElement, serializeFormat);
        } else if (messageName.equals(TCStartTransferRequest.class.getSimpleName())) {
            message = decodeTCStartTransferRequest(documentElement, serializeFormat);
        } else if (messageName.equals(TCStartTransferResponse.class.getSimpleName())) {
            message = decodeTCStartTransferResponse(documentElement, serializeFormat);
        } else if (messageName.equals(ESFFetchMissedEventsResponse.class.getSimpleName())) {
            message = decodeESFFetchMissedEventsResponse(documentElement, serializeFormat);
        } else if (messageName.equals(ESFFetchMissedEventsRequest.class.getSimpleName())) {
            message = decodeESFFetchMissedEventsRequest(documentElement, serializeFormat);
        } else if (messageName.equals(RSMDHTAck.class.getSimpleName())) {
            message = decodeRSMDHTAck(documentElement, serializeFormat);
        } else {
            throw new NetInfUncheckedException("Don't know how to decode this NetInfMessage");
        }

        Node errorMessageElement = getFirstElementByTagName(documentElement, EL_ERROR_MESSAGE);
        if (errorMessageElement != null) {
            message.setErrorMessage(errorMessageElement.getTextContent());
        }

        message.setSerializeFormat(serializeFormat);

        Node userNameNode = getFirstElementByTagName(documentElement, EL_USER_NAME);
        if (userNameNode != null) {
            message.setUserName(userNameNode.getTextContent());
        }

        Node privateKeyNode = getFirstElementByTagName(documentElement, EL_PRIVATE_KEY);
        if (privateKeyNode != null) {
            message.setPrivateKey(privateKeyNode.getTextContent());
        }

        return message;
    } catch (SAXException e) {
        LOG.error(e.getMessage(), e);
        throw new NetInfUncheckedException(e);
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new NetInfUncheckedException(e);
    } catch (ParserConfigurationException e) {
        LOG.error(e.getMessage(), e);
        throw new NetInfUncheckedException(e);
    }
}

From source file:nl.nn.adapterframework.webcontrol.api.ShowSecurityItems.java

private Map<String, Object> addApplicationDeploymentDescriptor() {
    String appDDString = null;/*from   w  ww  . j a  v a2s  . c om*/
    Map<String, Object> resultList = new HashMap<String, Object>();
    Document xmlDoc = null;

    try {
        appDDString = Misc.getApplicationDeploymentDescriptor();
        appDDString = XmlUtils.skipXmlDeclaration(appDDString);
        appDDString = XmlUtils.skipDocTypeDeclaration(appDDString);
        appDDString = XmlUtils.removeNamespaces(appDDString);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        InputSource inputSource = new InputSource(new StringReader(appDDString));
        xmlDoc = dBuilder.parse(inputSource);
        xmlDoc.getDocumentElement().normalize();
    } catch (Exception e) {
        return null;
    }

    Map<String, Map<String, List<String>>> secBindings = getSecurityRoleBindings();

    NodeList rowset = xmlDoc.getElementsByTagName("security-role");
    for (int i = 0; i < rowset.getLength(); i++) {
        Element row = (Element) rowset.item(i);
        NodeList fieldsInRowset = row.getChildNodes();
        if (fieldsInRowset != null && fieldsInRowset.getLength() > 0) {
            Map<String, Object> tmp = new HashMap<String, Object>();
            for (int j = 0; j < fieldsInRowset.getLength(); j++) {
                if (fieldsInRowset.item(j).getNodeType() == Node.ELEMENT_NODE) {
                    Element field = (Element) fieldsInRowset.item(j);
                    tmp.put(field.getNodeName(), field.getTextContent());
                }
            }
            if (secBindings.containsKey(row.getAttribute("id")))
                tmp.putAll(secBindings.get(row.getAttribute("id")));
            try {
                if (tmp.containsKey("role-name")) {
                    String role = (String) tmp.get("role-name");
                    tmp.put("allowed", httpServletRequest.isUserInRole(role));
                }
            } catch (Exception e) {
            }
            ;
            resultList.put(row.getAttribute("id"), tmp);
        }
    }

    return resultList;
}

From source file:nl.nn.adapterframework.webcontrol.api.ShowSecurityItems.java

private Map<String, Map<String, List<String>>> getSecurityRoleBindings() {
    String appBndString = null;// w  w w .  j av a 2  s .  c o  m
    Map<String, Map<String, List<String>>> resultList = new HashMap<String, Map<String, List<String>>>();
    Document xmlDoc = null;

    try {
        appBndString = Misc.getDeployedApplicationBindings();
        appBndString = XmlUtils.removeNamespaces(appBndString);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        InputSource inputSource = new InputSource(new StringReader(appBndString));
        xmlDoc = dBuilder.parse(inputSource);
        xmlDoc.getDocumentElement().normalize();
    } catch (Exception e) {
        return null;
    }

    NodeList rowset = xmlDoc.getElementsByTagName("authorizations");
    for (int i = 0; i < rowset.getLength(); i++) {
        Element row = (Element) rowset.item(i);
        NodeList fieldsInRowset = row.getChildNodes();
        if (fieldsInRowset != null && fieldsInRowset.getLength() > 0) {
            String role = null;
            List<String> roles = new ArrayList<String>();
            List<String> specialSubjects = new ArrayList<String>();
            for (int j = 0; j < fieldsInRowset.getLength(); j++) {
                if (fieldsInRowset.item(j).getNodeType() == Node.ELEMENT_NODE) {
                    Element field = (Element) fieldsInRowset.item(j);

                    if (field.getNodeName() == "role") {
                        role = field.getAttribute("href");
                        if (role.indexOf("#") > -1)
                            role = role.substring(role.indexOf("#") + 1);
                    } else if (field.getNodeName() == "specialSubjects") {
                        specialSubjects.add(field.getAttribute("name"));
                    } else if (field.getNodeName() == "groups") {
                        roles.add(field.getAttribute("name"));
                    }
                }
            }
            if (role != null && role != "") {
                Map<String, List<String>> roleBinding = new HashMap<String, List<String>>();
                roleBinding.put("groups", roles);
                roleBinding.put("specialSubjects", specialSubjects);
                resultList.put(role, roleBinding);
            }
        }
    }
    return resultList;
}

From source file:openblocks.yacodeblocks.BlockSaveFileTest.java

private void assertElementContainsOnlyAsciiCharacters(Element element) throws Exception {
    assertStringContainsOnlyAsciiCharacters(element.getNodeName(), "name", element);

    if (element.hasAttributes()) {
        NamedNodeMap attributes = element.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            assertNodeContainsOnlyAsciiCharacters(attributes.item(i));
        }/*from   w w w  .  j  a v  a  2 s.  c o  m*/
    }

    if (element.hasChildNodes()) {
        NodeList childNodes = element.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            assertNodeContainsOnlyAsciiCharacters(childNodes.item(i));
        }
    }
}

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

/**
 * Generate the XForm based on a user supplied XML Schema.
 *
 * @param instanceDocument The document source for the XML Schema.
 * @param schemaDocument Schema document
 * @param rootElementName Name of the root element
 * @param resourceBundle Strings to use//  ww w .j ava2 s  . co  m
 * @return The Document containing the XForm.
 * @throws org.chiba.tools.schemabuilder.FormBuilderException
 *          If an error occurs building the XForm.
 */
public Pair<Document, XSModel> buildXForm(final Document instanceDocument, final Document schemaDocument,
        String rootElementName, final ResourceBundle resourceBundle) throws FormBuilderException {
    final XSModel schema = SchemaUtil.parseSchema(schemaDocument, true);
    this.typeTree = SchemaUtil.buildTypeTree(schema);

    //refCounter = 0;
    this.counter.clear();

    final Document xformsDocument = this.createFormTemplate(rootElementName);

    //find form element: last element created
    final Element formSection = (Element) xformsDocument.getDocumentElement().getLastChild();
    final Element modelSection = (Element) xformsDocument.getDocumentElement()
            .getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "model").item(0);

    //add XMLSchema if we use schema types      
    final Element importedSchemaDocumentElement = (Element) xformsDocument
            .importNode(schemaDocument.getDocumentElement(), true);
    importedSchemaDocumentElement.setAttributeNS(null, "id", "schema-1");

    NodeList nl = importedSchemaDocumentElement.getChildNodes();
    boolean hasExternalSchema = false;

    for (int i = 0; i < nl.getLength(); i++) {
        Node current = nl.item(i);
        if (current.getNamespaceURI() != null
                && current.getNamespaceURI().equals(NamespaceConstants.XMLSCHEMA_NS)) {
            String localName = current.getLocalName();
            if (localName.equals("include") || localName.equals("import")) {
                hasExternalSchema = true;
                break;
            }
        }
    }

    // ALF-8105 / ETWOTWO-1384: Only embed the schema if it does not reference externals
    if (!hasExternalSchema) {
        modelSection.appendChild(importedSchemaDocumentElement);
    }

    //check if target namespace
    final StringList schemaNamespaces = schema.getNamespaces();
    final HashMap<String, String> schemaNamespacesMap = new HashMap<String, String>();
    if (schemaNamespaces.getLength() != 0) {
        // will return null if no target namespace was specified
        this.targetNamespace = schemaNamespaces.item(0);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("[buildXForm] using targetNamespace " + this.targetNamespace);

        for (int i = 0; i < schemaNamespaces.getLength(); i++) {
            if (schemaNamespaces.item(i) == null) {
                continue;
            }
            final String prefix = addNamespace(xformsDocument.getDocumentElement(),
                    schemaDocument.lookupPrefix(schemaNamespaces.item(i)), schemaNamespaces.item(i));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[buildXForm] adding namespace " + schemaNamespaces.item(i) + " with prefix "
                        + prefix + " to xform and default instance element");
            }
            schemaNamespacesMap.put(prefix, schemaNamespaces.item(i));
        }
    }

    //if target namespace & we use the schema types: add it to form ns declarations
    //   if (this.targetNamespace != null && this.targetNamespace.length() != 0)
    //       envelopeElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
    //                  "xmlns:schema",
    //                  this.targetNamespace);

    final XSElementDeclaration rootElementDecl = schema.getElementDeclaration(rootElementName,
            this.targetNamespace);
    if (rootElementDecl == null) {
        throw new FormBuilderException("Invalid root element tag name [" + rootElementName
                + ", targetNamespace = " + this.targetNamespace + "]");
    }

    rootElementName = this.getElementName(rootElementDecl, xformsDocument);
    final Element instanceElement = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
            NamespaceConstants.XFORMS_PREFIX + ":instance");
    modelSection.appendChild(instanceElement);
    this.setXFormsId(instanceElement);

    final Element defaultInstanceDocumentElement = xformsDocument.createElement(rootElementName);
    addNamespace(defaultInstanceDocumentElement, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
    if (this.targetNamespace != null) {
        final String targetNamespacePrefix = schemaDocument.lookupPrefix(this.targetNamespace);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[buildXForm] adding target namespace " + this.targetNamespace + " with prefix "
                    + targetNamespacePrefix + " to xform and default instance element");
        }

        addNamespace(defaultInstanceDocumentElement, targetNamespacePrefix, this.targetNamespace);
        addNamespace(xformsDocument.getDocumentElement(), targetNamespacePrefix, this.targetNamespace);
    }

    Element prototypeInstanceElement = null;
    if (instanceDocument == null || instanceDocument.getDocumentElement() == null) {
        instanceElement.appendChild(defaultInstanceDocumentElement);
    } else {
        Element instanceDocumentElement = instanceDocument.getDocumentElement();
        if (!instanceDocumentElement.getNodeName().equals(rootElementName)) {
            throw new IllegalArgumentException("instance document root tag name invalid.  " + "expected "
                    + rootElementName + ", got " + instanceDocumentElement.getNodeName());
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("[buildXForm] importing rootElement from other document");

        prototypeInstanceElement = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
                NamespaceConstants.XFORMS_PREFIX + ":instance");
        modelSection.appendChild(prototypeInstanceElement);
        this.setXFormsId(prototypeInstanceElement, "instance_prototype");
        prototypeInstanceElement.appendChild(defaultInstanceDocumentElement);
    }

    final Element rootGroup = this.addElement(xformsDocument, modelSection, defaultInstanceDocumentElement,
            formSection, schema, rootElementDecl, "/" + this.getElementName(rootElementDecl, xformsDocument),
            new SchemaUtil.Occurrence(1, 1), resourceBundle);
    if (rootGroup.getNodeName() != NamespaceConstants.XFORMS_PREFIX + ":group") {
        throw new FormBuilderException("Expected root form element to be a " + NamespaceConstants.XFORMS_PREFIX
                + ":group, not a " + rootGroup.getNodeName() + ".  Ensure that "
                + this.getElementName(rootElementDecl, xformsDocument)
                + " is a concrete type that has no extensions.  "
                + "Types with extensions are not supported for " + "the root element of a form.");
    }
    this.setXFormsId(rootGroup, "alfresco-xforms-root-group");

    if (prototypeInstanceElement != null) {
        Schema2XForms.rebuildInstance(prototypeInstanceElement, instanceDocument, instanceElement,
                schemaNamespacesMap);
    }

    this.createSubmitElements(xformsDocument, modelSection, rootGroup);
    this.createTriggersForRepeats(xformsDocument, rootGroup);

    final Comment comment = xformsDocument.createComment(
            "This XForm was generated by " + this.getClass().getName() + " on " + (new Date()) + " from the '"
                    + rootElementName + "' element of the '" + this.targetNamespace + "' XML Schema.");
    xformsDocument.getDocumentElement().insertBefore(comment,
            xformsDocument.getDocumentElement().getFirstChild());
    xformsDocument.normalizeDocument();

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("[buildXForm] Returning XForm =\n" + XMLUtil.toString(xformsDocument));

    return new Pair<Document, XSModel>(xformsDocument, schema);
}

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

/**
 * Add a repeat section if maxOccurs > 1.
 *///from   w  w  w .  j  ava2  s .c  o  m
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

private static String addNamespace(final Element e, String nsPrefix, final String ns) {
    String prefix;//from  w  w  w.  java2  s  .  co  m
    if ((prefix = NamespaceResolver.getPrefix(e, ns)) != null) {
        return prefix;
    }

    if (nsPrefix == null || e.hasAttributeNS(NamespaceConstants.XMLNS_NS, nsPrefix)) {
        // Generate a unique prefix
        int suffix = 1;
        while (e.hasAttributeNS(NamespaceConstants.XMLNS_NS, nsPrefix = "ns" + suffix)) {
            suffix++;
        }
    }

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("[addNamespace] adding namespace " + ns + " with prefix " + nsPrefix + " to "
                + e.getNodeName());

    e.setAttributeNS(NamespaceConstants.XMLNS_NS, NamespaceConstants.XMLNS_PREFIX + ':' + nsPrefix, ns);

    return nsPrefix;
}

From source file:org.apache.axis.AxisFault.java

/**
 * Find a fault detail element by its qname.
 * @param qname name of the node to look for
 * @return the matching element or null//ww w  .  java  2 s  .c  o m
 * @since axis1.1
 */
public Element lookupFaultDetail(QName qname) {
    if (faultDetails != null) {
        //extract details from the qname. the empty namespace is represented
        //by the empty string
        String searchNamespace = qname.getNamespaceURI();
        String searchLocalpart = qname.getLocalPart();
        //now spin through the elements, seeking a match
        Iterator it = faultDetails.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String localpart = e.getLocalName();
            if (localpart == null) {
                localpart = e.getNodeName();
            }
            String namespace = e.getNamespaceURI();
            if (namespace == null) {
                namespace = "";
            }
            //we match on matching namespace and local part; empty namespace
            //in an element may be null, which matches QName's ""
            if (searchNamespace.equals(namespace) && searchLocalpart.equals(localpart)) {
                return e;
            }
        }
    }
    return null;
}

From source file:org.apache.axis.encoding.SerializationContext.java

/**
 * Output a DOM representation to a SerializationContext
 * @param el is a DOM Element/*  w w  w  .j  ava2 s  .com*/
 */
public void writeDOMElement(Element el) throws IOException {
    if (startOfDocument && sendXMLDecl) {
        writeXMLDeclaration();
    }

    // If el is a Text element, write the text and exit
    if (el instanceof org.apache.axis.message.Text) {
        writeSafeString(((Text) el).getData());
        return;
    }

    AttributesImpl attributes = null;
    NamedNodeMap attrMap = el.getAttributes();

    if (attrMap.getLength() > 0) {
        attributes = new AttributesImpl();
        for (int i = 0; i < attrMap.getLength(); i++) {
            Attr attr = (Attr) attrMap.item(i);
            String tmp = attr.getNamespaceURI();
            if (tmp != null && tmp.equals(Constants.NS_URI_XMLNS)) {
                String prefix = attr.getLocalName();
                if (prefix != null) {
                    if (prefix.equals("xmlns"))
                        prefix = "";
                    String nsURI = attr.getValue();
                    registerPrefixForURI(prefix, nsURI);
                }
                continue;
            }

            attributes.addAttribute(attr.getNamespaceURI(), attr.getLocalName(), attr.getName(), "CDATA",
                    attr.getValue());
        }
    }

    String namespaceURI = el.getNamespaceURI();
    String localPart = el.getLocalName();
    if (namespaceURI == null || namespaceURI.length() == 0)
        localPart = el.getNodeName();
    QName qName = new QName(namespaceURI, localPart);

    startElement(qName, attributes);

    NodeList children = el.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child instanceof Element) {
            writeDOMElement((Element) child);
        } else if (child instanceof CDATASection) {
            writeString("<![CDATA[");
            writeString(((Text) child).getData());
            writeString("]]>");
        } else if (child instanceof Comment) {
            writeString("<!--");
            writeString(((CharacterData) child).getData());
            writeString("-->");
        } else if (child instanceof Text) {
            writeSafeString(((Text) child).getData());
        }
    }

    endElement();
}