List of usage examples for org.w3c.dom Node getAttributes
public NamedNodeMap getAttributes();
NamedNodeMap
containing the attributes of this node (if it is an Element
) or null
otherwise. From source file:Main.java
private static Node copyNodeExceptNamespace(Document document, Node srcNode, Set<String> namespace, List<String> exceptNamespaces) { if (srcNode.getNodeType() == Node.ELEMENT_NODE) { String nodeName = srcNode.getNodeName(); nodeName = nodeName.substring(nodeName.indexOf(":") + 1); Element element = document.createElement(nodeName); for (int i = 0; i < srcNode.getAttributes().getLength(); i++) { Attr attr = (Attr) srcNode.getAttributes().item(i); String name = attr.getName(); if (name.startsWith("xmlns:")) { String suffix = name.substring(6); if (!exceptNamespaces.contains(suffix)) { namespace.add(suffix); }// w ww . j av a 2 s. c o m continue; } } for (int i = 0; i < srcNode.getAttributes().getLength(); i++) { Attr attr = (Attr) srcNode.getAttributes().item(i); String name = attr.getName(); if (name.startsWith("xmlns:")) { continue; } int semi = name.indexOf(":"); if (semi > 0) { if (namespace.contains(name.substring(0, semi))) { name = name.substring(semi + 1); } } element.setAttribute(name, attr.getValue()); } NodeList nodeList = srcNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node childNode = nodeList.item(i); if (childNode.getNodeType() == Node.TEXT_NODE) { element.appendChild(document.createTextNode(childNode.getTextContent())); } else if (childNode.getNodeType() == Node.ELEMENT_NODE) { Node node = copyNodeExceptNamespace(document, childNode, namespace, exceptNamespaces); element.appendChild(node); } } return element; } if (srcNode.getNodeType() == Node.TEXT_NODE) { Text text = document.createTextNode(srcNode.getTextContent()); return text; } return null; }
From source file:Main.java
private static String prettyPrintDom(Node node, String indent, boolean isRoot, boolean escapeStrings) { String ret = ""; switch (node.getNodeType()) { case Node.DOCUMENT_NODE: // recurse on each child NodeList nodes = node.getChildNodes(); if (nodes != null) { for (int i = 0; i < nodes.getLength(); i++) { ret += prettyPrintDom(nodes.item(i), indent, isRoot, escapeStrings); }/* w w w . ja va2 s . c o m*/ } break; case Node.ELEMENT_NODE: String name = node.getNodeName(); ret += indent + "<" + name; NamedNodeMap attributes = node.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node current = attributes.item(i); ret += " " + current.getNodeName() + "=\"" + ((escapeStrings) ? escapeStringForXML(current.getNodeValue()) : current.getNodeValue()) + "\""; } ret += ">"; // recurse on each child NodeList children = node.getChildNodes(); if (children != null) { for (int i = 0; i < children.getLength(); i++) { String tmp = prettyPrintDom(children.item(i), indent + ((isRoot) ? "" : BI), false, escapeStrings); if (!tmp.replaceAll("[\\s]+", "").equals("")) if (tmp.endsWith("\n")) if (ret.endsWith("\n")) ret += tmp; else ret += "\n" + tmp; else ret += tmp; } } if (ret.endsWith("\n")) ret += indent + "</" + name + ">\n"; else ret += "</" + name + ">\n"; break; case Node.TEXT_NODE: ret += (escapeStrings) ? escapeStringForXML(node.getNodeValue()) : node.getNodeValue(); break; case Node.COMMENT_NODE: ret += "<!-- " + node.getNodeValue() + " -->"; break; } return ret; }
From source file:com.connexta.arbitro.attr.xacml3.AttributeSelector.java
/** * Creates a new <code>AttributeSelector</code> based on the DOM root of the XML type. Note that * as of XACML 1.1 the XPathVersion element is required in any policy that uses a selector, so * if the <code>xpathVersion</code> string is null, then this will throw an exception. * * @param root the root of the DOM tree for the XML AttributeSelectorType XML type * @param metaData the meta-data associated with the containing policy * * @return an <code>AttributeSelector</code> * * @throws ParsingException if the AttributeSelectorType was invalid *///from w ww.j av a 2 s . c o m public static AttributeSelector getInstance(Node root, PolicyMetaData metaData) throws ParsingException { URI category = null; URI type = null; URI contextSelectorId = null; String path = null; boolean mustBePresent = false; String xpathVersion = metaData.getXPathIdentifier(); // make sure we were given an xpath version if (xpathVersion == null) { throw new ParsingException("An XPathVersion is required for " + "any policies that use selectors"); } NamedNodeMap attrs = root.getAttributes(); try { // there's always a DataType attribute category = new URI(attrs.getNamedItem("Category").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required Category " + "attribute in AttributeSelector", e); } try { // there's always a DataType attribute type = new URI(attrs.getNamedItem("DataType").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required DataType " + "attribute in AttributeSelector", e); } try { // there's always a RequestPath path = attrs.getNamedItem("Path").getNodeValue(); } catch (Exception e) { throw new ParsingException("Error parsing required " + "Path attribute in " + "AttributeSelector", e); } try { String stringValue = attrs.getNamedItem("MustBePresent").getNodeValue(); mustBePresent = Boolean.parseBoolean(stringValue); } catch (Exception e) { throw new ParsingException("Error parsing required MustBePresent attribute " + "in AttributeSelector", e); } try { Node node = attrs.getNamedItem("ContextSelectorId"); if (node != null) { contextSelectorId = new URI(node.getNodeValue()); } } catch (Exception e) { throw new ParsingException("Error parsing required MustBePresent attribute " + "in AttributeSelector", e); } return new AttributeSelector(category, type, contextSelectorId, path, mustBePresent, xpathVersion); }
From source file:ch.entwine.weblounge.common.impl.util.config.ConfigurationUtils.java
/** * Returns <code>true</code> if the node contains an attribute named * <tt>default</tt> with a value that corresponds to any of: * <ul>/*w w w . j av a2 s . c o m*/ * <li>true</li> * <li>on</li> * <li>yes</li> * </ul> * * @param value * the value to test * @return <code>true</code> if the value can be interpreted as * <code>true</code> */ public static boolean isDefault(Node node) { if (node == null) return false; Node defaultAttribute = node.getAttributes().getNamedItem("default"); if (defaultAttribute == null || defaultAttribute.getNodeValue() == null) return false; return isTrue(defaultAttribute.getNodeValue()); }
From source file:com.connexta.arbitro.attr.AttributeSelector.java
/** * Creates a new <code>AttributeSelector</code> based on the DOM root of the XML type. Note that * as of XACML 1.1 the XPathVersion element is required in any policy that uses a selector, so * if the <code>xpathVersion</code> string is null, then this will throw an exception. * // w ww. jav a 2 s. c o m * @param root the root of the DOM tree for the XML AttributeSelectorType XML type * @param metaData the meta-data associated with the containing policy * * @return an <code>AttributeSelector</code> * * @throws ParsingException if the AttributeSelectorType was invalid */ public static AttributeSelector getInstance(Node root, PolicyMetaData metaData) throws ParsingException { URI type = null; String contextPath = null; boolean mustBePresent = false; String xpathVersion = metaData.getXPathIdentifier(); // make sure we were given an xpath version if (xpathVersion == null) throw new ParsingException("An XPathVersion is required for " + "any policies that use selectors"); NamedNodeMap attrs = root.getAttributes(); try { // there's always a DataType attribute type = new URI(attrs.getNamedItem("DataType").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required DataType " + "attribute in AttributeSelector", e); } try { // there's always a RequestPath contextPath = attrs.getNamedItem("RequestContextPath").getNodeValue(); } catch (Exception e) { throw new ParsingException( "Error parsing required " + "RequestContextPath attribute in " + "AttributeSelector", e); } try { // there may optionally be a MustBePresent Node node = attrs.getNamedItem("MustBePresent"); if (node != null) if (node.getNodeValue().equals("true")) mustBePresent = true; } catch (Exception e) { // this shouldn't happen, since we check the cases, but still... throw new ParsingException("Error parsing optional attributes " + "in AttributeSelector", e); } // as of 1.2 we need the root element of the policy so we can get // the namespace mapping, but in order to leave the APIs unchanged, // we'll walk up the tree to find the root rather than pass this // element around through all the code Node policyRoot = null; Node node = root.getParentNode(); while ((node != null) && (node.getNodeType() == Node.ELEMENT_NODE)) { policyRoot = node; node = node.getParentNode(); } // create the new selector return new AttributeSelector(type, contextPath, policyRoot, mustBePresent, xpathVersion); }
From source file:ch.entwine.weblounge.common.impl.content.page.PageletRendererImpl.java
/** * Initializes this pagelet renderer from an XML node that was generated using * {@link #toXml()}./* ww w.j a v a 2 s . c o m*/ * * @param node * the pagelet renderer node * @param xpath * the xpath processor * @throws IllegalStateException * if the pagelet renderer cannot be parsed * @see #fromXml(Node) * @see #toXml() */ public static PageletRenderer fromXml(Node node, XPath xpath) throws IllegalStateException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // Identifier String id = XPathHelper.valueOf(node, "@id", xpath); if (id == null) throw new IllegalStateException("Missing id in page template definition"); // Class String className = XPathHelper.valueOf(node, "m:class", xpath); // Create the pagelet renderer PageletRenderer renderer = null; if (className != null) { Class<? extends PageletRenderer> c = null; try { c = (Class<? extends PageletRenderer>) classLoader.loadClass(className); renderer = c.newInstance(); renderer.setIdentifier(id); } catch (ClassNotFoundException e) { throw new IllegalStateException( "Implementation " + className + " for pagelet renderer '" + id + "' not found", e); } catch (InstantiationException e) { throw new IllegalStateException( "Error instantiating impelementation " + className + " for pagelet renderer '" + id + "'", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Access violation instantiating implementation " + className + " for pagelet renderer '" + id + "'", e); } catch (Throwable t) { throw new IllegalStateException( "Error loading implementation " + className + " for pagelet renderer '" + id + "'", t); } } else { renderer = new PageletRendererImpl(); renderer.setIdentifier(id); } // Renderer url NodeList rendererUrlNodes = XPathHelper.selectList(node, "m:renderer", xpath); if (rendererUrlNodes.getLength() == 0) throw new IllegalStateException("Missing renderer in page template definition"); for (int i = 0; i < rendererUrlNodes.getLength(); i++) { Node rendererUrlNode = rendererUrlNodes.item(i); URL rendererUrl = null; Node typeNode = rendererUrlNode.getAttributes().getNamedItem("type"); String type = (typeNode != null) ? typeNode.getNodeValue() : RendererType.Page.toString(); try { rendererUrl = new URL(rendererUrlNode.getFirstChild().getNodeValue()); renderer.addRenderer(rendererUrl, type); } catch (MalformedURLException e) { throw new IllegalStateException( "Malformed renderer url in page template definition: " + rendererUrlNode); } } // Composeable renderer.setComposeable("true".equals(XPathHelper.valueOf(node, "@composeable", xpath))); // Preview mode String previewMode = XPathHelper.valueOf(node, "m:preview", xpath); if (previewMode != null) renderer.setPreviewMode(PagePreviewMode.parse(previewMode)); // Editor url String editorUrlNode = XPathHelper.valueOf(node, "m:editor", xpath); try { if (editorUrlNode != null) { URL editorUrl = new URL(editorUrlNode); renderer.setEditor(editorUrl); } } catch (MalformedURLException e) { throw new IllegalStateException("Malformed editor url in page template definition: " + editorUrlNode); } // client revalidation time String recheck = XPathHelper.valueOf(node, "m:recheck", xpath); if (recheck != null) { try { renderer.setClientRevalidationTime(ConfigurationUtils.parseDuration(recheck)); } catch (NumberFormatException e) { throw new IllegalStateException( "The pagelet renderer revalidation time is malformed: '" + recheck + "'"); } catch (IllegalArgumentException e) { throw new IllegalStateException( "The pagelet renderer revalidation time is malformed: '" + recheck + "'"); } } // cache expiration time String valid = XPathHelper.valueOf(node, "m:valid", xpath); if (valid != null) { try { renderer.setCacheExpirationTime(ConfigurationUtils.parseDuration(valid)); } catch (NumberFormatException e) { throw new IllegalStateException("The pagelet renderer valid time is malformed: '" + valid + "'", e); } catch (IllegalArgumentException e) { throw new IllegalStateException("The pagelet renderer valid time is malformed: '" + valid + "'", e); } } // name String name = XPathHelper.valueOf(node, "m:name", xpath); renderer.setName(name); // scripts NodeList scripts = XPathHelper.selectList(node, "m:includes/m:script", xpath); for (int i = 0; i < scripts.getLength(); i++) { renderer.addHTMLHeader(ScriptImpl.fromXml(scripts.item(i))); } // links NodeList includes = XPathHelper.selectList(node, "m:includes/m:link", xpath); for (int i = 0; i < includes.getLength(); i++) { renderer.addHTMLHeader(LinkImpl.fromXml(includes.item(i))); } return renderer; }
From source file:com.bcmcgroup.flare.client.ClientUtil.java
/** * Obtain the STIX version from the Content_Binding urn * * @param node Content_Binding node// ww w .ja v a 2s. co m * @return a String containing the STIX version * @throws DOMException DOM operations only raise exceptions in "exceptional" circumstances, i.e., when an operation * is impossible to perform (either for logical reasons, because data is lost, or because the implementation has become unstable). * <a href="https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/DOMException.html">Reference to Oracle Documentation.</a> * */ private static String getStixVersion(Node node) throws DOMException { try { String urnStr = ""; if (node.hasAttributes()) { Attr attr = (Attr) node.getAttributes().getNamedItem("binding_id"); if (attr != null) { urnStr = attr.getValue(); } } if (urnStr.isEmpty()) { urnStr = node.getTextContent(); } if (urnStr != null && !urnStr.isEmpty()) { int lastIndex = urnStr.lastIndexOf(":"); String version = ""; if (lastIndex >= 0) { version = urnStr.substring(lastIndex + 1); } return version; } } catch (DOMException e) { logger.debug("DOMException when attempting to parse binding id from a STIX node. "); throw e; } return ""; }
From source file:Main.java
/** * Serializes the DOM-tree to a stringBuffer. Recursive method! * * @param node Node to start examining the tree from. * @param writeString The StringBuffer you want to fill with xml. * @return The StringBuffer containing the xml. * // ww w.j a v a 2s . co m * @since 2002-12-12 * @author Mattias Bogeblad */ public static StringBuffer serializeDom(Node node, StringBuffer writeString) { int type = node.getNodeType(); try { switch (type) { // print the document element case Node.DOCUMENT_NODE: { writeString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); writeString = serializeDom(((Document) node).getDocumentElement(), writeString); break; } // print element with attributes case Node.ELEMENT_NODE: { writeString.append("<"); writeString.append(node.getNodeName()); NamedNodeMap attrs = node.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); String outString = " " + attr.getNodeName() + "=\"" + replaceSpecialCharacters(attr.getNodeValue()) + "\""; writeString.append(outString); } writeString.append(">"); NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) writeString = serializeDom(children.item(i), writeString); } break; } // handle entity reference nodes case Node.ENTITY_REFERENCE_NODE: { String outString = "&" + node.getNodeName() + ";"; writeString.append(outString); break; } // print cdata sections case Node.CDATA_SECTION_NODE: { String outString = "<![CDATA[" + node.getNodeValue() + "]]>"; writeString.append(outString); break; } // print text case Node.TEXT_NODE: { writeString.append(replaceSpecialCharacters(node.getNodeValue())); break; } // print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { String data = node.getNodeValue(); String outString = "<?" + node.getNodeName() + " " + data + "?>"; writeString.append(outString); break; } } if (type == Node.ELEMENT_NODE) { String outString = "</" + node.getNodeName() + ">"; writeString.append(outString); } } catch (Exception e) { } return writeString; }
From source file:com.photon.phresco.framework.commons.QualityUtil.java
public static List<String> getDeviceNames(Document document) throws Exception { NodeList nodeList = org.apache.xpath.XPathAPI.selectNodeList(document, "/*/*"); List<String> deviceList = new ArrayList<String>(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); NamedNodeMap nameNodeMap = node.getAttributes(); String deviceId = ""; String deviceName = ""; Node idAttr = nameNodeMap.getNamedItem(FrameworkConstants.ATTR_ID); deviceId = idAttr.getNodeValue(); Node nameAttr = nameNodeMap.getNamedItem(FrameworkConstants.ATTR_NAME); deviceName = nameAttr.getNodeValue(); deviceList.add(deviceId + "#SEP#" + deviceName); }/*from w w w . j a v a 2 s.co m*/ return deviceList; }
From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityXmlParser.java
/** * Resolves DOM node contained textual data and formats it using provided locator. * * @param locator//from w w w . j a va 2 s . c om * locator instance to alter using XML attributes contained data type, format and units used to format * resolved value * @param node * DOM node to collect textual data * @return resolved textual value formatted based on the locator's formatting properties * @throws ParseException * if exception occurs applying locator format properties to specified value */ protected static Object getTextContent(ActivityFieldLocator locator, Node node) throws ParseException { String strValue = node.getTextContent(); Node attrsNode = node; if (node instanceof Attr) { Attr attr = (Attr) node; attrsNode = attr.getOwnerElement(); } // Get list of attributes and their values for // current element NamedNodeMap attrsMap = attrsNode == null ? null : attrsNode.getAttributes(); Node attr; String attrVal; ActivityFieldLocator locCopy = locator.clone(); if (attrsMap != null && attrsMap.getLength() > 0) { attr = attrsMap.getNamedItem(DATA_TYPE_ATTR); attrVal = attr == null ? null : attr.getTextContent(); if (StringUtils.isNotEmpty(attrVal)) { locCopy.setDataType(ActivityFieldDataType.valueOf(attrVal)); } attr = attrsMap.getNamedItem(FORMAT_ATTR); attrVal = attr == null ? null : attr.getTextContent(); if (StringUtils.isNotEmpty(attrVal)) { attr = attrsMap.getNamedItem(LOCALE_ATTR); String attrLVal = attr == null ? null : attr.getTextContent(); locCopy.setFormat(attrVal, StringUtils.isEmpty(attrLVal) ? locator.getLocale() : attrLVal); } attr = attrsMap.getNamedItem(UNITS_ATTR); attrVal = attr == null ? null : attr.getTextContent(); if (StringUtils.isNotEmpty(attrVal)) { locCopy.setUnits(attrVal); } } return locCopy.formatValue(strValue.trim()); }