List of usage examples for org.w3c.dom Node getPrefix
public String getPrefix();
null
if it is unspecified. From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlFilterReader.java
private QName extractQName(Node node) { QName qname;/*from w w w . j ava2s .c o m*/ String localName = node.getLocalName(); if (localName == null) { qname = new QName(node.getNodeName()); } else { if (node.getPrefix() == null) { qname = new QName(node.getNamespaceURI(), localName); } else { qname = new QName(node.getNamespaceURI(), localName, node.getPrefix()); } } return qname; }
From source file:org.apache.ws.security.message.WSSecDKSign.java
protected Set getInclusivePrefixes(Element target, boolean excludeVisible) { Set result = new HashSet(); Node parent = target;/* ww w. j a va 2s. c o m*/ NamedNodeMap attributes; Node attribute; while (!(parent.getParentNode() instanceof Document)) { parent = parent.getParentNode(); attributes = parent.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { attribute = attributes.item(i); if (attribute.getNamespaceURI() != null && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) { if (attribute.getNodeName().equals("xmlns")) { result.add("#default"); } else { result.add(attribute.getLocalName()); } } } } if (excludeVisible == true) { attributes = target.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { attribute = attributes.item(i); if (attribute.getNamespaceURI() != null && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) { if (attribute.getNodeName().equals("xmlns")) { result.remove("#default"); } else { result.remove(attribute.getLocalName()); } } if (attribute.getPrefix() != null) { result.remove(attribute.getPrefix()); } } if (target.getPrefix() == null) { result.remove("#default"); } else { result.remove(target.getPrefix()); } } return result; }
From source file:org.apache.ws.security.message.WSSecSignature.java
protected Set getInclusivePrefixes(Element target, boolean excludeVisible) { Set result = new HashSet(); Node parent = target;//from www . j a v a 2 s . com while (!(parent.getParentNode() instanceof Document)) { parent = parent.getParentNode(); NamedNodeMap attributes = parent.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); if (attribute.getNamespaceURI() != null && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) { if (attribute.getNodeName().equals("xmlns")) { result.add("#default"); } else { result.add(attribute.getLocalName()); } } } } if (excludeVisible == true) { NamedNodeMap attributes = target.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); if (attribute.getNamespaceURI() != null && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) { if (attribute.getNodeName().equals("xmlns")) { result.remove("#default"); } else { result.remove(attribute.getLocalName()); } } if (attribute.getPrefix() != null) { result.remove(attribute.getPrefix()); } } if (target.getPrefix() == null) { result.remove("#default"); } else { result.remove(target.getPrefix()); } } return result; }
From source file:org.apache.ws.security.message.WSSecSignatureBase.java
/** * Get the List of inclusive prefixes from the DOM Element argument *///from w w w .ja v a2s .co m public List<String> getInclusivePrefixes(Element target, boolean excludeVisible) { List<String> result = new ArrayList<String>(); Node parent = target; while (parent.getParentNode() != null && !(Node.DOCUMENT_NODE == parent.getParentNode().getNodeType())) { parent = parent.getParentNode(); NamedNodeMap attributes = parent.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); if (WSConstants.XMLNS_NS.equals(attribute.getNamespaceURI())) { if ("xmlns".equals(attribute.getNodeName())) { result.add("#default"); } else { result.add(attribute.getLocalName()); } } } } if (excludeVisible) { NamedNodeMap attributes = target.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); if (WSConstants.XMLNS_NS.equals(attribute.getNamespaceURI())) { if ("xmlns".equals(attribute.getNodeName())) { result.remove("#default"); } else { result.remove(attribute.getLocalName()); } } if (attribute.getPrefix() != null) { result.remove(attribute.getPrefix()); } } if (target.getPrefix() == null) { result.remove("#default"); } else { result.remove(target.getPrefix()); } } return result; }
From source file:org.exist.dom.ElementImpl.java
private Node appendChild(Txn transaction, NodeId newNodeId, NodeImplRef last, NodePath lastPath, Node child, StreamListener listener) throws DOMException { if (last == null || last.getNode() == null) //TODO : same test as above ? -pb {/* w w w. j ava 2 s. c om*/ throw new DOMException(DOMException.INVALID_MODIFICATION_ERR, "invalid node"); } final DocumentImpl owner = (DocumentImpl) getOwnerDocument(); DBBroker broker = null; try { broker = ownerDocument.getBrokerPool().get(null); switch (child.getNodeType()) { case Node.DOCUMENT_FRAGMENT_NODE: appendChildren(transaction, newNodeId, null, last, lastPath, child.getChildNodes(), listener); return null; // TODO: implement document fragments so //we can return all newly appended children case Node.ELEMENT_NODE: // create new element final ElementImpl elem = new ElementImpl( new QName(child.getLocalName() == null ? child.getNodeName() : child.getLocalName(), child.getNamespaceURI(), child.getPrefix()), broker.getBrokerPool().getSymbols()); elem.setNodeId(newNodeId); elem.setOwnerDocument(owner); final NodeListImpl ch = new NodeListImpl(); final NamedNodeMap attribs = child.getAttributes(); int numActualAttribs = 0; for (int i = 0; i < attribs.getLength(); i++) { final Attr attr = (Attr) attribs.item(i); if (!attr.getNodeName().startsWith("xmlns")) { ch.add(attr); numActualAttribs++; } else { final String xmlnsDecl = attr.getNodeName(); final String prefix = xmlnsDecl.length() == 5 ? "" : xmlnsDecl.substring(6); elem.addNamespaceMapping(prefix, attr.getNodeValue()); } } final NodeList cl = child.getChildNodes(); for (int i = 0; i < cl.getLength(); i++) { final Node n = cl.item(i); if (n.getNodeType() != Node.ATTRIBUTE_NODE) { ch.add(n); } } elem.setChildCount(ch.getLength()); if (numActualAttribs != (short) numActualAttribs) { throw new DOMException(DOMException.INVALID_MODIFICATION_ERR, "Too many attributes"); } elem.setAttributes((short) numActualAttribs); lastPath.addComponent(elem.getQName()); // insert the node broker.insertNodeAfter(transaction, last.getNode(), elem); broker.indexNode(transaction, elem, lastPath); broker.getIndexController().indexNode(transaction, elem, lastPath, listener); elem.setChildCount(0); last.setNode(elem); //process child nodes elem.appendChildren(transaction, newNodeId.newChild(), null, last, lastPath, ch, listener); broker.endElement(elem, lastPath, null); broker.getIndexController().endElement(transaction, elem, lastPath, listener); lastPath.removeLastComponent(); return elem; case Node.TEXT_NODE: final TextImpl text = new TextImpl(newNodeId, ((Text) child).getData()); text.setOwnerDocument(owner); // insert the node broker.insertNodeAfter(transaction, last.getNode(), text); broker.indexNode(transaction, text, lastPath); broker.getIndexController().indexNode(transaction, text, lastPath, listener); last.setNode(text); return text; case Node.CDATA_SECTION_NODE: final CDATASectionImpl cdata = new CDATASectionImpl(newNodeId, ((CDATASection) child).getData()); cdata.setOwnerDocument(owner); // insert the node broker.insertNodeAfter(transaction, last.getNode(), cdata); broker.indexNode(transaction, cdata, lastPath); last.setNode(cdata); return cdata; case Node.ATTRIBUTE_NODE: final Attr attr = (Attr) child; final String ns = attr.getNamespaceURI(); final String prefix = (Namespaces.XML_NS.equals(ns) ? "xml" : attr.getPrefix()); String name = attr.getLocalName(); if (name == null) { name = attr.getName(); } final QName attrName = new QName(name, ns, prefix); final AttrImpl attrib = new AttrImpl(attrName, attr.getValue(), broker.getBrokerPool().getSymbols()); attrib.setNodeId(newNodeId); attrib.setOwnerDocument(owner); if (ns != null && attrName.compareTo(Namespaces.XML_ID_QNAME) == Constants.EQUAL) { // an xml:id attribute. Normalize the attribute and set its type to ID attrib.setValue(StringValue.trimWhitespace(StringValue.collapseWhitespace(attrib.getValue()))); attrib.setType(AttrImpl.ID); } else { attrName.setNameType(ElementValue.ATTRIBUTE); } broker.insertNodeAfter(transaction, last.getNode(), attrib); broker.indexNode(transaction, attrib, lastPath); broker.getIndexController().indexNode(transaction, attrib, lastPath, listener); last.setNode(attrib); return attrib; case Node.COMMENT_NODE: final CommentImpl comment = new CommentImpl(((Comment) child).getData()); comment.setNodeId(newNodeId); comment.setOwnerDocument(owner); // insert the node broker.insertNodeAfter(transaction, last.getNode(), comment); broker.indexNode(transaction, comment, lastPath); last.setNode(comment); return comment; case Node.PROCESSING_INSTRUCTION_NODE: final ProcessingInstructionImpl pi = new ProcessingInstructionImpl(newNodeId, ((ProcessingInstruction) child).getTarget(), ((ProcessingInstruction) child).getData()); pi.setOwnerDocument(owner); //insert the node broker.insertNodeAfter(transaction, last.getNode(), pi); broker.indexNode(transaction, pi, lastPath); last.setNode(pi); return pi; default: throw new DOMException(DOMException.INVALID_MODIFICATION_ERR, "Unknown node type: " + child.getNodeType() + " " + child.getNodeName()); } } catch (final EXistException e) { LOG.warn("Exception while appending node: " + e.getMessage(), e); } finally { if (broker != null) broker.release(); } return null; }
From source file:org.jbpm.bpel.xml.util.XmlUtil.java
public static void copyAttributes(Element target, Element source) { // easy way out: no attributes if (!source.hasAttributes()) return;//from w w w .j a v a2 s . c o m // traverse attributes NamedNodeMap attributes = source.getAttributes(); for (int i = 0, n = attributes.getLength(); i < n; i++) { Node sourceAttr = attributes.item(i); String namespaceURI = sourceAttr.getNamespaceURI(); String name = sourceAttr.getNodeName(); // namespace declaration? if (BpelConstants.NS_XMLNS.equals(namespaceURI)) continue; // unqualified? if (namespaceURI == null || namespaceURI.length() == 0) { target.setAttribute(name, sourceAttr.getNodeValue()); if (traceEnabled) log.trace("set attribute: " + name); } // qualified else { Attr targetAttr = target.getOwnerDocument().createAttributeNS(namespaceURI, name); targetAttr.setValue(sourceAttr.getNodeValue()); target.setAttributeNodeNS(targetAttr); ensureNamespaceDeclared(targetAttr, namespaceURI, sourceAttr.getPrefix()); if (traceEnabled) log.trace("set attribute: {" + namespaceURI + '}' + name); } } }
From source file:org.kisoonlineapp.XthmlCheckTest.java
/** * Huebsches String-Format fuer einen Node * * @param n/*from w w w. ja va 2 s. c o m*/ * @return human readable repr. of a Node */ private String formatNode(Node n) { final String SEP = "\n"; StringBuilder sb = new StringBuilder(); sb.append(n.getNodeName()).append(SEP).append(n.getNodeValue()).append(SEP).append(n.getNodeType()) .append(SEP).append(n.getBaseURI()).append(SEP).append(n.getLocalName()).append(SEP) .append(n.getNamespaceURI()).append(SEP).append(n.getPrefix()).append(SEP); String formatNode = sb.toString(); return formatNode; }
From source file:org.ojbc.bundles.adapters.staticmock.StaticMockQuery.java
private Document createFirearmRegistrationDocument(Document document, String firearmId) throws Exception { Document copy = createNewDocument(); copy.appendChild(copy.importNode(document.getDocumentElement(), true)); Node rootElement = XmlUtils.xPathNodeSearch(copy, "/*"); LOG.debug("Keeper: " + firearmId); NodeList otherFirearmNodes = XmlUtils.xPathNodeListSearch(rootElement, "firearm-ext:Firearm[@s:id != '" + firearmId + "']"); for (int i = 0; i < otherFirearmNodes.getLength(); i++) { Node goner = otherFirearmNodes.item(i); LOG.debug("Goner: " + XmlUtils.xPathStringSearch(goner, "@s:id")); rootElement.removeChild(goner);// w w w . j a va 2s . c o m } NodeList otherItemRegNodes = XmlUtils.xPathNodeListSearch(rootElement, "firearm-ext:ItemRegistration[@s:id != /firearm-doc:PersonFirearmRegistrationQueryResults/nc:PropertyRegistrationAssociation[nc:ItemReference/@s:ref='" + firearmId + "']/nc:ItemRegistrationReference/@s:ref]"); for (int i = 0; i < otherItemRegNodes.getLength(); i++) { rootElement.removeChild(otherItemRegNodes.item(i)); } NodeList otherRegAssociationNodes = XmlUtils.xPathNodeListSearch(rootElement, "nc:PropertyRegistrationAssociation[nc:ItemReference/@s:ref != '" + firearmId + "']"); for (int i = 0; i < otherRegAssociationNodes.getLength(); i++) { rootElement.removeChild(otherRegAssociationNodes.item(i)); } copy.renameNode(rootElement, rootElement.getNamespaceURI(), "FirearmRegistrationQueryResults"); Node documentRootElement = XmlUtils.xPathNodeSearch(document, "/*"); rootElement.setPrefix(documentRootElement.getPrefix()); return copy; }
From source file:org.opensingular.internal.lib.commons.xml.TestMElement.java
License:asdf
/** * Verifica se ambos os nos so iguais fazendo uma comparao em * profundidade.// w w w.jav a 2 s. c o m * * @param n1 - * @param n2 - * @throws Exception Se nbo forem iguais */ public static void isIgual(Node n1, Node n2) throws Exception { if (n1 == n2) { return; } isIgual(n1, n2, "NodeName", n1.getNodeName(), n2.getNodeName()); isIgual(n1, n2, "NodeValue", n1.getNodeValue(), n2.getNodeValue()); isIgual(n1, n2, "Namespace", n1.getNamespaceURI(), n2.getNamespaceURI()); isIgual(n1, n2, "Prefix", n1.getPrefix(), n2.getPrefix()); isIgual(n1, n2, "LocalName", n1.getLocalName(), n2.getLocalName()); if (isMesmaClasse(Element.class, n1, n2)) { Element e1 = (Element) n1; Element e2 = (Element) n2; //Verifica se possuem os mesmos atributos NamedNodeMap nn1 = e1.getAttributes(); NamedNodeMap nn2 = e2.getAttributes(); if (nn1.getLength() != nn2.getLength()) { fail("O nmero atributos em " + XPathToolkit.getFullPath(n1) + " (qtd=" + nn1.getLength() + " diferente de n2 (qtd=" + nn2.getLength() + ")"); } for (int i = 0; i < nn1.getLength(); i++) { isIgual((Attr) nn1.item(i), (Attr) nn2.item(i)); } //Verifica se possuem os mesmos filhos Node filho1 = e1.getFirstChild(); Node filho2 = e2.getFirstChild(); int count = 0; while ((filho1 != null) && (filho2 != null)) { isIgual(filho1, filho2); filho1 = filho1.getNextSibling(); filho2 = filho2.getNextSibling(); count++; } if (filho1 != null) { fail("H mais node [" + count + "] " + XPathToolkit.getNomeTipo(filho1) + " (" + XPathToolkit.getFullPath(filho1) + ") em n1:" + XPathToolkit.getFullPath(n1)); } if (filho2 != null) { fail("H mais node [" + count + "] " + XPathToolkit.getNomeTipo(filho2) + " (" + XPathToolkit.getFullPath(filho2) + ") em n2:" + XPathToolkit.getFullPath(n2)); } } else if (isMesmaClasse(Attr.class, n1, n2)) { //Ok } else if (isMesmaClasse(Text.class, n1, n2)) { //Ok } else { fail("Tipo de n " + n1.getClass() + " no tratado"); } }
From source file:org.pentaho.di.trans.steps.webservices.WebService.java
private void processRows(InputStream anXml, Object[] rowData, RowMetaInterface rowMeta, boolean ignoreNamespacePrefix, String encoding) throws KettleException { // Just to make sure the old transformations keep working... ////from w ww . ja v a 2 s . c om if (meta.isCompatible()) { compatibleProcessRows(anXml, rowData, rowMeta, ignoreNamespacePrefix, encoding); return; } // First we should get the complete string // The problem is that the string can contain XML or any other format such as HTML saying the service is no longer // available. // We're talking about a WEB service here. // As such, to keep the original parsing scheme, we first read the content. // Then we create an input stream from the content again. // It's elaborate, but that way we can report on the failure more correctly. // String response = readStringFromInputStream(anXml, encoding); try { // What is the expected response object for the operation? // DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(new InputSource(new StringReader(response))); Node envelopeNode = doc.getFirstChild(); String nsPrefix = envelopeNode.getPrefix(); Node bodyNode = XMLHandler.getSubNode(envelopeNode, nsPrefix + ":Body"); if (bodyNode == null) { XMLHandler.getSubNode(envelopeNode, nsPrefix + ":body"); // retry, just in case! } // Create a few objects to help do the layout of XML snippets we find along the way // Transformer transformer = null; try { Class<?> clazz = Class.forName("org.apache.xalan.processor.TransformerFactoryImpl"); TransformerFactory transformerFactory = (TransformerFactory) clazz.newInstance(); transformer = transformerFactory.newTransformer(); } catch (Throwable t) { TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformer = transformerFactory.newTransformer(); } transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); if (log.isDetailed()) { StringWriter bodyXML = new StringWriter(); transformer.transform(new DOMSource(bodyNode), new StreamResult(bodyXML)); logDetailed(bodyXML.toString()); } // The node directly below the body is the response node // It's apparently a hassle to get the name in a consistent way, but we know it's the first element node // Node responseNode = null; NodeList nodeList = null; if (!Const.isEmpty(meta.getRepeatingElementName())) { // We have specified the repeating element name : use it // nodeList = ((Element) bodyNode).getElementsByTagName(meta.getRepeatingElementName()); } else { if (meta.isReturningReplyAsString()) { // Just return the body node as an XML string... // StringWriter nodeXML = new StringWriter(); transformer.transform(new DOMSource(bodyNode), new StreamResult(nodeXML)); String xml = response; // nodeXML.toString(); Object[] outputRowData = createNewRow(rowData); int index = rowData == null ? 0 : getInputRowMeta().size(); outputRowData[index++] = xml; putRow(data.outputRowMeta, outputRowData); } else { // We just grab the list of nodes from the children of the body // Look for the first element node (first real child) and take that one. // For that child-element, we consider all the children below // NodeList responseChildren = bodyNode.getChildNodes(); for (int i = 0; i < responseChildren.getLength(); i++) { Node responseChild = responseChildren.item(i); if (responseChild.getNodeType() == Node.ELEMENT_NODE) { responseNode = responseChild; break; } } // See if we want the whole block returned as XML... // if (meta.getFieldsOut().size() == 1) { WebServiceField field = meta.getFieldsOut().get(0); if (field.getWsName().equals(responseNode.getNodeName())) { // Pass the data as XML // StringWriter nodeXML = new StringWriter(); transformer.transform(new DOMSource(responseNode), new StreamResult(nodeXML)); String xml = nodeXML.toString(); Object[] outputRowData = createNewRow(rowData); int index = rowData == null ? 0 : getInputRowMeta().size(); outputRowData[index++] = xml; putRow(data.outputRowMeta, outputRowData); } else { if (responseNode != null) { nodeList = responseNode.getChildNodes(); } } } else { if (responseNode != null) { nodeList = responseNode.getChildNodes(); } } } } // The section below is just for repeating nodes. If we don't have those it ends here. // if (nodeList == null || meta.isReturningReplyAsString()) { return; } // Allocate a result row in case we are dealing with a single result row // Object[] outputRowData = createNewRow(rowData); // Now loop over the node list found above... // boolean singleRow = false; int fieldsFound = 0; for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (meta.isReturningReplyAsString()) { // Just return the body node as an XML string... // StringWriter nodeXML = new StringWriter(); transformer.transform(new DOMSource(bodyNode), new StreamResult(nodeXML)); String xml = nodeXML.toString(); outputRowData = createNewRow(rowData); int index = rowData == null ? 0 : getInputRowMeta().size(); outputRowData[index++] = xml; putRow(data.outputRowMeta, outputRowData); } else { // This node either contains the data for a single row or it contains the first element of a single result // response // If we find the node name in out output result fields list, we are going to consider it a single row result. // WebServiceField field = meta.getFieldOutFromWsName(node.getNodeName(), ignoreNamespacePrefix); if (field != null) { if (getNodeValue(outputRowData, node, field, transformer, true)) { // We found a match. // This means that we are dealing with a single row // It also means that we need to update the output index pointer // singleRow = true; fieldsFound++; } } else { // If we didn't already get data in the previous block we'll assume multiple rows coming back. // if (!singleRow) { // Sticking with the multiple-results scenario... // // TODO: remove next 2 lines, added for debug reasons. // if (log.isDetailed()) { StringWriter nodeXML = new StringWriter(); transformer.transform(new DOMSource(node), new StreamResult(nodeXML)); logDetailed(BaseMessages.getString(PKG, "WebServices.Log.ResultRowDataFound", nodeXML.toString())); } // Allocate a new row... // outputRowData = createNewRow(rowData); // Let's see what's in there... // NodeList childNodes = node.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node childNode = childNodes.item(j); field = meta.getFieldOutFromWsName(childNode.getNodeName(), ignoreNamespacePrefix); if (field != null) { if (getNodeValue(outputRowData, childNode, field, transformer, false)) { // We found a match. // This means that we are dealing with a single row // It also means that we need to update the output index pointer // fieldsFound++; } } } // Prevent empty rows from being sent out. // if (fieldsFound > 0) { // Send a row in a series of rows on its way. // putRow(data.outputRowMeta, outputRowData); } } } } } if (singleRow && fieldsFound > 0) { // Send the single row on its way. // putRow(data.outputRowMeta, outputRowData); } } catch (Exception e) { throw new KettleStepException( BaseMessages.getString(PKG, "WebServices.ERROR0010.OutputParsingError", response.toString()), e); } }