List of usage examples for org.w3c.dom Element lookupNamespaceURI
public String lookupNamespaceURI(String prefix);
From source file:Main.java
/** * Obtains the list of child elements with the specified tag name * inside the specific namespace./*ww w.j a va 2 s .c om*/ * * @param element the root element. * @param namespace the child namespace name. * @param tagName the child tag name. * @return the child element list. */ public static List<Element> getChildElements(final Element element, final String namespace, final String tagName) { final List<Element> elements = getElementList(element); final int numElements = elements.size(); final List<Element> childElements = new ArrayList<Element>(); for (int i = 0; i < numElements; i++) { final Element childElement = elements.get(i); String childTagName = childElement.getTagName(); final String childPrefix = childElement.getPrefix(); final String childNamespace = (childPrefix != null ? childElement.lookupNamespaceURI(childPrefix) : null); if (namespace != null) { if (!namespace.equals(childNamespace)) { continue; } else { childTagName = childElement.getLocalName(); } } if (!childTagName.equals(tagName)) { continue; } childElements.add(childElement); } return childElements; }
From source file:Main.java
/** * Obtains the first child element with the specified name inside * the specified namespace./*from w w w . j a v a 2 s .c o m*/ * * @param element the root element. * @param namespace the namespace of the child element. * @param tagName the child local name. * @return the child element. */ public static Element getChildElement(final Element element, final String namespace, final String tagName) { final NodeList childNodes = element.getChildNodes(); final int numChildren = childNodes.getLength(); for (int i = 0; i < numChildren; i++) { final Node childNode = childNodes.item(i); if (childNode.getNodeType() != Node.ELEMENT_NODE) { continue; } final Element childElement = (Element) childNode; String childTagName = childElement.getTagName(); final String childPrefix = childElement.getPrefix(); final String childNamespace = (childPrefix != null ? childElement.lookupNamespaceURI(childPrefix) : null); if (namespace != null) { if (!namespace.equals(childNamespace)) { continue; } else { childTagName = childElement.getLocalName(); } } if (!childTagName.equals(tagName)) { continue; } return childElement; } return null; }
From source file:com.evolveum.midpoint.util.DOMUtil.java
/** * @param element Element, on which the namespace declaration is evaluated * @param namespaceUri Namespace URI to be assigned to a prefix * @param preferredPrefix Preferred prefix * @param definitionElement Element, on which namespace declaration will be created (there should not be any redefinitions between definitionElement and element in order for this to work...) * @param allowUseOfDefaultNamespace If we are allowed to use default namespace (i.e. return empty prefix). This is important for QNames, see setQNameValue * @return prefix that is really used//from w w w. ja va2s.com * * Returned prefix is never null nor "" if allowUseOfDefaultNamespace is false. */ public static String lookupOrCreateNamespaceDeclaration(Element element, String namespaceUri, String preferredPrefix, Element definitionElement, boolean allowUseOfDefaultNamespace) { // We need to figure out correct prefix. We have namespace URI, but we // need a prefix to specify in the xsi:type or element name if (!StringUtils.isBlank(preferredPrefix)) { String namespaceForPreferredPrefix = element.lookupNamespaceURI(preferredPrefix); if (namespaceForPreferredPrefix == null) { // preferred prefix is not yet bound setNamespaceDeclaration(definitionElement, preferredPrefix, namespaceUri); return preferredPrefix; } else { if (namespaceForPreferredPrefix.equals(namespaceUri)) { return preferredPrefix; } else { // Prefix conflict, we need to create different prefix // Just going on will do that } } } if (allowUseOfDefaultNamespace && element.isDefaultNamespace(namespaceUri)) { // Namespace URI is a default namespace. Return empty prefix; return ""; } // We DO NOT WANT to use default namespace for QNames. QNames without prefix are NOT considered by midPoint to belong to the default namespace. String prefix = element.lookupPrefix(namespaceUri); if (prefix == null) { // generate random prefix boolean gotIt = false; for (int i = 0; i < RANDOM_ATTR_PREFIX_MAX_ITERATIONS; i++) { prefix = generatePrefix(); if (element.lookupNamespaceURI(prefix) == null) { // the prefix is free gotIt = true; break; } } if (!gotIt) { throw new IllegalStateException("Unable to generate unique prefix for namespace " + namespaceUri + " even after " + RANDOM_ATTR_PREFIX_MAX_ITERATIONS + " attempts"); } setNamespaceDeclaration(definitionElement, prefix, namespaceUri); } return prefix; }
From source file:org.callimachusproject.rdfa.test.RDFaGenerationTest.java
XPathExpression conjoinXPaths(Document fragment, String base) throws Exception { String path = "//*"; final Element e = fragment.getDocumentElement(); if (e == null) return null; final XPathIterator conjunction = new XPathIterator(e, base); if (conjunction.hasNext()) { path += "["; boolean first = true; while (conjunction.hasNext()) { if (!first) path += " and "; XPathExpression x = conjunction.next(); String exp = x.toString(); boolean positive = true; if (exp.startsWith("-")) { positive = false;//from w w w. j av a2 s . c o m exp = exp.substring(1); } // remove the initial '/' exp = exp.substring(1); if (positive) path += exp; else path += "not(" + exp + ")"; first = false; } path += "]"; } XPath xpath = xPathFactory.newXPath(); // add namespace prefix resolver to the xpath based on the current element xpath.setNamespaceContext(new AbstractNamespaceContext() { public String getNamespaceURI(String prefix) { // for the empty prefix lookup the default namespace if (prefix.isEmpty()) return e.lookupNamespaceURI(null); for (int i = 0; i < conjunction.contexts.size(); i++) { NamespaceContext c = conjunction.contexts.get(i); String ns = c.getNamespaceURI(prefix); if (ns != null) return ns; } return null; } }); final String exp = path; final XPathExpression compiled = xpath.compile(path); if (verbose) System.out.println(exp); return new XPathExpression() { public String evaluate(Object source) throws XPathExpressionException { return compiled.evaluate(source); } public String evaluate(InputSource source) throws XPathExpressionException { return compiled.evaluate(source); } public Object evaluate(Object source, QName returnType) throws XPathExpressionException { return compiled.evaluate(source, returnType); } public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException { return compiled.evaluate(source, returnType); } public String toString() { return exp; } }; }
From source file:org.apache.cxf.tools.wsdlto.frontend.jaxws.customization.JAXWSBindingParser.java
void parseElement(JAXWSBinding jaxwsBinding, Element element) { Node child = element.getFirstChild(); if (child == null) { // global binding if (isAsyncElement(element)) { jaxwsBinding.setEnableAsyncMapping(getNodeValue(element)); }/*from ww w .j a va 2s. c om*/ if (isMIMEElement(element)) { jaxwsBinding.setEnableMime(getNodeValue(element)); } if (isPackageElement(element)) { jaxwsBinding.setPackage(getPackageName(element)); } if (isWrapperStyle(element)) { jaxwsBinding.setEnableWrapperStyle(getNodeValue(element)); } } else { // other binding while (child != null) { if (isAsyncElement(child)) { jaxwsBinding.setEnableAsyncMapping(getNodeValue(child)); } else if (isMIMEElement(child)) { jaxwsBinding.setEnableMime(getNodeValue(child)); } else if (isWrapperStyle(child)) { jaxwsBinding.setEnableWrapperStyle(getNodeValue(child)); } else if (isPackageElement(child)) { jaxwsBinding.setPackage(getPackageName(child)); Node docChild = DOMUtils.getChild(child, Element.ELEMENT_NODE); if (docChild != null && this.isJAXWSClassDoc(docChild)) { jaxwsBinding.setPackageJavaDoc(StringEscapeUtils.escapeHtml(DOMUtils.getContent(docChild))); } } else if (isJAXWSMethodElement(child)) { jaxwsBinding.setMethodName(getMethodName(child)); Node docChild = DOMUtils.getChild(child, Element.ELEMENT_NODE); if (docChild != null && this.isJAXWSClassDoc(docChild)) { jaxwsBinding.setMethodJavaDoc(StringEscapeUtils.escapeHtml(DOMUtils.getContent(docChild))); } } else if (isJAXWSParameterElement(child)) { Element childElement = (Element) child; String partPath = "//" + childElement.getAttribute("part"); Node node = queryXPathNode(element.getOwnerDocument().getDocumentElement(), partPath); String messageName = ""; String partName = ""; if (node != null) { partName = ((Element) node).getAttribute("name"); Node messageNode = node.getParentNode(); if (messageNode != null) { Element messageEle = (Element) messageNode; messageName = messageEle.getAttribute("name"); } } String name = childElement.getAttribute("name"); String elementNameString = childElement.getAttribute("childElementName"); QName elementName = null; if (!StringUtils.isEmpty(elementNameString)) { String ns = ""; if (elementNameString.indexOf(':') != -1) { ns = elementNameString.substring(0, elementNameString.indexOf(':')); ns = childElement.lookupNamespaceURI(ns); elementNameString = elementNameString.substring(elementNameString.indexOf(':') + 1); } elementName = new QName(ns, elementNameString); } JAXWSParameter jpara = new JAXWSParameter(messageName, partName, elementName, name); jaxwsBinding.addJaxwsPara(jpara); } else if (isJAXWSClass(child)) { Element childElement = (Element) child; String clzName = childElement.getAttribute("name"); String javadoc = ""; Node docChild = DOMUtils.getChild(child, Element.ELEMENT_NODE); if (docChild != null && this.isJAXWSClassDoc(docChild)) { javadoc = StringEscapeUtils.escapeHtml(DOMUtils.getContent(docChild)); } JAXWSClass jaxwsClass = new JAXWSClass(clzName, javadoc); jaxwsBinding.setJaxwsClass(jaxwsClass); } child = child.getNextSibling(); } } }
From source file:org.apache.shindig.gadgets.rewrite.TemplateRewriter.java
/** * Register templates with a "tag" attribute. *///from ww w.j a v a2 s. co m private TagRegistry registerCustomTags(List<Element> allTemplates) { ImmutableSet.Builder<TagHandler> handlers = ImmutableSet.builder(); for (Element template : allTemplates) { // Only process templates with a tag attribute if (template.getAttribute("tag").length() == 0) { continue; } String[] nameParts = StringUtils.splitPreserveAllTokens(template.getAttribute("tag"), ':'); // At this time, we only support if (nameParts.length != 2) { continue; } String namespaceUri = template.lookupNamespaceURI(nameParts[0]); if (namespaceUri != null) { handlers.add(new TemplateBasedTagHandler(template, namespaceUri, nameParts[1])); } } return new DefaultTagRegistry(handlers.build()); }
From source file:org.apache.shindig.gadgets.templates.XmlTemplateLibrary.java
private TagHandler createHandler(String tagName, Element template, Set<TemplateResource> resources) throws TemplateParserException { String[] nameParts = StringUtils.splitPreserveAllTokens(tagName, ':'); // At this time, we only support namespaced tags if (nameParts.length != 2) { return null; }/*from w ww.ja v a 2s. co m*/ String namespaceUri = template.lookupNamespaceURI(nameParts[0]); if (!nsPrefix.equals(nameParts[0]) || !nsUri.equals(namespaceUri)) { throw new TemplateParserException("Can't create tags in undeclared namespace: " + nameParts[0]); } if (isSafe()) { bypassTemplateSanitization(template); } return new LibraryTagHandler(createTagHandler(template, namespaceUri, nameParts[1]), resources); }
From source file:org.kalypsodeegree.xml.XMLTools.java
/** * @param name/* w w w . j ava2 s .c o m*/ * @param namespace * @param node */ public static QName getQNameValue(final Element element) { if (element == null) return null; final String value = getValue(element); if (StringUtils.isBlank(value)) return null; // hack to build a qName from string presentation (QName.toString()) // this is needed as the XML-SchemaType is still xs:string and not xs:QName // according to Markus U. Mller (OGC SLD-Editor) this will change in the next version in SLD Standard final int pos = value.indexOf('}'); if (value.startsWith("{") && pos > 0) return QName.valueOf(value); QName prefixedName = parsePrefixedQName(value); String prefix = prefixedName.getPrefix(); final String namespaceURI = element.lookupNamespaceURI(prefix); return new QName(namespaceURI, prefixedName.getLocalPart(), prefix); }
From source file:org.lilyproject.indexer.model.indexerconf.LilyIndexerConfBuilder.java
private void buildRecordFilter() throws Exception { IndexRecordFilter recordFilter = new IndexRecordFilter(); List<Element> includes = RECORD_INCLUDE_FILTERS.get().evalAsNativeElementList(doc); for (Element includeEl : includes) { RecordMatcher recordMatcher = parseRecordMatcher(includeEl); String vtagsSpec = DocumentHelper.getAttribute(includeEl, "vtags", true); Set<SchemaId> vtags = parseVersionTags(vtagsSpec); recordFilter.addInclude(recordMatcher, new IndexCase(vtags)); }// w w w . java2 s.c om List<Element> excludes = RECORD_EXCLUDE_FILTERS.get().evalAsNativeElementList(doc); for (Element excludeEl : excludes) { RecordMatcher recordMatcher = parseRecordMatcher(excludeEl); recordFilter.addExclude(recordMatcher); } // This is for backwards compatibility: previously, <recordFilter> was called <records> and didn't have // excludes. This syntax was deprecated in 2.0. List<Element> cases = INDEX_CASES.get().evalAsNativeElementList(doc); for (Element caseEl : cases) { WildcardPattern matchNamespace = null; WildcardPattern matchName = null; String matchNamespaceAttr = DocumentHelper.getAttribute(caseEl, "matchNamespace", false); if (matchNamespaceAttr != null) { // If the matchNamespace attr does not contain a wildcard expression, and its value // happens to be an existing namespace prefix, than substitute the prefix for the full URI. if (!WildcardPattern.isWildcardExpression(matchNamespaceAttr)) { String uri = caseEl.lookupNamespaceURI(matchNamespaceAttr); if (uri != null) { matchNamespaceAttr = uri; } } matchNamespace = new WildcardPattern(matchNamespaceAttr); } String matchNameAttr = DocumentHelper.getAttribute(caseEl, "matchName", false); if (matchNameAttr != null) { matchName = new WildcardPattern(matchNameAttr); } String vtagsSpec = DocumentHelper.getAttribute(caseEl, "vtags", false); Map<String, String> varPropsPattern = parseVariantPropertiesPattern(caseEl, "matchVariant"); Set<SchemaId> vtags = parseVersionTags(vtagsSpec); RecordMatcher recordMatcher = new RecordMatcher(matchNamespace, matchName, null, null, null, null, varPropsPattern, null, typeManager); recordFilter.addInclude(recordMatcher, new IndexCase(vtags)); } conf.setRecordFilter(recordFilter); }
From source file:org.lilyproject.indexer.model.indexerconf.LilyIndexerConfBuilder.java
private void buildDynamicFields() throws Exception { List<Element> fields = DYNAMIC_INDEX_FIELDS.get().evalAsNativeElementList(doc); for (Element fieldEl : fields) { String matchNamespaceAttr = DocumentHelper.getAttribute(fieldEl, "matchNamespace", false); String matchNameAttr = DocumentHelper.getAttribute(fieldEl, "matchName", false); String matchTypeAttr = DocumentHelper.getAttribute(fieldEl, "matchType", false); String matchScopeAttr = DocumentHelper.getAttribute(fieldEl, "matchScope", false); String nameAttr = DocumentHelper.getAttribute(fieldEl, "name", true); WildcardPattern matchNamespace = null; if (matchNamespaceAttr != null) { // If the matchNamespace attr does not contain a wildcard expression, and its value // happens to be an existing namespace prefix, than substitute the prefix for the full URI. if (!WildcardPattern.isWildcardExpression(matchNamespaceAttr)) { String uri = fieldEl.lookupNamespaceURI(matchNamespaceAttr); if (uri != null) { matchNamespaceAttr = uri; }/*from w w w . ja va2 s .c o m*/ } matchNamespace = new WildcardPattern(matchNamespaceAttr); } WildcardPattern matchName = null; if (matchNameAttr != null) { matchName = new WildcardPattern(matchNameAttr); } TypePattern matchTypes = null; if (matchTypeAttr != null) { matchTypes = new TypePattern(matchTypeAttr); } Set<Scope> matchScopes = null; if (matchScopeAttr != null) { matchScopes = EnumSet.noneOf(Scope.class); for (String scope : COMMA_SPLITTER.split(matchScopeAttr)) { matchScopes.add(Scope.valueOf(scope)); } if (matchScopes.isEmpty()) { matchScopes = null; } } // Be gentle to users of Lily 1.0 and warn them about attributes that are not supported anymore if (DocumentHelper.getAttribute(fieldEl, "matchMultiValue", false) != null) { log.warn( "The attribute matchMultiValue on dynamicField is not supported anymore, it will be ignored."); } if (DocumentHelper.getAttribute(fieldEl, "matchHierarchical", false) != null) { log.warn( "The attribute matchHierarchical on dynamicField is not supported anymore, it will be ignored."); } Set<String> variables = new HashSet<String>(); variables.add("namespace"); variables.add("name"); variables.add("type"); variables.add("baseType"); variables.add("nestedType"); variables.add("nestedBaseType"); variables.add("deepestNestedBaseType"); if (matchName != null && matchName.hasWildcard()) { variables.add("nameMatch"); } if (matchNamespace != null && matchNamespace.hasWildcard()) { variables.add("namespaceMatch"); } NameTemplate name; try { name = new NameTemplateParser().parse(fieldEl, nameAttr, new DynamicFieldNameTemplateValidator(variables)); } catch (NameTemplateException nte) { throw new IndexerConfException("Error in name template: " + nameAttr + " at " + LocationAttributes.getLocationString(fieldEl), nte); } boolean extractContent = DocumentHelper.getBooleanAttribute(fieldEl, "extractContent", false); String formatter = DocumentHelper.getAttribute(fieldEl, "formatter", false); if (formatter != null && !conf.getFormatters().hasFormatter(formatter)) { throw new IndexerConfException("Formatter does not exist: " + formatter + " at " + LocationAttributes.getLocationString(fieldEl)); } boolean continue_ = DocumentHelper.getBooleanAttribute(fieldEl, "continue", false); DynamicIndexField field = new DynamicIndexField(matchNamespace, matchName, matchTypes, matchScopes, name, extractContent, continue_, formatter); conf.addDynamicIndexField(field); } }