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
/** Prints the specified node, then prints all of its children. */ public static void printDOM(Node node) { int type = node.getNodeType(); switch (type) { // print the document element case Node.DOCUMENT_NODE: { System.out.print("<?xml version=\"1.0\" ?>"); printDOM(((Document) node).getDocumentElement()); break;//from w ww . ja v a 2s. c o m } // print element with attributes case Node.ELEMENT_NODE: { System.out.println(); System.out.print("<"); System.out.print(node.getNodeName()); NamedNodeMap attrs = node.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); System.out.print(" " + attr.getNodeName().trim() + "=\"" + attr.getNodeValue().trim() + "\""); } System.out.print(">"); NodeList children = node.getChildNodes(); if (children != null) { int len = children.getLength(); for (int i = 0; i < len; i++) printDOM(children.item(i)); } break; } // handle entity reference nodes case Node.ENTITY_REFERENCE_NODE: { System.out.print("&"); System.out.print(node.getNodeName().trim()); System.out.print(";"); break; } // print cdata sections case Node.CDATA_SECTION_NODE: { System.out.print("<![CDATA["); System.out.print(node.getNodeValue().trim()); System.out.print("]]>"); break; } // print text case Node.TEXT_NODE: { System.out.println(); System.out.print(node.getNodeValue().trim()); break; } // print processing instruction case Node.PROCESSING_INSTRUCTION_NODE: { System.out.print("<?"); System.out.print(node.getNodeName().trim()); String data = node.getNodeValue().trim(); { System.out.print(" "); System.out.print(data); } System.out.print("?>"); break; } } if (type == Node.ELEMENT_NODE) { System.out.println(); System.out.print("</"); System.out.print(node.getNodeName().trim()); System.out.print('>'); } }
From source file:Main.java
public static void spreadNamespaces(Node node, String tns, boolean overwrite) { Document doc = node instanceof Document ? (Document) node : node.getOwnerDocument(); boolean isParent = false; while (node != null) { Node next = null;//ww w. j a v a2 s. com if (!isParent && node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNamespaceURI() == null) { node = doc.renameNode(node, tns, node.getNodeName()); } else { if (overwrite) { tns = node.getNamespaceURI(); } } NamedNodeMap nodeMap = node.getAttributes(); int nodeMapLengthl = nodeMap.getLength(); for (int i = 0; i < nodeMapLengthl; i++) { Node attr = nodeMap.item(i); if (attr.getNamespaceURI() == null) { doc.renameNode(attr, tns, attr.getNodeName()); } } } isParent = (isParent || (next = node.getFirstChild()) == null) && (next = node.getNextSibling()) == null; node = isParent ? node.getParentNode() : next; if (isParent && node != null) { if (overwrite) { tns = node.getNamespaceURI(); } } } }
From source file:Main.java
/** * Gets value of an attribute from node. Returns default value if attribute * not found.//from ww w.j av a 2 s. co m * * @param node * Node Object * @param attributeName * Attribute Name * @param defaultValue * Default value if attribute not found * @return Attribute Value * @throws IllegalArgumentException * for Invalid input */ public static String getAttribute(final Node node, final String attributeName, final String defaultValue) throws IllegalArgumentException { // Validate attribute name if (attributeName == null) { throw new IllegalArgumentException( "Attribute Name " + " cannot be null in XmlUtils.getAttribute method"); } // Validate node if (node == null) { throw new IllegalArgumentException("Node cannot " + " be null in XmlUtils.getAttribute method for " + "Attribute Name:" + attributeName); } final NamedNodeMap attributeList = node.getAttributes(); final Node attribute = attributeList.getNamedItem(attributeName); // Validate attribute name if (attribute == null) { return defaultValue; } return ((Attr) attribute).getValue(); }
From source file:com.seleniumtests.core.SeleniumTestsContextManager.java
/** * Get service parameters from configuration file. * Only the parameters corresponding to the defined runMode. * @param parameters//from ww w . jav a2 s. c om * @param runMode * @param iTestContext * @param configParser * @return Map with service parameters from the given file. */ private static Map<String, String> getServiceParameters(Map<String, String> parameters, String runMode, TestConfigurationParser configParser) { for (Node node : configParser.getServiceNodes()) { if (node.getAttributes().getNamedItem("name").getNodeValue().equalsIgnoreCase(runMode)) { NodeList nList = node.getChildNodes(); for (int i = 0; i < nList.getLength(); i++) { Node paramNode = nList.item(i); if ("parameter".equals(paramNode.getNodeName())) { parameters.put(paramNode.getAttributes().getNamedItem("name").getNodeValue(), paramNode.getAttributes().getNamedItem("value").getNodeValue()); } } } } return parameters; }
From source file:com.puppycrawl.tools.checkstyle.XDocsPagesTest.java
private static void validateCheckSection(ModuleFactory moduleFactory, String fileName, String sectionName, Node section) {//w ww. ja v a 2 s. c o m Object instance = null; try { instance = moduleFactory.createModule(sectionName); } catch (CheckstyleException e) { Assert.fail(fileName + " couldn't find class: " + sectionName); } int subSectionPos = 0; for (Node subSection : getChildrenElements(section)) { final String subSectionName = subSection.getAttributes().getNamedItem("name").getNodeValue(); // can be in different orders, and completely optional if ("Notes".equals(subSectionName) || "Rule Description".equals(subSectionName)) { continue; } if (subSectionPos == 1 && !"Properties".equals(subSectionName)) { validatePropertySection(fileName, sectionName, null, instance); subSectionPos++; } Assert.assertEquals(fileName + " section '" + sectionName + "' should be in order", getSubSectionName(subSectionPos), subSectionName); switch (subSectionPos) { case 0: break; case 1: validatePropertySection(fileName, sectionName, subSection, instance); break; case 2: break; case 3: validateUsageExample(fileName, sectionName, subSection); break; case 4: validatePackageSection(fileName, sectionName, subSection, instance); break; case 5: validateParentSection(fileName, sectionName, subSection); break; default: break; } subSectionPos++; } }
From source file:com.seleniumtests.core.SeleniumTestsContextManager.java
/** * Get parameters from configuration file. * @param iTestContext//w w w .jav a2s.co m * @param configParser * @return Map with parameters from the given file. */ private static Map<String, String> getParametersFromConfigFile(final ITestContext iTestContext, TestConfigurationParser configParser) { Map<String, String> parameters; // get parameters if (iTestContext.getCurrentXmlTest() != null) { parameters = iTestContext.getCurrentXmlTest().getSuite().getParameters(); } else { parameters = iTestContext.getSuite().getXmlSuite().getParameters(); } // insert parameters for (Node node : configParser.getParameterNodes()) { parameters.put(node.getAttributes().getNamedItem("name").getNodeValue(), node.getAttributes().getNamedItem("value").getNodeValue()); } return parameters; }
From source file:ee.ria.xroad.proxy.util.MetaserviceTestUtil.java
/** Merge xroad-specific {@link SoapHeader} to the generic {@link SOAPHeader} * @param header//from w w w . j a va 2 s. c o m * @param xrHeader * @throws JAXBException * @throws ParserConfigurationException * @throws SOAPException */ public static void mergeHeaders(SOAPHeader header, SoapHeader xrHeader) throws JAXBException, ParserConfigurationException, SOAPException { Document document = documentBuilderFactory.newDocumentBuilder().newDocument(); final DocumentFragment documentFragment = document.createDocumentFragment(); // marshalling on the header would add the xroad header as a child of the header // (i.e. two nested header elements) marshaller.marshal(xrHeader, documentFragment); Document headerDocument = header.getOwnerDocument(); Node xrHeaderElement = documentFragment.getFirstChild(); assertTrue("test setup failed: assumed had header element but did not", xrHeaderElement.getNodeType() == Node.ELEMENT_NODE && xrHeaderElement.getLocalName().equals("Header")); final NamedNodeMap attributes = xrHeaderElement.getAttributes(); if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { final Attr attribute = (Attr) attributes.item(i); header.setAttributeNodeNS((Attr) headerDocument.importNode(attribute, false)); } } final NodeList childNodes = xrHeaderElement.getChildNodes(); if (childNodes != null) { for (int i = 0; i < childNodes.getLength(); i++) { final Node node = childNodes.item(i); header.appendChild(headerDocument.importNode(node, true)); } } }
From source file:com.bluexml.xforms.demo.Util.java
private static String getUserName(String alfrescohost, String user, String protocol, String identifier, String initiator) throws Exception { String firstname = ""; String lastname = ""; PostMethod post = new PostMethod(alfrescohost + "service/xforms/read"); post.setParameter("username", user); post.setParameter("objectId", protocol + "://" + identifier + "/" + initiator); HttpClient client = new HttpClient(); client.executeMethod(post);/*from w w w . j ava 2 s . c o m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(post.getResponseBodyAsStream()); Node root = document.getDocumentElement(); NodeList nodes = findNode(root.getChildNodes(), "attributes").getChildNodes(); for (int i = 0; i < nodes.getLength(); ++i) { Node n = nodes.item(i); if (n.getNodeName().equals("attribute")) { Node attr = n.getAttributes().getNamedItem("qualifiedName"); if (attr != null) if (attr.getNodeValue().equals("firstName")) firstname = findNode(n.getChildNodes(), "value").getTextContent(); else if (attr.getNodeValue().equals("lastName")) lastname = findNode(n.getChildNodes(), "value").getTextContent(); } } return firstname + " " + lastname; }
From source file:jp.sf.fess.solr.plugin.suggest.util.SolrConfigUtil.java
public static SuggestUpdateConfig getUpdateHandlerConfig(final SolrConfig config) { final SuggestUpdateConfig suggestUpdateConfig = new SuggestUpdateConfig(); final Node solrServerNode = config.getNode("updateHandler/suggest/solrServer", false); if (solrServerNode != null) { try {//from w w w . j a va 2s. c o m final Node classNode = solrServerNode.getAttributes().getNamedItem("class"); String className; if (classNode != null) { className = classNode.getTextContent(); } else { className = "org.codelibs.solr.lib.server.SolrLibHttpSolrServer"; } @SuppressWarnings("unchecked") final Class<? extends SolrServer> clazz = (Class<? extends SolrServer>) Class.forName(className); final String arg = config.getVal("updateHandler/suggest/solrServer/arg", false); SolrServer solrServer; if (StringUtils.isNotBlank(arg)) { final Constructor<? extends SolrServer> constructor = clazz.getConstructor(String.class); solrServer = constructor.newInstance(arg); } else { solrServer = clazz.newInstance(); } final String username = config.getVal("updateHandler/suggest/solrServer/credentials/username", false); final String password = config.getVal("updateHandler/suggest/solrServer/credentials/password", false); if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password) && solrServer instanceof SolrLibHttpSolrServer) { final SolrLibHttpSolrServer solrLibHttpSolrServer = (SolrLibHttpSolrServer) solrServer; final URL u = new URL(arg); final AuthScope authScope = new AuthScope(u.getHost(), u.getPort()); final Credentials credentials = new UsernamePasswordCredentials(username, password); solrLibHttpSolrServer.setCredentials(authScope, credentials); solrLibHttpSolrServer.addRequestInterceptor(new PreemptiveAuthInterceptor()); } final NodeList childNodes = solrServerNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { final Node node = childNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { final String name = node.getNodeName(); if (!"arg".equals(name) && !"credentials".equals(name)) { final String value = node.getTextContent(); final Node typeNode = node.getAttributes().getNamedItem("type"); final Method method = clazz.getMethod( "set" + name.substring(0, 1).toUpperCase() + name.substring(1), getMethodArgClass(typeNode)); method.invoke(solrServer, getMethodArgValue(typeNode, value)); } } } if (solrServer instanceof SolrLibHttpSolrServer) { ((SolrLibHttpSolrServer) solrServer).init(); } suggestUpdateConfig.setSolrServer(solrServer); } catch (final Exception e) { throw new FessSuggestException("Failed to load SolrServer.", e); } } final String labelFields = config.getVal("updateHandler/suggest/labelFields", false); if (StringUtils.isNotBlank(labelFields)) { suggestUpdateConfig.setLabelFields(labelFields.trim().split(",")); } final String roleFields = config.getVal("updateHandler/suggest/roleFields", false); if (StringUtils.isNotBlank(roleFields)) { suggestUpdateConfig.setRoleFields(roleFields.trim().split(",")); } final String expiresField = config.getVal("updateHandler/suggest/expiresField", false); if (StringUtils.isNotBlank(expiresField)) { suggestUpdateConfig.setExpiresField(expiresField); } final String segmentField = config.getVal("updateHandler/suggest/segmentField", false); if (StringUtils.isNotBlank(segmentField)) { suggestUpdateConfig.setSegmentField(segmentField); } final String updateInterval = config.getVal("updateHandler/suggest/updateInterval", false); if (StringUtils.isNotBlank(updateInterval) && StringUtils.isNumeric(updateInterval)) { suggestUpdateConfig.setUpdateInterval(Long.parseLong(updateInterval)); } //set suggestFieldInfo final NodeList nodeList = config.getNodeList("updateHandler/suggest/suggestFieldInfo", true); for (int i = 0; i < nodeList.getLength(); i++) { try { final SuggestUpdateConfig.FieldConfig fieldConfig = new SuggestUpdateConfig.FieldConfig(); final Node fieldInfoNode = nodeList.item(i); final NamedNodeMap fieldInfoAttributes = fieldInfoNode.getAttributes(); final Node fieldNameNode = fieldInfoAttributes.getNamedItem("fieldName"); final String fieldName = fieldNameNode.getNodeValue(); if (StringUtils.isBlank(fieldName)) { continue; } fieldConfig.setTargetFields(fieldName.trim().split(",")); if (logger.isInfoEnabled()) { for (final String s : fieldConfig.getTargetFields()) { logger.info("fieldName : " + s); } } final NodeList fieldInfoChilds = fieldInfoNode.getChildNodes(); for (int j = 0; j < fieldInfoChilds.getLength(); j++) { final Node fieldInfoChildNode = fieldInfoChilds.item(j); final String fieldInfoChildNodeName = fieldInfoChildNode.getNodeName(); if ("tokenizerFactory".equals(fieldInfoChildNodeName)) { //field tokenier settings final SuggestUpdateConfig.TokenizerConfig tokenizerConfig = new SuggestUpdateConfig.TokenizerConfig(); final NamedNodeMap tokenizerFactoryAttributes = fieldInfoChildNode.getAttributes(); final Node tokenizerClassNameNode = tokenizerFactoryAttributes.getNamedItem("class"); final String tokenizerClassName = tokenizerClassNameNode.getNodeValue(); tokenizerConfig.setClassName(tokenizerClassName); if (logger.isInfoEnabled()) { logger.info("tokenizerFactory : " + tokenizerClassName); } final Map<String, String> args = new HashMap<String, String>(); for (int k = 0; k < tokenizerFactoryAttributes.getLength(); k++) { final Node attribute = tokenizerFactoryAttributes.item(k); final String key = attribute.getNodeName(); final String value = attribute.getNodeValue(); if (!"class".equals(key)) { args.put(key, value); } } if (!args.containsKey(USER_DICT_PATH)) { final String userDictPath = System.getProperty(SuggestConstants.USER_DICT_PATH, ""); if (StringUtils.isNotBlank(userDictPath)) { args.put(USER_DICT_PATH, userDictPath); } final String userDictEncoding = System.getProperty(SuggestConstants.USER_DICT_ENCODING, ""); if (StringUtils.isNotBlank(userDictEncoding)) { args.put(USER_DICT_ENCODING, userDictEncoding); } } tokenizerConfig.setArgs(args); fieldConfig.setTokenizerConfig(tokenizerConfig); } else if ("suggestReadingConverter".equals(fieldInfoChildNodeName)) { //field reading converter settings final NodeList converterNodeList = fieldInfoChildNode.getChildNodes(); for (int k = 0; k < converterNodeList.getLength(); k++) { final SuggestUpdateConfig.ConverterConfig converterConfig = new SuggestUpdateConfig.ConverterConfig(); final Node converterNode = converterNodeList.item(k); if (!"converter".equals(converterNode.getNodeName())) { continue; } final NamedNodeMap converterAttributes = converterNode.getAttributes(); final Node classNameNode = converterAttributes.getNamedItem("class"); final String className = classNameNode.getNodeValue(); converterConfig.setClassName(className); if (logger.isInfoEnabled()) { logger.info("converter : " + className); } final Map<String, String> properties = new HashMap<String, String>(); for (int l = 0; l < converterAttributes.getLength(); l++) { final Node attribute = converterAttributes.item(l); final String key = attribute.getNodeName(); final String value = attribute.getNodeValue(); if (!"class".equals(key)) { properties.put(key, value); } } converterConfig.setProperties(properties); if (logger.isInfoEnabled()) { logger.info("converter properties = " + properties); } fieldConfig.addConverterConfig(converterConfig); } } else if ("suggestNormalizer".equals(fieldInfoChildNodeName)) { //field normalizer settings final NodeList normalizerNodeList = fieldInfoChildNode.getChildNodes(); for (int k = 0; k < normalizerNodeList.getLength(); k++) { final SuggestUpdateConfig.NormalizerConfig normalizerConfig = new SuggestUpdateConfig.NormalizerConfig(); final Node normalizerNode = normalizerNodeList.item(k); if (!"normalizer".equals(normalizerNode.getNodeName())) { continue; } final NamedNodeMap normalizerAttributes = normalizerNode.getAttributes(); final Node classNameNode = normalizerAttributes.getNamedItem("class"); final String className = classNameNode.getNodeValue(); normalizerConfig.setClassName(className); if (logger.isInfoEnabled()) { logger.info("normalizer : " + className); } final Map<String, String> properties = new HashMap<String, String>(); for (int l = 0; l < normalizerAttributes.getLength(); l++) { final Node attribute = normalizerAttributes.item(l); final String key = attribute.getNodeName(); final String value = attribute.getNodeValue(); if (!"class".equals(key)) { properties.put(key, value); } } normalizerConfig.setProperties(properties); if (logger.isInfoEnabled()) { logger.info("normalize properties = " + properties); } fieldConfig.addNormalizerConfig(normalizerConfig); } } } suggestUpdateConfig.addFieldConfig(fieldConfig); } catch (final Exception e) { throw new FessSuggestException("Failed to load Suggest Field Info.", e); } } return suggestUpdateConfig; }
From source file:sep.gaia.resources.poi.POILoaderWorker.java
/** * Parses XML-data from the Overpass-API containing both nodes and ways and creates * <code>PointOfInterest</code>-objects from it. When a way is contained, one of its nodes * is picked as the describing POIs location. * @param doc The document to parse./*w w w.ja v a 2 s . c o m*/ * @return The POIs described by the Overpass-data. */ private static Collection<PointOfInterest> parseResponse(Document doc) { // First all ways must be parsed, because later the contained nodes must be known: Collection<Way> ways = new LinkedList<>(); NodeList wayElements = doc.getElementsByTagName("way"); // Iterate all way-elements: for (int i = 0; i < wayElements.getLength(); i++) { Node wayElement = wayElements.item(i); Set<String> nodeReferences = new HashSet<>(); Map<String, String> tags = new HashMap<>(); // Iterate all child-elements of the way-element: NodeList childs = wayElement.getChildNodes(); for (int j = 0; j < childs.getLength(); j++) { Node currentChild = childs.item(j); // If its a node reference if (currentChild.getNodeName().equals("nd")) { // Add its ID to the ways node references: NamedNodeMap attributes = currentChild.getAttributes(); String ref = attributes.getNamedItem("ref").getNodeValue(); nodeReferences.add(ref); // If its an attribute tag-element: } else if (currentChild.getNodeName().equals("tag")) { // Add the k/v-attributes to the ways attributes: NamedNodeMap attributes = currentChild.getAttributes(); String key = attributes.getNamedItem("k").getNodeValue(); String value = attributes.getNamedItem("v").getNodeValue(); tags.put(key, value); } } // Remember the way for later use: Way way = new Way(nodeReferences, tags); ways.add(way); } // Now all node-elements are parsed: NodeList nodeElements = doc.getElementsByTagName("node"); Collection<PointOfInterest> pois = new ArrayList<>(nodeElements.getLength()); for (int i = 0; i < nodeElements.getLength(); i++) { Node node = nodeElements.item(i); // Get the nodes ID and position: NamedNodeMap attributes = node.getAttributes(); String id = attributes.getNamedItem("id").getNodeValue(); float lat = Float.parseFloat(attributes.getNamedItem("lat").getNodeValue()); float lon = Float.parseFloat(attributes.getNamedItem("lon").getNodeValue()); // If the node is part of a way, add its position to the ways position-set: Way containedIn = null; Iterator<Way> wayIter = ways.iterator(); while (wayIter.hasNext() && containedIn == null) { Way current = wayIter.next(); if (current.containsNode(id)) { current.addNode(new FloatVector3D(lat, lon, 0)); containedIn = current; } } // If this node is not a part of a way: if (containedIn == null) { Map<String, String> tags = new HashMap<>(); // Iterate all children of the node: NodeList childs = node.getChildNodes(); for (int j = 0; j < childs.getLength(); j++) { Node currentChild = childs.item(j); NamedNodeMap childAttrs = currentChild.getAttributes(); // Add attribute for each k/v-element: if (currentChild.getNodeName().equals("tag")) { String key = childAttrs.getNamedItem("k").getNodeValue(); String value = childAttrs.getNamedItem("v").getNodeValue(); tags.put(key, value); } } // Valid POIs must have a name: String name = tags.get("name"); if (name != null) { // Create the POI from read data and add it to results: PointOfInterest poi = createPoiFromTags(lat, lon, tags); if (poi != null) { pois.add(poi); } } } } // The last thing to do is to convert all generated ways to POIs: for (Way way : ways) { PointOfInterest poi = wayToPoi(way); if (poi != null) { pois.add(poi); } } return pois; }