List of usage examples for org.w3c.dom Element hasAttributeNS
public boolean hasAttributeNS(String namespaceURI, String localName) throws DOMException;
true
when an attribute with a given local name and namespace URI is specified on this element or has a default value, false
otherwise. 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 va 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; }/* ww w .ja v a 2 s . c o m*/ 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
protected String setXFormsId(final Element el, String id) { if (el.hasAttributeNS(null, "id")) { el.removeAttributeNS(null, "id"); }// w w w. j a va 2 s .com if (id == null) { final String name = el.getLocalName(); final Long l = this.counter.get(name); final long count = (l != null) ? l : 0; // increment the counter this.counter.put(name, new Long(count + 1)); id = name + "_" + count; } el.setAttributeNS(null, "id", id); return id; }
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 ww.ja va 2 s .com*/ 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.ws.security.util.WSSecurityUtil.java
/** * Returns the single element that contains an Id with value * <code>uri</code> and <code>namespace</code>. <p/> This is a * replacement for a XPath Id lookup with the given namespace. It's somewhat * faster than XPath, and we do not deal with prefixes, just with the real * namespace URI//from w ww. ja va 2s . c o m * * If there are multiple elements, we log a warning and return null as this * can be used to get around the signature checking. * * @param startNode Where to start the search * @param value Value of the Id attribute * @param namespace Namespace URI of the Id * @return The found element if there was exactly one match, or * <code>null</code> otherwise */ public static Element findElementById(Node startNode, String value, String namespace) { Element foundElement = null; // // Replace the formerly recursive implementation with a depth-first-loop // lookup // if (startNode == null) { return null; } Node startParent = startNode.getParentNode(); Node processedNode = null; while (startNode != null) { // start node processing at this point if (startNode.getNodeType() == Node.ELEMENT_NODE) { Element se = (Element) startNode; if (se.hasAttributeNS(namespace, "Id") && value.equals(se.getAttributeNS(namespace, "Id"))) { if (foundElement == null) { foundElement = se; // Continue searching to find duplicates } else { log.warn("Multiple elements with the same 'Id' attribute value!"); return null; } } } processedNode = startNode; startNode = startNode.getFirstChild(); // no child, this node is done. if (startNode == null) { // close node processing, get sibling startNode = processedNode.getNextSibling(); } // no more siblings, get parent, all children // of parent are processed. while (startNode == null) { processedNode = processedNode.getParentNode(); if (processedNode == startParent) { return foundElement; } // close parent node processing (processed node now) startNode = processedNode.getNextSibling(); } } return foundElement; }
From source file:org.apache.xml.security.utils.XMLUtils.java
/** * This is the work horse for {@link #circumventBug2650}. * * @param node//from w ww .j a v a2 s . c o m * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650"> * Namespace axis resolution is not XPath compliant </A> */ private static void circumventBug2650internal(Node node) { Node parent = null; Node sibling = null; final String namespaceNs = Constants.NamespaceSpecNS; do { switch (node.getNodeType()) { case Node.ELEMENT_NODE: Element element = (Element) node; if (!element.hasChildNodes()) { break; } if (element.hasAttributes()) { NamedNodeMap attributes = element.getAttributes(); int attributesLength = attributes.getLength(); for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getNodeType() != Node.ELEMENT_NODE) { continue; } Element childElement = (Element) child; for (int i = 0; i < attributesLength; i++) { Attr currentAttr = (Attr) attributes.item(i); if (!namespaceNs.equals(currentAttr.getNamespaceURI())) continue; if (childElement.hasAttributeNS(namespaceNs, currentAttr.getLocalName())) { continue; } childElement.setAttributeNS(namespaceNs, currentAttr.getName(), currentAttr.getNodeValue()); } } } case Node.ENTITY_REFERENCE_NODE: parent = node; sibling = node.getFirstChild(); break; case Node.DOCUMENT_NODE: parent = node; sibling = node.getFirstChild(); break; } while ((sibling == null) && (parent != null)) { sibling = parent.getNextSibling(); parent = parent.getParentNode(); } if (sibling == null) { return; } node = sibling; sibling = node.getNextSibling(); } while (true); }
From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java
/** * builds a form from a XML schema.//w w w . ja va 2 s . c o m * * @param inputURI the URI of the Schema to be used * @return __UNDOCUMENTED__ * @throws FormBuilderException __UNDOCUMENTED__ */ public Document buildForm(String inputURI) throws FormBuilderException { try { this.loadSchema(inputURI); buildTypeTree(schema); //refCounter = 0; counter = new HashMap(); Document xForm = createFormTemplate(_rootTagName, _rootTagName + " Form", getProperty(CSS_STYLE_PROP, DEFAULT_CSS_STYLE_PROP)); //this.buildInheritenceTree(schema); Element envelopeElement = xForm.getDocumentElement(); //Element formSection = (Element) envelopeElement.getElementsByTagNameNS(CHIBA_NS, "form").item(0); //Element formSection =(Element) envelopeElement.getElementsByTagName("body").item(0); //find form element: last element created NodeList children = xForm.getDocumentElement().getChildNodes(); int nb = children.getLength(); Element formSection = (Element) children.item(nb - 1); Element modelSection = (Element) envelopeElement.getElementsByTagNameNS(XFORMS_NS, "model").item(0); //add XMLSchema if we use schema types if (_useSchemaTypes && modelSection != null) { modelSection.setAttributeNS(XFORMS_NS, this.getXFormsNSPrefix() + "schema", inputURI); } //change stylesheet String stylesheet = this.getStylesheet(); if ((stylesheet != null) && !stylesheet.equals("")) { envelopeElement.setAttributeNS(CHIBA_NS, this.getChibaNSPrefix() + "stylesheet", stylesheet); } // TODO: Commented out because comments aren't output properly by the Transformer. //String comment = "This XForm was automatically generated by " + this.getClass().getName() + " on " + (new Date()) + System.getProperty("line.separator") + " from the '" + rootElementName + "' element from the '" + schema.getSchemaTargetNS() + "' XML Schema."; //xForm.insertBefore(xForm.createComment(comment),envelopeElement); //xxx XSDNode node = findXSDNodeByName(rootElementTagName,schemaNode.getElementSet()); //check if target namespace //no way to do this with XS API ? load DOM document ? //TODO: find a better way to find the targetNamespace try { Document domDoc = DOMUtil.parseXmlFile(inputURI, true, false); if (domDoc != null) { Element root = domDoc.getDocumentElement(); targetNamespace = root.getAttribute("targetNamespace"); if (targetNamespace != null && targetNamespace.equals("")) targetNamespace = null; } } catch (Exception ex) { LOGGER.error("Schema not loaded as DOM document: " + ex.getMessage()); } //if target namespace & we use the schema types: add it to form ns declarations if (_useSchemaTypes && targetNamespace != null && !targetNamespace.equals("")) { envelopeElement.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:schema", targetNamespace); } //TODO: WARNING: in Xerces 2.6.1, parameters are switched !!! (name, namespace) //XSElementDeclaration rootElementDecl =schema.getElementDeclaration(targetNamespace, _rootTagName); XSElementDeclaration rootElementDecl = schema.getElementDeclaration(_rootTagName, targetNamespace); if (rootElementDecl == null) { //DEBUG rootElementDecl = schema.getElementDeclaration(_rootTagName, targetNamespace); if (rootElementDecl != null && LOGGER.isDebugEnabled()) LOGGER.debug("getElementDeclaration: inversed parameters OK !!!"); throw new FormBuilderException("Invalid root element tag name [" + _rootTagName + ", targetNamespace=" + targetNamespace + "]"); } Element instanceElement = (Element) modelSection .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "instance")); this.setXFormsId(instanceElement); Element rootElement; if (_instanceMode == AbstractSchemaFormBuilder.INSTANCE_MODE_NONE) { rootElement = (Element) instanceElement.appendChild( xForm.createElementNS(targetNamespace, getElementName(rootElementDecl, xForm))); String prefix = xmlSchemaInstancePrefix.substring(0, xmlSchemaInstancePrefix.length() - 1); rootElement.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:" + prefix, XMLSCHEMA_INSTANCE_NAMESPACE_URI); } else if (_instanceMode == AbstractSchemaFormBuilder.INSTANCE_MODE_INCLUDED) //get the instance element { boolean ok = true; try { /*DOMResult result = new DOMResult(); TransformerFactory trFactory = TransformerFactory.newInstance(); Transformer tr = trFactory.newTransformer(); tr.transform(_instanceSource, result); Document instanceDoc = (Document) result.getNode();*/ DocumentBuilderFactory docFact = DocumentBuilderFactory.newInstance(); docFact.setNamespaceAware(true); docFact.setValidating(false); DocumentBuilder parser = docFact.newDocumentBuilder(); Document instanceDoc = parser.parse(new InputSource(_instanceSource.getSystemId())); //possibility abandonned for the moment: //modify the instance to add the correct "xsi:type" attributes wherever needed //Document instanceDoc=this.setXMLSchemaAndPSVILoad(inputURI, _instanceSource, targetNamespace); if (instanceDoc != null) { Element instanceInOtherDoc = instanceDoc.getDocumentElement(); if (instanceInOtherDoc.getNodeName().equals(_rootTagName)) { rootElement = (Element) xForm.importNode(instanceInOtherDoc, true); instanceElement.appendChild(rootElement); //add XMLSchema instance NS String prefix = xmlSchemaInstancePrefix.substring(0, xmlSchemaInstancePrefix.length() - 1); if (!rootElement.hasAttributeNS(XMLNS_NAMESPACE_URI, prefix)) rootElement.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:" + prefix, XMLSCHEMA_INSTANCE_NAMESPACE_URI); //possibility abandonned for the moment: //modify the instance to add the correct "xsi:type" attributes wherever needed //this.addXSITypeAttributes(rootElement); } else { ok = false; } } else { ok = false; } } catch (Exception ex) { ex.printStackTrace(); //if there is an exception we put the empty root element ok = false; } //if there was a problem if (!ok) { rootElement = (Element) instanceElement.appendChild(xForm.createElement(_rootTagName)); } } else if (_instanceMode == AbstractSchemaFormBuilder.INSTANCE_MODE_HREF) //add the xlink:href attribute { instanceElement.setAttributeNS(SchemaFormBuilder.XLINK_NS, this.getXLinkNSPrefix() + "href", _instanceHref); } Element formContentWrapper = _wrapper.createGroupContentWrapper(formSection); addElement(xForm, modelSection, formContentWrapper, rootElementDecl, rootElementDecl.getTypeDefinition(), "/" + getElementName(rootElementDecl, xForm)); Element submitInfoElement = (Element) modelSection .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "submission")); //submitInfoElement.setAttributeNS(XFORMS_NS,getXFormsNSPrefix()+"id","save"); String submissionId = this.setXFormsId(submitInfoElement); //action if (_action == null) { submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "action", ""); } else { submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "action", _action); } //method if ((_submitMethod != null) && !_submitMethod.equals("")) { submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "method", _submitMethod); } else { //default is "post" submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "method", AbstractSchemaFormBuilder.SUBMIT_METHOD_POST); } //Element submitButton = (Element) formSection.appendChild(xForm.createElementNS(XFORMS_NS,getXFormsNSPrefix()+"submit")); Element submitButton = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "submit"); Element submitControlWrapper = _wrapper.createControlsWrapper(submitButton); formContentWrapper.appendChild(submitControlWrapper); submitButton.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "submission", submissionId); this.setXFormsId(submitButton); Element submitButtonCaption = (Element) submitButton .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "label")); submitButtonCaption.appendChild(xForm.createTextNode("Submit")); this.setXFormsId(submitButtonCaption); return xForm; } catch (ParserConfigurationException x) { throw new FormBuilderException(x); } catch (java.lang.ClassNotFoundException x) { throw new FormBuilderException(x); } catch (java.lang.InstantiationException x) { throw new FormBuilderException(x); } catch (java.lang.IllegalAccessException x) { throw new FormBuilderException(x); } }
From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java
protected String setXFormsId(Element el) { //remove the eventuel "id" attribute if (el.hasAttributeNS(SchemaFormBuilder.XFORMS_NS, "id")) { el.removeAttributeNS(SchemaFormBuilder.XFORMS_NS, "id"); }/*from w ww . java 2 s. co m*/ //long count=this.incIdCounter(); long count = 0; String name = el.getLocalName(); Long l = (Long) counter.get(name); if (l != null) { count = l.longValue(); } String id = name + "_" + count; //increment the counter counter.put(name, new Long(count + 1)); el.setAttributeNS(SchemaFormBuilder.XFORMS_NS, this.getXFormsNSPrefix() + "id", id); return id; }
From source file:org.chiba.xml.xforms.CustomElementFactory.java
public boolean isCustomActionElement(Element element) throws XFormsException { if (this.noCustomElements) { //no custom elements configured return false; }// www. j a v a 2s . c om //key to search the Map for a custom element String key = getKeyForElement(element); if (ACTIONS_ELEMENTS.containsKey(key)) { //a match was found return true; } //if the element is not recognized but it has a //mustUnderstand attribute, throw an exception to //signal error according to the spec if (element.hasAttributeNS(NamespaceConstants.XFORMS_NS, MUST_UNDERSTAND_ATTRIBUTE)) { String elementId = element.getPrefix() + ":" + element.getLocalName(); throw new XFormsException("MustUnderstand Module failure at element " + elementId); } //no matching configuration was found return false; }
From source file:org.chiba.xml.xforms.Model.java
private void loadInlineSchemas(List list) throws XFormsException { String schemaId = null;//from w w w . j a v a 2 s . c om try { NodeList children = this.element.getChildNodes(); for (int index = 0; index < children.getLength(); index++) { Node child = children.item(index); if (Node.ELEMENT_NODE == child.getNodeType() && NamespaceCtx.XMLSCHEMA_NS.equals(child.getNamespaceURI())) { Element element = (Element) child; schemaId = element.hasAttributeNS(null, "id") ? element.getAttributeNS(null, "id") : element.getNodeName(); XSModel schema = loadSchema(element); if (schema == null) { throw new NullPointerException("resource not found"); } list.add(schema); } } } catch (Exception e) { throw new XFormsLinkException("could not load inline schema", this.target, schemaId); } }