List of usage examples for org.w3c.dom Document getElementsByTagName
public NodeList getElementsByTagName(String tagname);
NodeList
of all the Elements
in document order with a given tag name and are contained in the document. 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.//from w w w . j a va 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; }
From source file:org.geosamples.credentials.CredentialsValidator.java
/** * Validates user credentials for use with GeoPass from SESAR. * * @see/*from w ww .jav a 2 s . c o m*/ * <a href="http://www.iedadata.org/services/sesar_api#2.sesarusercredential">SESAR * credential POST API</a> * @param userName * @param password * @param credentialsService * @return ArrayList of user codes for this user * @throws IOException * @throws ParserConfigurationException * @throws SAXException * @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws KeyManagementException */ private static ArrayList<String> validateUserCredentials(String userName, String password, String credentialsService) throws IOException, ParserConfigurationException, SAXException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { ArrayList<String> userCodes = new ArrayList<>(); Map<String, String> dataToPost = new HashMap<>(); dataToPost.put("username", userName); dataToPost.put("password", password); org.apache.http.client.methods.HttpPost httpPost = new HttpPost(credentialsService); List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("username", userName)); nameValuePairs.add(new BasicNameValuePair("password", password)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpClient httpClient = org.geosamples.utilities.HTTPClient.clientWithNoSecurityValidation(); Document doc; try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) { HttpEntity myEntity = httpResponse.getEntity(); InputStream response = myEntity.getContent(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); doc = factory.newDocumentBuilder().parse(response); EntityUtils.consume(myEntity); } if (doc != null) { if (doc.getElementsByTagName("valid").getLength() > 0) { if (doc.getElementsByTagName("valid").item(0).getTextContent().trim().equalsIgnoreCase("yes")) { NodeList userCodesList = doc.getElementsByTagName("user_code"); for (int i = 0; i < userCodesList.getLength(); i++) { userCodes.add(userCodesList.item(i).getTextContent().trim()); } } } } return userCodes; }
From source file:org.dasein.cloud.terremark.Terremark.java
public static String getTaskHref(Document doc, String taskName) { String href = null;//from www. j a v a2 s . c o m NodeList taskElements = doc.getElementsByTagName(Terremark.TASK_TAG); for (int i = 0; i < taskElements.getLength(); i++) { Node taskElement = taskElements.item(i); NodeList taskChildren = taskElement.getChildNodes(); for (int j = 0; j < taskChildren.getLength(); j++) { Node taskChild = taskChildren.item(j); if (taskChild.getNodeName().equals(Terremark.OPERATION_TAG)) { if (taskChild.getTextContent().equals(taskName)) { href = taskElement.getAttributes().getNamedItem(Terremark.HREF).getNodeValue(); break; } } } if (href != null) { break; } } return href; }
From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java
/** * Gets a set of names of checkstyle's checks which are referenced in checkstyle_checks.xml. * @param configFilePath file path of checkstyle_checks.xml. * @return names of checkstyle's checks which are referenced in checkstyle_checks.xml. * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested. * @throws IOException if any IO errors occur. * @throws SAXException if any parse errors occur. *//*from ww w .j av a 2s . c o m*/ private static Set<String> getCheckStyleChecksReferencedInConfig(String configFilePath) throws ParserConfigurationException, IOException, SAXException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Validations of XML file make parsing too slow, that is why we disable all validations. factory.setNamespaceAware(false); factory.setValidating(false); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/validation", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(new File(configFilePath)); // optional, but recommended // FYI: http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work document.getDocumentElement().normalize(); final NodeList nodeList = document.getElementsByTagName("module"); Set<String> checksReferencedInCheckstyleChecksXML = new HashSet<>(); for (int i = 0; i < nodeList.getLength(); i++) { final Node currentNode = nodeList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { final Element module = (Element) currentNode; final String checkName = module.getAttribute("name"); if (!"Checker".equals(checkName) && !"TreeWalker".equals(checkName) && !"SuppressionFilter".equals(checkName)) { checksReferencedInCheckstyleChecksXML.add(checkName); } } } return checksReferencedInCheckstyleChecksXML; }
From source file:com.omertron.thetvdbapi.tools.TvdbParser.java
/** * Get a list of banners from the URL/*www . ja va 2 s . c om*/ * * @param urlString * @param bannerMirror * @return */ public static Banners getBanners(String urlString, String bannerMirror) { Banners banners = new Banners(); Banner banner; NodeList nlBanners; Node nBanner; Element eBanner; try { Document doc = DOMHelper.getEventDocFromUrl(urlString); if (doc != null) { nlBanners = doc.getElementsByTagName(BANNER); for (int loop = 0; loop < nlBanners.getLength(); loop++) { nBanner = nlBanners.item(loop); if (nBanner.getNodeType() == Node.ELEMENT_NODE) { eBanner = (Element) nBanner; banner = parseNextBanner(eBanner, bannerMirror); if (banner != null) { banners.addBanner(banner); } } } } } catch (WebServiceException ex) { LOG.warn("Banners error: " + ex.getMessage(), ex); } return banners; }
From source file:com.omertron.thetvdbapi.tools.TvdbParser.java
/** * Get the episode information from the URL * * @param urlString/* w w w .j a va 2s . co m*/ * @param bannerMirror * @return */ public static Episode getEpisode(String urlString, String bannerMirror) { Episode episode = new Episode(); NodeList nlEpisode; Node nEpisode; Element eEpisode; try { Document doc = DOMHelper.getEventDocFromUrl(urlString); if (doc != null) { nlEpisode = doc.getElementsByTagName(EPISODE); for (int loop = 0; loop < nlEpisode.getLength(); loop++) { nEpisode = nlEpisode.item(loop); if (nEpisode.getNodeType() == Node.ELEMENT_NODE) { eEpisode = (Element) nEpisode; episode = parseNextEpisode(eEpisode, bannerMirror); if (episode != null) { // We only need the first episode break; } } } } } catch (WebServiceException ex) { LOG.warn("Series error: " + ex.getMessage(), ex); } return episode; }
From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java
/** * Gets names of checkstyle's modules which are documented in xdocs. * @param xdocsDirectoryPath xdocs directory path. * @return a set of checkstyle's modules which have xdoc documentation. * @throws ParserConfigurationException if a DocumentBuilder cannot be created which satisfies the configuration requested. * @throws IOException if any IO errors occur. * @throws SAXException if any parse errors occur. *//*from w w w . j a v a 2s . c o m*/ private static Set<String> getModulesNamesWhichHaveXdoc(String xdocsDirectoryPath) throws ParserConfigurationException, IOException, SAXException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Validations of XML file make parsing too slow, that is why we disable all validations. factory.setNamespaceAware(false); factory.setValidating(false); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/validation", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); final Set<Path> xdocsFilePaths = getXdocsFilePaths(xdocsDirectoryPath); final Set<String> modulesNamesWhichHaveXdoc = new HashSet<>(); for (Path path : xdocsFilePaths) { final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(path.toFile()); // optional, but recommended // FYI: http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work document.getDocumentElement().normalize(); final NodeList nodeList = document.getElementsByTagName("section"); for (int i = 0; i < nodeList.getLength(); i++) { final Node currentNode = nodeList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { final Element module = (Element) currentNode; final String moduleName = module.getAttribute("name"); if (!"Content".equals(moduleName) && !"Overview".equals(moduleName)) { modulesNamesWhichHaveXdoc.add(moduleName); } } } } return modulesNamesWhichHaveXdoc; }
From source file:module.signature.util.XAdESValidator.java
/** * @author joantune/*from ww w. j a va2 s . com*/ * * Makes sure that the document which was signed is equal to the one * that was sent. It also checks to see if the signers are the * correct persons or not NOTE: It does note validate the validity * of the signature itself, only that what was sent was the same * that was receveived. * * To validate, see: * * @see XAdESValidator#validateXMLSignature(byte[]) * @param receivedContent * the received signature * @param originalContent * the byte array of what was sent to the signer * @param usersPermitted * Users that are permitted to be on the signature * @param usersExcluded * Users which must not be on the list of signers, or null/empty * list if none is excluded * @param allUsersPermittedShouldBeThere * if true, all of the users of <i>usersPermitted</i> must be on * the list of signers * @throws SignatureDataException * if any error has been observed, thus the validation fails */ public static void validateSentAndReceivedContent(String receivedContent, byte[] originalContent, Set<User> usersPermitted, Set<User> usersExcluded, boolean allUsersPermittedShouldBeThere) throws SignatureDataException { //let's validate the content. That is, what we received against what we sent and make sure it hasn't changed if (schemaXSD == null) { loadXAdESSchemas(); } //we know that we are receiving a XaDES-T signature boolean validSignature = false; try { //let's extract the signatureContent and compare it against what we sent //let's decode and interpret the XML file //making the objects to interpret the XML document DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); ErrorHandler eh = new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } @Override public void error(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { throw new UnsupportedOperationException("Not supported yet.", exception); } }; //let's decode the document byte[] signatureDecoded = Base64.decode(receivedContent); ByteArrayInputStream bais = new ByteArrayInputStream(signatureDecoded); // let's parse the document parser.setErrorHandler(eh); Document document = parser.parse(bais); NodeList fileContentNodeList = document.getElementsByTagName("FileContent"); //Even if we have more than one signature, we should only have one file content!! if not, let's throw an exception here if (fileContentNodeList.getLength() > 1) { throw new SignatureDataException("too.many.file.content.nodes.malformed.signature.document", true, null); } if (fileContentNodeList.getLength() < 1) { throw new SignatureDataException("no.file.content.nodes.in.received.signature", true, null); } Node fileContentNode = fileContentNodeList.item(0).getFirstChild(); //now finally, we can compare the content of this node with the one that we generated //debug lines: byte[] receivedDecodedByteContent = Base64.decode(fileContentNode.getNodeValue()); //ok, so let's parse this again to strings and then we can better compare them and maybe know exactly why they are different String originalEncodedContent = Base64.encodeBytes(originalContent); String originalDecodedContent = new String(Base64.decode(originalEncodedContent), Charset.forName("UTF-8")); String receivedDecodedContent = new String(receivedDecodedByteContent, Charset.forName("UTF-8")); //now let's //make sure the signature is from the right person //TODO uncomment the following line: // validateSigner(document, usersPermitted, usersExcluded, allUsersPermittedShouldBeThere); if (!StringUtils.equals(StringUtils.trimToEmpty(originalDecodedContent), StringUtils.trimToEmpty(receivedDecodedContent))) { // } throw new SignatureDataException("signature.content.sent.and.received.are.different"); } else { validSignature = true; } //TODO FENIX-196 assert if one should be notified of these errors } catch (IOException e1) { // e1.printStackTrace(); throw new SignatureDataException("error.decoding.base64.sig", e1); } catch (SAXException e) { // e.printStackTrace(); throw new SignatureDataException("error.parsing.received.signature.file", e); } catch (ParserConfigurationException e) { // e.printStackTrace(); throw new SignatureDataException("error.parsing.received.signature.file.parser.configuration", e); } if (!validSignature) { throw new SignatureDataException("invalid.signature.content"); } }
From source file:com.netsteadfast.greenstep.base.action.BaseSupportAction.java
private static Map<String, String> loadStrutsConstants(InputStream is) throws Exception { if (loadStrutsSettingConstatns != null) { return loadStrutsSettingConstatns; }/*www . ja v a 2 s. c om*/ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature("http://xml.org/sax/features/validation", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(is); NodeList nodes = doc.getElementsByTagName("constant"); loadStrutsSettingConstatns = new HashMap<String, String>(); for (int i = 0; nodes != null && i < nodes.getLength(); i++) { Node node = nodes.item(i); Element nodeElement = (Element) node; loadStrutsSettingConstatns.put(nodeElement.getAttribute("name"), nodeElement.getAttribute("value")); } return loadStrutsSettingConstatns; }
From source file:org.n52.geoar.newdata.PluginLoader.java
/** * Extracts and parses the geoar-plugin.xml plugin-descriptor to create and * fill a {@link PluginInfo} instance./*from w w w. java2 s . c o m*/ * * @param pluginFile * @return */ private static PluginInfo readPluginInfoFromPlugin(File pluginFile) { try { ZipFile zipFile = new ZipFile(pluginFile); ZipEntry pluginDescriptorEntry = zipFile.getEntry("geoar-plugin.xml"); if (pluginDescriptorEntry == null) { return null; } Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(zipFile.getInputStream(pluginDescriptorEntry)); // Find name String name = null; NodeList nodeList = document.getElementsByTagName("name"); if (nodeList != null && nodeList.getLength() >= 1) { name = nodeList.item(0).getTextContent(); } else { LOG.warn("Plugin Descriptor for " + pluginFile.getName() + " does not specify a name"); } // Find publisher String publisher = null; nodeList = document.getElementsByTagName("publisher"); if (nodeList != null && nodeList.getLength() >= 1) { publisher = nodeList.item(0).getTextContent(); } else { LOG.warn("Plugin Descriptor for " + pluginFile.getName() + " does not specify a publisher"); } // Find description String description = null; nodeList = document.getElementsByTagName("description"); if (nodeList != null && nodeList.getLength() >= 1) { description = nodeList.item(0).getTextContent(); } else { LOG.warn("Plugin Descriptor for " + pluginFile.getName() + " does not specify a description"); } // Find identifier String identifier = null; nodeList = document.getElementsByTagName("identifier"); if (nodeList != null && nodeList.getLength() >= 1) { identifier = nodeList.item(0).getTextContent(); } else { LOG.warn("Plugin Descriptor for " + pluginFile.getName() + " does not specify an identifier"); } // Find version Long version = null; nodeList = document.getElementsByTagName("version"); if (nodeList != null && nodeList.getLength() >= 1) { String versionString = "-" + nodeList.item(0).getTextContent(); Matcher matcher = pluginVersionPattern.matcher(versionString); if (matcher.find() && matcher.group(1) != null) { try { version = parseVersionNumber(matcher.group(1)); } catch (NumberFormatException e) { LOG.error("Plugin filename version invalid: " + matcher.group(1)); } } } else { LOG.warn("Plugin Descriptor for " + pluginFile.getName() + " does not specify a version"); } if (identifier == null) { identifier = name; } return new PluginInfo(pluginFile, name, description, version, identifier, publisher); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (ZipException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }