List of usage examples for org.w3c.dom Document getFirstChild
public Node getFirstChild();
From source file:org.alternativevision.gpx.GPXParser.java
/** * Parses a stream containing GPX data/* ww w . j a va 2 s . c o m*/ * * @param in the input stream * @return {@link GPX} object containing parsed data, or null if no gpx data was found in the seream * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ public GPX parseGPX(InputStream in) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder builder = docFactory.newDocumentBuilder(); Document doc = builder.parse(in); Node firstChild = doc.getFirstChild(); if (firstChild != null && GPXConstants.GPX_NODE.equals(firstChild.getNodeName())) { GPX gpx = new GPX(); NamedNodeMap attrs = firstChild.getAttributes(); for (int idx = 0; idx < attrs.getLength(); idx++) { Node attr = attrs.item(idx); if (GPXConstants.VERSION_ATTR.equals(attr.getNodeName())) { gpx.setVersion(attr.getNodeValue()); } else if (GPXConstants.CREATOR_ATTR.equals(attr.getNodeName())) { gpx.setCreator(attr.getNodeValue()); } } NodeList nodes = firstChild.getChildNodes(); if (logger.isDebugEnabled()) logger.debug("Found " + nodes.getLength() + " child nodes. Start parsing ..."); for (int idx = 0; idx < nodes.getLength(); idx++) { Node currentNode = nodes.item(idx); if (GPXConstants.WPT_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("Found waypoint node. Start parsing..."); Waypoint w = parseWaypoint(currentNode); if (w != null) { logger.info("Add waypoint to gpx data. [waypointName=" + w.getName() + "]"); gpx.addWaypoint(w); } } else if (GPXConstants.TRK_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("Found track node. Start parsing..."); Track trk = parseTrack(currentNode); if (trk != null) { logger.info("Add track to gpx data. [trackName=" + trk.getName() + "]"); gpx.addTrack(trk); } } else if (GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("Found extensions node. Start parsing..."); Iterator<IExtensionParser> it = extensionParsers.iterator(); while (it.hasNext()) { IExtensionParser parser = it.next(); Object data = parser.parseGPXExtension(currentNode); gpx.addExtensionData(parser.getId(), data); } } else if (GPXConstants.RTE_NODE.equals(currentNode.getNodeName())) { if (logger.isDebugEnabled()) logger.debug("Found route node. Start parsing..."); Route rte = parseRoute(currentNode); if (rte != null) { logger.info("Add route to gpx data. [routeName=" + rte.getName() + "]"); gpx.addRoute(rte); } } } //TODO: parse route node return gpx; } else { logger.error("FATAL!! - Root node is not gpx."); } return null; }
From source file:org.apache.openaz.xacml.pdp.policy.dom.DOMPolicy.java
public static void main(String args[]) { try {/* w w w . j a v a 2 s . c om*/ for (String fileName : args) { File filePolicy = new File(fileName); if (filePolicy.exists() && filePolicy.canRead()) { try { Document documentPolicy = DOMUtil.loadDocument(filePolicy); if (documentPolicy.getFirstChild() == null) { System.err.println(fileName + ": Error: No Policy found"); } else if (!XACML3.ELEMENT_POLICY.equals(documentPolicy.getFirstChild().getLocalName())) { System.err.println(fileName + ": Error: Not a Policy documnt"); } else { Policy policy = DOMPolicy.newInstance(documentPolicy.getFirstChild(), null, null); System.out.println(fileName + ": validate()=" + policy.validate()); System.out.println(StringUtils.prettyPrint(policy.toString())); } } catch (Exception ex) { System.err.println("Exception processing policy file \"" + fileName + "\""); ex.printStackTrace(System.err); } } else { System.err.println("Cannot read policy file \"" + fileName + "\""); } } } catch (Exception ex) { ex.printStackTrace(System.err); System.exit(1); } System.exit(0); }
From source file:org.apache.openaz.xacml.pdp.policy.dom.DOMPolicySet.java
public static void main(String args[]) { try {/*from w w w .j a va 2 s . c o m*/ for (String fileName : args) { File filePolicy = new File(fileName); if (filePolicy.exists() && filePolicy.canRead()) { try { Document documentPolicy = DOMUtil.loadDocument(filePolicy); if (documentPolicy.getFirstChild() == null) { System.err.println(fileName + ": Error: No PolicySet found"); } else if (!XACML3.ELEMENT_POLICYSET .equals(documentPolicy.getFirstChild().getLocalName())) { System.err.println(fileName + ": Error: Not a PolicySet document"); } else { PolicySet policySet = DOMPolicySet.newInstance(documentPolicy.getFirstChild(), null, null); System.out.println(fileName + ": validate()=" + policySet.validate()); System.out.println(StringUtils.prettyPrint(policySet.toString())); } } catch (Exception ex) { System.err.println("Exception processing policy set file \"" + fileName + "\""); ex.printStackTrace(System.err); } } else { System.err.println("Cannot read policy set file \"" + fileName + "\""); } } } catch (Exception ex) { ex.printStackTrace(System.err); System.exit(1); } System.exit(0); }
From source file:org.apache.shindig.gadgets.rewrite.MutableContentTest.java
@Test public void getContentAndParseTreeNoSets() throws Exception { String content = mhc.getContent(); assertEquals("DEFAULT VIEW", content); Document document = mhc.getDocument(); assertEquals(2, document.getFirstChild().getChildNodes().getLength()); Assert.assertSame(document.getFirstChild().getChildNodes().item(1).getFirstChild().getNodeType(), Node.TEXT_NODE);//from w w w .j a v a 2 s. c o m assertEquals(content, document.getFirstChild().getChildNodes().item(1).getTextContent()); assertSame(content, mhc.getContent()); assertTrue(Arrays.equals(content.getBytes("UTF8"), IOUtils.toByteArray(mhc.getContentBytes()))); assertSame(document, mhc.getDocument()); assertEquals(0, mhc.getNumChanges()); }
From source file:org.apache.shindig.gadgets.rewrite.MutableContentTest.java
@Test public void modifyTreeReflectedInContent() throws Exception { Document document = mhc.getDocument(); // First child should be text node per other tests. Modify it. document.getFirstChild().getFirstChild().setTextContent("FOO CONTENT"); assertEquals(0, mhc.getNumChanges()); MutableContent.notifyEdit(document); assertEquals(1, mhc.getNumChanges()); assertTrue(mhc.getContent().contains("FOO CONTENT")); // Do it again document.getFirstChild().getFirstChild().setTextContent("BAR CONTENT"); MutableContent.notifyEdit(document); assertEquals(2, mhc.getNumChanges()); assertTrue(mhc.getContent().contains("BAR CONTENT")); assertTrue(new String(IOUtils.toByteArray(mhc.getContentBytes()), "UTF8").contains("BAR CONTENT")); // GadgetHtmlNode hasn't changed because string hasn't changed assertSame(document, mhc.getDocument()); }
From source file:org.apache.ws.security.message.SignatureTest.java
/** * This is a test for WSS-234 - /*from ww w.j a v a 2 s. co m*/ * "When a document contains a comment as its first child element, * wss4j will not find the SOAP body." */ @org.junit.Test public void testWSS234() throws Exception { WSSecSignature builder = new WSSecSignature(); builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security"); LOG.info("Before Signing...."); Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); Document signedDoc = builder.build(doc, crypto, secHeader); // Add a comment node as the first node element org.w3c.dom.Node firstChild = signedDoc.getFirstChild(); org.w3c.dom.Node newNode = signedDoc.removeChild(firstChild); org.w3c.dom.Node commentNode = signedDoc.createComment("This is a comment"); signedDoc.appendChild(commentNode); signedDoc.appendChild(newNode); if (LOG.isDebugEnabled()) { LOG.debug("After Signing...."); String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); LOG.debug(outputString); } verify(signedDoc); }
From source file:org.apache.ws.security.saml.ext.OpenSAMLUtil.java
/** * Convert a SAML Assertion from a XMLObject to a DOM Element * * @param xmlObject of type XMLObject/*from ww w . jav a 2 s . c o m*/ * @param doc of type Document * @param signObject whether to sign the XMLObject during marshalling * @return Element * @throws MarshallingException * @throws SignatureException */ public static Element toDom(XMLObject xmlObject, Document doc, boolean signObject) throws WSSecurityException { Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject); Element element = null; DocumentFragment frag = doc == null ? null : doc.createDocumentFragment(); try { if (frag != null) { while (doc.getFirstChild() != null) { frag.appendChild(doc.removeChild(doc.getFirstChild())); } } try { if (doc == null) { element = marshaller.marshall(xmlObject); } else { element = marshaller.marshall(xmlObject, doc); } } catch (MarshallingException ex) { throw new WSSecurityException("Error marshalling a SAML assertion", ex); } if (signObject) { signXMLObject(xmlObject); } } finally { if (frag != null) { while (doc.getFirstChild() != null) { doc.removeChild(doc.getFirstChild()); } doc.appendChild(frag); } } return element; }
From source file:org.apache.xml.security.Init.java
/** * Initialise the library from a configuration file *//*from w w w . ja va 2s . c om*/ private static void fileInit(InputStream is) { try { /* read library configuration file */ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(is); Node config = doc.getFirstChild(); for (; config != null; config = config.getNextSibling()) { if ("Configuration".equals(config.getLocalName())) { break; } } if (config == null) { log.error("Error in reading configuration file - Configuration element not found"); return; } for (Node el = config.getFirstChild(); el != null; el = el.getNextSibling()) { if (el == null || Node.ELEMENT_NODE != el.getNodeType()) { continue; } String tag = el.getLocalName(); if (tag.equals("ResourceBundles")) { Element resource = (Element) el; /* configure internationalization */ Attr langAttr = resource.getAttributeNode("defaultLanguageCode"); Attr countryAttr = resource.getAttributeNode("defaultCountryCode"); String languageCode = (langAttr == null) ? null : langAttr.getNodeValue(); String countryCode = (countryAttr == null) ? null : countryAttr.getNodeValue(); I18n.init(languageCode, countryCode); } if (tag.equals("CanonicalizationMethods")) { Element[] list = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "CanonicalizationMethod"); for (int i = 0; i < list.length; i++) { String URI = list[i].getAttributeNS(null, "URI"); String JAVACLASS = list[i].getAttributeNS(null, "JAVACLASS"); try { Canonicalizer.register(URI, JAVACLASS); if (log.isDebugEnabled()) { log.debug("Canonicalizer.register(" + URI + ", " + JAVACLASS + ")"); } } catch (ClassNotFoundException e) { Object exArgs[] = { URI, JAVACLASS }; log.error(I18n.translate("algorithm.classDoesNotExist", exArgs)); } } } if (tag.equals("TransformAlgorithms")) { Element[] tranElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "TransformAlgorithm"); for (int i = 0; i < tranElem.length; i++) { String URI = tranElem[i].getAttributeNS(null, "URI"); String JAVACLASS = tranElem[i].getAttributeNS(null, "JAVACLASS"); try { Transform.register(URI, JAVACLASS); if (log.isDebugEnabled()) { log.debug("Transform.register(" + URI + ", " + JAVACLASS + ")"); } } catch (ClassNotFoundException e) { Object exArgs[] = { URI, JAVACLASS }; log.error(I18n.translate("algorithm.classDoesNotExist", exArgs)); } catch (NoClassDefFoundError ex) { log.warn("Not able to found dependencies for algorithm, I'll keep working."); } } } if ("JCEAlgorithmMappings".equals(tag)) { Node algorithmsNode = ((Element) el).getElementsByTagName("Algorithms").item(0); if (algorithmsNode != null) { Element[] algorithms = XMLUtils.selectNodes(algorithmsNode.getFirstChild(), CONF_NS, "Algorithm"); for (int i = 0; i < algorithms.length; i++) { Element element = algorithms[i]; String id = element.getAttribute("URI"); JCEMapper.register(id, new JCEMapper.Algorithm(element)); } } } if (tag.equals("SignatureAlgorithms")) { Element[] sigElems = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "SignatureAlgorithm"); for (int i = 0; i < sigElems.length; i++) { String URI = sigElems[i].getAttributeNS(null, "URI"); String JAVACLASS = sigElems[i].getAttributeNS(null, "JAVACLASS"); /** $todo$ handle registering */ try { SignatureAlgorithm.register(URI, JAVACLASS); if (log.isDebugEnabled()) { log.debug("SignatureAlgorithm.register(" + URI + ", " + JAVACLASS + ")"); } } catch (ClassNotFoundException e) { Object exArgs[] = { URI, JAVACLASS }; log.error(I18n.translate("algorithm.classDoesNotExist", exArgs)); } } } if (tag.equals("ResourceResolvers")) { Element[] resolverElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver"); for (int i = 0; i < resolverElem.length; i++) { String JAVACLASS = resolverElem[i].getAttributeNS(null, "JAVACLASS"); String Description = resolverElem[i].getAttributeNS(null, "DESCRIPTION"); if ((Description != null) && (Description.length() > 0)) { if (log.isDebugEnabled()) { log.debug("Register Resolver: " + JAVACLASS + ": " + Description); } } else { if (log.isDebugEnabled()) { log.debug("Register Resolver: " + JAVACLASS + ": For unknown purposes"); } } try { ResourceResolver.register(JAVACLASS); } catch (Throwable e) { log.warn("Cannot register:" + JAVACLASS + " perhaps some needed jars are not installed", e); } } } if (tag.equals("KeyResolver")) { Element[] resolverElem = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "Resolver"); List<String> classNames = new ArrayList<String>(resolverElem.length); for (int i = 0; i < resolverElem.length; i++) { String JAVACLASS = resolverElem[i].getAttributeNS(null, "JAVACLASS"); String Description = resolverElem[i].getAttributeNS(null, "DESCRIPTION"); if ((Description != null) && (Description.length() > 0)) { if (log.isDebugEnabled()) { log.debug("Register Resolver: " + JAVACLASS + ": " + Description); } } else { if (log.isDebugEnabled()) { log.debug("Register Resolver: " + JAVACLASS + ": For unknown purposes"); } } classNames.add(JAVACLASS); } KeyResolver.registerClassNames(classNames); } if (tag.equals("PrefixMappings")) { if (log.isDebugEnabled()) { log.debug("Now I try to bind prefixes:"); } Element[] nl = XMLUtils.selectNodes(el.getFirstChild(), CONF_NS, "PrefixMapping"); for (int i = 0; i < nl.length; i++) { String namespace = nl[i].getAttributeNS(null, "namespace"); String prefix = nl[i].getAttributeNS(null, "prefix"); if (log.isDebugEnabled()) { log.debug("Now I try to bind " + prefix + " to " + namespace); } ElementProxy.setDefaultPrefix(namespace, prefix); } } } } catch (Exception e) { log.error("Bad: ", e); e.printStackTrace(); } }
From source file:org.broad.igv.cbio.GeneNetworkTest.java
@Test public void testAnnotateAll() throws Exception { String networkPath = TestUtils.DATA_DIR + "egfr_brca1.xml.gz"; assertTrue(network.loadNetwork(networkPath) > 0); //Load some tracks String dataPath = TestUtils.DATA_DIR + "seg/Broad.080528.subtypes.seg.gz"; ResourceLocator locator = new ResourceLocator(dataPath); List<Track> tracks = new TrackLoader().load(locator, genome); network.annotateAll(tracks);// w w w.j ava 2 s .c o m //Check data Set<Node> nodes = network.vertexSet(); for (Node node : nodes) { for (String key : GeneNetwork.attributeMap.keySet()) { String data = GeneNetwork.getNodeKeyData(node, key); String name = GeneNetwork.getNodeKeyData(node, GeneNetwork.LABEL); if (!"CHMP3".equalsIgnoreCase(name)) { assertNotNull(data); } } } //Check schema Document doc = network.createDocument(); Node gml = doc.getFirstChild(); for (String key : GeneNetwork.attributeMap.keySet()) { String data = GeneNetwork.getNodeAttrValue(gml, "id", key); assertNotNull(data); } }
From source file:org.dbgl.util.searchengine.TheGamesDBSearchEngine.java
public WebProfile getEntryDetailedInformation(final WebProfile entry) throws UnknownHostException, IOException { WebProfile result = new WebProfile(); result.setTitle(entry.getTitle());/*w w w. ja v a 2 s.c o m*/ result.setYear(entry.getYear()); result.setUrl(entry.getUrl()); result.setPlatform(entry.getPlatform()); try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(getInputStream(entry.getUrl())); Element gameNode = (Element) doc.getFirstChild(); result.setDeveloperName(StringUtils.defaultString(XmlUtils.getTextValue(gameNode, "Developer"))); result.setPublisherName(StringUtils.defaultString(XmlUtils.getTextValue(gameNode, "Publisher"))); result.setNotes(StringUtils.defaultString(XmlUtils.getTextValue(gameNode, "Overview"))); String rating = XmlUtils.getTextValue(gameNode, "Rating"); if (rating != null) result.setRank((int) ((Double.parseDouble(rating) * 10.0) + 0.5)); else result.setRank(0); result.setCoreGameCoverUrl(XmlUtils.getTextValue(gameNode, "baseImgUrl")); result.setXmlElementWithAllImages(XmlUtils.getNode(gameNode, "Images")); StringBuffer genre = new StringBuffer(); Element el = XmlUtils.getNode(gameNode, "Genres"); if (el != null) { NodeList genreNodes = el.getChildNodes(); for (int i = 0; i < genreNodes.getLength(); i++) { if (i > 0) genre.append(", "); genre.append(genreNodes.item(i).getFirstChild().getNodeValue()); } } result.setGenre(genre.toString()); result.setUrl(absoluteUrl(THE_GAMES_DB_HOST_NAME, "/game/" + XmlUtils.getTextValue(gameNode, "id"))); } catch (ParserConfigurationException | SAXException e) { throw new IOException(e); } return result; }