Java Code Examples for org.w3c.dom.Document
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project addis, under directory /application/src/main/java/org/drugis/addis/imports/.
Source file: PubMedIDRetriever.java

public PubMedIdList importPubMedID(String StudyID) throws IOException { InputStream inOne=openUrl(PUBMED_API + "esearch.fcgi?db=pubmed&retmax=0&usehistory=y&term=" + StudyID+ "[Secondary%20Source%20ID]"); String resultsUrl=getResultsUrl(inOne); InputStream inTwo=openUrl(PUBMED_API + resultsUrl); Document docTwo=parse(inTwo); return getIdList(docTwo); }
Example 2
public void readConnectionsXML() throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder=dbFactory.newDocumentBuilder(); Document doc=dBuilder.parse(getClass().getResourceAsStream("/got/resource/xml/connection.xml")); doc.getDocumentElement().normalize(); NodeList nList=doc.getElementsByTagName("Connection"); for (int temp=0; temp < nList.getLength(); temp++) { Node nNode=nList.item(temp); String t1=nNode.getAttributes().getNamedItem("t1").getNodeValue(); String t2=nNode.getAttributes().getNamedItem("t2").getNodeValue(); getConnTerritories().get(t1).add(t2); getConnTerritories().get(t2).add(t1); } }
Example 3
From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/model/quests/qparser/.
Source file: AbstractParser.java

protected final void parseDocument(File f) throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); Document doc=factory.newDocumentBuilder().parse(f); for (Node start0=doc.getFirstChild(); start0 != null; start0=start0.getNextSibling()) { readData(start0); } }
Example 4
/** * Instantiates a new xml dom. * @param is Raw XML. * @throws SAXException the SAX exception */ public XmlDom(InputStream is) throws SAXException { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder=factory.newDocumentBuilder(); Document doc=builder.parse(is); this.root=(Element)doc.getDocumentElement(); } catch ( ParserConfigurationException e) { } catch ( IOException e) { throw new SAXException(e); } }
Example 5
From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.
Source file: ServerConfigParser.java

public List load(InputStream ins) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); Document doc=db.parse(ins); return loadConnectors(doc); }
Example 6
From project any23, under directory /core/src/main/java/org/apache/any23/extractor/html/.
Source file: TagSoupParser.java

/** * Returns the validated DOM and applies fixes on it if <i>applyFix</i> is set to <code>true</code>. * @param applyFix * @return a report containing the <i>HTML</i> DOM that has been validated and fixed if <i>applyFix</i>if <code>true</code>. The reports contains also information about the activated rules and the the detected issues. * @throws IOException * @throws org.apache.any23.validator.ValidatorException */ public DocumentReport getValidatedDOM(boolean applyFix) throws IOException, ValidatorException { final URI dURI; try { dURI=new URI(documentURI); } catch ( URISyntaxException urise) { throw new ValidatorException("Error while performing validation, invalid document URI.",urise); } Validator validator=new DefaultValidator(); Document document=getDOM(); return new DocumentReport(validator.validate(dURI,document,applyFix),document); }
Example 7
From project Archimedes, under directory /br.org.archimedes.io.xml.tests/plugin-test/br/org/archimedes/io/xml/parsers/.
Source file: NPointParserTestHelper.java

protected Node getNodeLine(String xmlSample) throws Exception { DocumentBuilderFactory docBuilderFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder=null; docBuilder=docBuilderFactory.newDocumentBuilder(); StringReader ir=new StringReader(xmlSample); InputSource is=new InputSource(ir); Document doc=docBuilder.parse(is); doc.normalize(); return doc.getFirstChild(); }
Example 8
From project arquillian-container-jbossas, under directory /jbossas-managed-4.2/src/main/java/org/jboss/arquillian/container/jbossas/managed_4_2/.
Source file: ManagementViewParser.java

private static List<String> extractServletNames(String descriptor) throws Exception { Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(descriptor.getBytes())); XPathExpression xPathExpression=XPathFactory.newInstance().newXPath().compile("/web-app/servlet/servlet-name"); NodeList nodes=(NodeList)xPathExpression.evaluate(doc,XPathConstants.NODESET); List<String> servletNames=new ArrayList<String>(); for (int i=0; i < nodes.getLength(); i++) { Node node=nodes.item(i); servletNames.add(node.getTextContent()); } return servletNames; }
Example 9
From project arquillian-core, under directory /config/impl-base/src/test/java/org/jboss/arquillian/config/descriptor/impl/.
Source file: AssertXPath.java

/** * Assert that the specified XPath Expression resolves to the specified values. <br/><br/> Assertions:<br/> "ExpectedValue count should match found Node count" <br/> "XPath content should match expected value" <br/> * @param xml The XML to assert against * @param expression XPath expression to extract * @param expectedValue The Expected values found by expression * @throws Exception XML/XPath related parse exceptions */ public static void assertXPath(String xml,String expression,Object... expectedValue) throws Exception { Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes())); XPathExpression xPathExpression=XPathFactory.newInstance().newXPath().compile(expression); NodeList nodes=(NodeList)xPathExpression.evaluate(doc,XPathConstants.NODESET); Assert.assertEquals("ExpectedValue count should match found Node count",expectedValue.length,nodes.getLength()); for (int i=0; i < nodes.getLength(); i++) { Node node=nodes.item(i); Assert.assertEquals("XPath content should match expected value",String.valueOf(expectedValue[i]),node.getTextContent()); } }
Example 10
From project arquillian_deprecated, under directory /containers/jbossas-remote-5/src/main/java/org/jboss/arquillian/container/jbossas/remote_5_0/.
Source file: ManagementViewParser.java

private static List<String> extractServletNames(String descriptor) throws Exception { Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(descriptor.getBytes())); XPathExpression xPathExpression=XPathFactory.newInstance().newXPath().compile("/web-app/servlet/servlet-name"); NodeList nodes=(NodeList)xPathExpression.evaluate(doc,XPathConstants.NODESET); List<String> servletNames=new ArrayList<String>(); for (int i=0; i < nodes.getLength(); i++) { Node node=nodes.item(i); servletNames.add(node.getTextContent()); } return servletNames; }
Example 11
From project as3-commons-jasblocks, under directory /src/main/java/org/as3commons/asblocks/impl/.
Source file: SWCResourceRoot.java

private List<ASQName> readCatalog(InputStream in) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { Document doc=loadDoc(in); XPathFactory fact=XPathFactory.newInstance(); XPath xpath=fact.newXPath(); NodeList list=(NodeList)xpath.evaluate("/swc/libraries/library/script/def",doc,XPathConstants.NODESET); List<ASQName> result=new ArrayList<ASQName>(); for (int i=0; i < list.getLength(); i++) { Element def=(Element)list.item(i); String defined=def.getAttribute("id"); result.add(toQName(defined)); } return result; }
Example 12
From project azure-sdk-for-java-samples, under directory /WAAD.WebSSO.JAVA/java/code/libraries/waad-federation/src/main/java/com/microsoft/samples/federation/.
Source file: SamlTokenValidator.java

private static SignableSAMLObject getSamlTokenFromSamlResponse(String samlResponse) throws ParserConfigurationException, SAXException, IOException, UnmarshallingException { Document document=getDocument(samlResponse); Unmarshaller unmarshaller=Configuration.getUnmarshallerFactory().getUnmarshaller(document.getDocumentElement()); org.opensaml.saml2.core.Response response=(org.opensaml.saml2.core.Response)unmarshaller.unmarshall(document.getDocumentElement()); SignableSAMLObject samlToken=(SignableSAMLObject)response.getAssertions().get(0); return samlToken; }
Example 13
From project big-data-plugin, under directory /test-src/org/pentaho/di/job/.
Source file: AbstractJobEntryTest.java

@Test public void testLoadXml() throws Exception { TestJobEntry jobEntry=new TestJobEntry(); BlockableJobConfig jobConfig=new BlockableJobConfig(); jobConfig.setJobEntryName("Job Name"); jobEntry.setJobConfig(jobConfig); JobEntryCopy jec=new JobEntryCopy(jobEntry); jec.setLocation(0,0); String xml=jec.getXML(); Document d=XMLHandler.loadXMLString(xml); TestJobEntry jobEntry2=new TestJobEntry(); jobEntry2.loadXML(d.getDocumentElement(),null,null,null); BlockableJobConfig jobConfig2=jobEntry2.getJobConfig(); assertEquals(jobConfig.getJobEntryName(),jobConfig2.getJobEntryName()); }
Example 14
From project bioportal-service, under directory /src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/identity/.
Source file: IdentityConverter.java

private int getHighestVersionId(String xml){ int highestVersionId=0; Document document=BioportalRestUtils.getDocument(xml); List<Node> nodeList=TransformUtils.getNodeListWithPath(document,"success.data.list.ontologyBean"); for ( Node node : nodeList) { String ontologyVersionId=TransformUtils.getNamedChildText(node,ONTOLOGY_VERSION_ID); int versionId=Integer.parseInt(ontologyVersionId); if (versionId > highestVersionId) { highestVersionId=versionId; } } return highestVersionId; }
Example 15
From project blacktie, under directory /blacktie-admin-services/src/main/java/org/jboss/narayana/blacktie/administration/.
Source file: BlacktieStompAdministrationService.java

Element stringToElement(String s) throws Exception { StringReader sreader=new StringReader(s); DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder parser=factory.newDocumentBuilder(); Document doc=parser.parse(new InputSource(sreader)); return doc.getDocumentElement(); }
Example 16
From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.
Source file: Parser.java

/** * Parse an input stream for blueprint xml. * @param inputStream The data to parse. The caller is responsible for closing the stream afterwards. * @throws Exception on parse error */ public void parse(InputStream inputStream) throws Exception { InputSource inputSource=new InputSource(inputStream); DocumentBuilder builder=getDocumentBuilderFactory().newDocumentBuilder(); Document doc=builder.parse(inputSource); documents.add(doc); }
Example 17
From project bndtools, under directory /bndtools.core/src/bndtools/launch/.
Source file: BndDependencySourceContainerType.java

public String getMemento(ISourceContainer container) throws CoreException { Document document=newDocument(); Element element=document.createElement("default"); document.appendChild(element); return serializeDocument(document); }
Example 18
From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/control/util/.
Source file: BPELUnitUtil.java

/** * Creates a new document with a dummy root node, intended to store literal data for a receive or send. CAUTION: This method depends on initialization which is done by calling {@link initializeParsing}. Not initializing this class will cause uncaught NPEs. * @return */ public static Element generateDummyElementNode(){ Document document=fgDocumentBuilder.newDocument(); Element root=document.createElement(DUMMY_ELEMENT_NAME); document.appendChild(root); return root; }
Example 19
From project BukkitUtilities, under directory /src/main/java/name/richardson/james/bukkit/utilities/updater/.
Source file: MavenManifest.java

public MavenManifest(final File file) throws SAXException, IOException, ParserConfigurationException { final DocumentBuilderFactory docBuilderFactory=DocumentBuilderFactory.newInstance(); final DocumentBuilder docBuilder=docBuilderFactory.newDocumentBuilder(); final Document doc=docBuilder.parse(file); doc.getDocumentElement().normalize(); final NodeList root=doc.getChildNodes(); final Node meta=this.getNode("metadata",root); final Node versioning=this.getNode("versioning",meta.getChildNodes()); final Node versions=this.getNode("versions",versioning.getChildNodes()); final NodeList nodes=versions.getChildNodes(); this.setVersionList(nodes); file.deleteOnExit(); }
Example 20
From project C-Cat, under directory /util/src/main/java/gov/llnl/ontology/text/corpora/.
Source file: NYTDocumentReader.java

/** * Parse an New York Times Document from a file. * @param file The file from which to parse the document. * @param disableValidation True if the file is to be validated against thenitf DTD and false if it is not. It is recommended that validation be disabled, as all documents in the corpus have previously been validated against the NITF DTD. * @return The parsed document, or null if an error occurs. */ public static NYTCorpusDocument parseNYTCorpusDocumentFromFile(File file,boolean validating){ Document document=null; if (validating) { document=loadValidating(file); } else { document=loadNonValidating(file); } return parseNYTCorpusDocumentFromDOMDocument(file,document); }
Example 21
From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.
Source file: FileUtils.java

public static Document readXML(File file){ if (!file.exists()) return null; Document doc=null; try { DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db; db=dbf.newDocumentBuilder(); doc=db.parse(file); doc.getDocumentElement().normalize(); } catch ( Exception e) { System.err.println("XML read/parse Error: " + e); e.printStackTrace(); } return doc; }
Example 22
From project Absolute-Android-RSS, under directory /src/com/AA/Other/.
Source file: RSSParse.java

/** * Get the list of articles currently contained in the RSS feed. * @param isBackground if the request is being run in the background * @param callingContext current application context * @return List of articles contained in the RSS on success. On failure returns null */ public static List<Article> getArticles(boolean isBackground,Context callingContext){ if (!isNetworkAvailable(isBackground,callingContext)) return null; Document doc=getDocument(); if (doc == null) return null; try { ArrayList<Article> articles=new ArrayList<Article>(); NodeList items=doc.getElementsByTagName("item"); for (int i=0; i < items.getLength(); i++) { Element el=(Element)items.item(i); String title=el.getElementsByTagName("title").item(0).getFirstChild().getNodeValue(); String date=el.getElementsByTagName("pubDate").item(0).getFirstChild().getNodeValue(); String url=el.getElementsByTagName("link").item(0).getFirstChild().getNodeValue(); String desc=el.getElementsByTagName("description").item(0).getFirstChild().getNodeValue(); articles.add(new Article(desc,title,date,url)); } return articles; } catch ( Exception e) { Log.e("AARSS","Error Parsing RSS",e); return null; } }
Example 23
From project activemq-apollo, under directory /apollo-selector/src/main/java/org/apache/activemq/apollo/filter/.
Source file: XalanXPathEvaluator.java

protected boolean evaluate(InputSource inputSource){ try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder dbuilder=factory.newDocumentBuilder(); Document doc=dbuilder.parse(inputSource); CachedXPathAPI cachedXPathAPI=new CachedXPathAPI(); XObject result=cachedXPathAPI.eval(doc,xpath); if (result.bool()) return true; else { NodeIterator iterator=cachedXPathAPI.selectNodeIterator(doc,xpath); return (iterator.nextNode() != null); } } catch ( Throwable e) { return false; } }
Example 24
From project adt-maven-plugin, under directory /src/main/java/com/yelbota/plugins/adt/model/.
Source file: AneModel.java

private void parseXml(byte[] s) throws MojoFailureException { DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); try { DocumentBuilder db=dbf.newDocumentBuilder(); Document dom=db.parse(new InputSource(new ByteArrayInputStream(s))); NodeList nl=dom.getDocumentElement().getChildNodes(); for (int i=0; i < nl.getLength(); i++) { Object uel=nl.item(i); if (uel instanceof Element) { Element el=(Element)uel; String nodeName=el.getNodeName(); if (nodeName.equals("id")) id=el.getTextContent(); } } } catch ( ParserConfigurationException e) { throwParseFail(file,e); } catch ( SAXException e) { throwParseFail(file,e); } catch ( IOException e) { throwParseFail(file,e); } }
Example 25
From project android-joedayz, under directory /Proyectos/LectorFeeds/src/com/android/joedayz/demo/.
Source file: XMLParser.java

public LinkedList<HashMap<String,String>> parse(){ DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); LinkedList<HashMap<String,String>> entries=new LinkedList<HashMap<String,String>>(); HashMap<String,String> entry; try { DocumentBuilder builder=factory.newDocumentBuilder(); Document dom=builder.parse(this.url.openConnection().getInputStream()); Element root=dom.getDocumentElement(); NodeList items=root.getElementsByTagName("item"); for (int i=0; i < items.getLength(); i++) { entry=new HashMap<String,String>(); Node item=items.item(i); NodeList properties=item.getChildNodes(); for (int j=0; j < properties.getLength(); j++) { Node property=properties.item(j); String name=property.getNodeName(); if (name.equalsIgnoreCase("title")) { entry.put(Main.DATA_TITLE,property.getFirstChild().getNodeValue()); } else if (name.equalsIgnoreCase("link")) { entry.put(Main.DATA_LINK,property.getFirstChild().getNodeValue()); } } entries.add(entry); } } catch ( Exception e) { throw new RuntimeException(e); } return entries; }
Example 26
From project android_external_tagsoup, under directory /src/org/ccil/cowan/tagsoup/jaxp/.
Source file: JAXPTest.java

private void test(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java " + getClass() + " [input-file]"); System.exit(1); } File f=new File(args[0]); System.setProperty("javax.xml.parsers.SAXParserFactory","org.ccil.cowan.tagsoup.jaxp.SAXFactoryImpl"); SAXParserFactory spf=SAXParserFactory.newInstance(); System.out.println("Ok, SAX factory JAXP creates is: " + spf); System.out.println("Let's parse..."); spf.newSAXParser().parse(f,new org.xml.sax.helpers.DefaultHandler()); System.out.println("Done. And then DOM build:"); Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f); System.out.println("Succesfully built DOM tree from '" + f + "', -> "+ doc); }
Example 27
From project ant4eclipse, under directory /org.ant4eclipse.ant.pde/src/org/ant4eclipse/ant/pde/.
Source file: PatchFeatureManifestTask.java

/** * Replaces the given plug-in-versions in given feature.xml-File. * @param featureXml The feature.xml file. NOTE: this file will be <b>changed</b> and thus must be writable * @param qualifier The new version for this feature. If set to null, the "version"-attribute of the "feature"-tag won't be changed * @param newBundleVersions A map containing plugin-id (String) - version (String) associations * @throws Exception */ protected void replaceVersions(File featureXml,String qualifier,StringMap newBundleVersions) throws Exception { Assure.notNull("featureXml",featureXml); Assure.assertTrue(featureXml.isFile(),"featureXml (" + featureXml + ") must point to an existing file"); DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document featureDom=builder.parse(featureXml); if (qualifier != null) { Element featureElement=featureDom.getDocumentElement(); String featureVersion=featureElement.getAttribute("version"); if (featureVersion != null && featureVersion.endsWith(".qualifier")) { featureElement.setAttribute("version",PdeBuildHelper.resolveVersion(new Version(featureVersion),qualifier).toString()); } } NodeList pluginNodes=featureDom.getDocumentElement().getElementsByTagName("plugin"); for (int i=0; i < pluginNodes.getLength(); i++) { Element element=(Element)pluginNodes.item(i); String id=element.getAttribute("id"); if (newBundleVersions.containsKey(id)) { String version=newBundleVersions.get(id); element.setAttribute("version",version); } } DOMSource domSource=new DOMSource(featureDom); Transformer transformer=TransformerFactory.newInstance().newTransformer(); StreamResult result=new StreamResult(featureXml); transformer.transform(domSource,result); }
Example 28
/** * Runs the IdeaTask and creates/updates the Idea .ipr project file */ @Override public void execute(){ final File ideaFile=ideaFile(id,".ipr"); if (mustBuild(ideaFile)) { Document document=readIdeaFile(ideaFile,DEFAULT_PROJECT_TEMPLATE); Element docElement=document.getDocumentElement(); if (jdkName.isEmpty()) { jdkName=System.getProperty("java.specification.version"); env.logInfo("jdkName is not set, using [java version %s] as default.%n",jdkName); } setJdkName(docElement,jdkName); setWildcardResourcePatterns(docElement,"!?*.java"); Element modulesElement=findElement(findComponent(docElement,"ProjectModuleManager"),"modules"); removeOldElements(modulesElement,"module"); Set<String> groups=calculateGroups(); for ( String mod : modules) { addModuleToProject(mod,modulesElement,groups); } generateProjectDefinitionsModule(modulesElement,projectDirectory,projectDirectory.getName()); Element libraryTable=findComponent(docElement,"libraryTable"); removeOldElements(libraryTable,"library"); filterLibraries(libraries); checkDuplicates(libraries); for ( Library lib : libraries) { addLibrary(lib,libraryTable); } if (libraryTable.getChildNodes().item(0) == null) { docElement.removeChild(libraryTable); } writeDocument(env,ideaFile,document); } }
Example 29
From project apps-for-android, under directory /CLiCkin2DaBeaT/src/com/google/clickin2dabeat/.
Source file: C2B.java

private void loadC2B(String fileUriString){ try { FileInputStream fis=new FileInputStream(fileUriString); DocumentBuilder docBuild; docBuild=DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document c2b=docBuild.parse(fis); runC2B(c2b); } catch ( FileNotFoundException e) { e.printStackTrace(); } catch ( ParserConfigurationException e) { e.printStackTrace(); } catch ( FactoryConfigurationError e) { e.printStackTrace(); } catch ( SAXException e) { e.printStackTrace(); } catch ( IOException e) { e.printStackTrace(); } }
Example 30
From project aranea, under directory /server/src/main/java/no/dusken/aranea/admin/control/.
Source file: ImportStvMediaController.java

public ModelAndView handleRequest(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception { if (isImporting) { log.error("import already running"); return new ModelAndView("redirect:/"); } else { isImporting=true; } URI uri=new URI(feedUrl); URL url=uri.toURL(); File file=new File(cacheDirectory + "/" + "feed.xml"); FileUtils.copyURLToFile(url,file); Document doc=parseXmlFile(file); Element docEle=doc.getDocumentElement(); NodeList nl=docEle.getElementsByTagName("item"); if (nl != null && nl.getLength() > 0) { for (int i=0; i < nl.getLength(); i++) { Element el=(Element)nl.item(i); MediaResource mr=getMediaResource(el); if (!isInDb(mr)) { mediaResourceService.saveOrUpdate(mr); log.info("Imported media, url: {}",mr.getUrlToResource()); } } } return new ModelAndView("redirect:/"); }
Example 31
From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/core/configuration/.
Source file: PersistenceDescriptorParser.java

public String obtainDataSourceName(final String descriptor){ try { final Document document=factory.newDocumentBuilder().parse(new ByteArrayInputStream(descriptor.getBytes())); final NodeList persistenceUnits=document.getElementsByTagName("persistence-unit"); if (persistenceUnits.getLength() > 1) { throw new MultiplePersistenceUnitsException("Multiple persistence units defined. Please specify default data source either in 'arquillian.xml' or by using @DataSource annotation"); } final Node persistenceUnit=persistenceUnits.item(0); Node dataSource=getJtaDataSource(persistenceUnit); if (dataSource == null) { dataSource=getNonJtaDataSource(persistenceUnit); } return dataSource.getTextContent(); } catch ( SAXException e) { throw new PersistenceDescriptorParsingException("Unable to parse descriptor " + descriptor,e); } catch ( IOException e) { throw new PersistenceDescriptorParsingException("Unable to parse descriptor " + descriptor,e); } catch ( ParserConfigurationException e) { throw new PersistenceDescriptorParsingException("Unable to parse descriptor " + descriptor,e); } }
Example 32
From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/coreutils/.
Source file: XMLUtil.java

/** * Loads XML files from disk * @param clazz the class this method is invoked from * @param xmlPath the full path to the file to load * @param xsdPath the full path to the file to validate against */ public static Document loadDoc(Class clazz,String xmlPath,String xsdPath){ DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance(); Document ret=null; try { DocumentBuilder builder=builderFactory.newDocumentBuilder(); ret=builder.parse(new FileInputStream(xmlPath)); } catch ( ParserConfigurationException e) { Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Error loading XML file: can't initialize parser.",e); } catch ( SAXException e) { Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Error loading XML file: can't parse XML.",e); } catch ( IOException e) { Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Error loading XML file: can't read file.",e); } if (!XMLUtil.xmlIsValid(ret,clazz,xsdPath)) { Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Error loading XML file: could not validate against [" + xsdPath + "], results may not be accurate"); } return ret; }
Example 33
From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/regions/.
Source file: RegionMetadataParser.java

/** * Parses the specified input stream and returns a list of the regions declared in it. * @param input The stream containing the region metadata to parse. * @return The list of parsed regions. */ public List<Region> parseRegionMetadata(InputStream input){ Document document; try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder=factory.newDocumentBuilder(); document=documentBuilder.parse(input); } catch ( Exception e) { throw new RuntimeException("Unable to parse region metadata file: " + e.getMessage(),e); } NodeList regionNodes=document.getElementsByTagName(REGION_TAG); List<Region> regions=new ArrayList<Region>(); for (int i=0; i < regionNodes.getLength(); i++) { Node node=regionNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element=(Element)node; regions.add(parseRegionElement(element)); } } return regions; }
Example 34
From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/cron/.
Source file: CronService.java

/** * Loads cron.xml. */ private static void loadCronXML(){ final String webRoot=AbstractServletListener.getWebRoot(); final File cronXML=new File(webRoot + File.separator + "WEB-INF"+ File.separator+ "cron.xml"); if (!cronXML.exists()) { LOGGER.log(Level.INFO,"Not found cron.xml, no cron jobs need to schedule"); return; } final DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance(); try { final DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder(); final Document document=documentBuilder.parse(cronXML); final Element root=document.getDocumentElement(); root.normalize(); final NodeList crons=root.getElementsByTagName("cron"); LOGGER.log(Level.CONFIG,"Reading cron jobs: "); for (int i=0; i < crons.getLength(); i++) { final Element cronElement=(Element)crons.item(i); final Element urlElement=(Element)cronElement.getElementsByTagName("url").item(0); final Element descriptionElement=(Element)cronElement.getElementsByTagName("description").item(0); final Element scheduleElement=(Element)cronElement.getElementsByTagName("schedule").item(0); final String url=urlElement.getTextContent(); final String description=descriptionElement.getTextContent(); final String schedule=scheduleElement.getTextContent(); LOGGER.log(Level.CONFIG,"Cron[url={0}, description={1}, schedule={2}]",new Object[]{url,description,schedule}); CRONS.add(new Cron(url,description,schedule)); } } catch ( final Exception e) { LOGGER.log(Level.SEVERE,"Reads cron.xml failed",e); throw new RuntimeException(e); } }
Example 35
From project bbb-java, under directory /src/main/java/org/mconf/bbb/api/.
Source file: JoinedMeeting.java

public void parse(String str) throws UnsupportedEncodingException, SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); Document doc=db.parse(new ByteArrayInputStream(str.getBytes("UTF-8"))); doc.getDocumentElement().normalize(); Element nodeResponse=(Element)doc.getElementsByTagName("response").item(0); returncode=ParserUtils.getNodeValue(nodeResponse,"returncode"); if (returncode.equals("SUCCESS")) { fullname=ParserUtils.getNodeValue(nodeResponse,"fullname"); confname=ParserUtils.getNodeValue(nodeResponse,"confname"); meetingID=ParserUtils.getNodeValue(nodeResponse,"meetingID"); externUserID=ParserUtils.getNodeValue(nodeResponse,"externUserID"); role=ParserUtils.getNodeValue(nodeResponse,"role"); conference=ParserUtils.getNodeValue(nodeResponse,"conference"); room=ParserUtils.getNodeValue(nodeResponse,"room"); voicebridge=ParserUtils.getNodeValue(nodeResponse,"voicebridge"); webvoiceconf=ParserUtils.getNodeValue(nodeResponse,"webvoiceconf"); mode=ParserUtils.getNodeValue(nodeResponse,"mode"); record=ParserUtils.getNodeValue(nodeResponse,"record"); welcome=ParserUtils.getNodeValue(nodeResponse,"welcome"); server=ParserUtils.getNodeValue(nodeResponse,"server"); } else { message=ParserUtils.getNodeValue(nodeResponse,"message"); } }
Example 36
From project bioclipse.speclipse, under directory /plugins/net.bioclipse.nmrshiftdb/src/net/bioclipse/nmrshiftdb/business/.
Source file: NmrshiftdbManager.java

public String getSpectrumTypes(String serverurl) throws BioclipseException { try { Options opts=new Options(new String[0]); opts.setDefaultURL(serverurl + "/services/NMRShiftDB"); Service service=new Service(); Call call=(Call)service.createCall(); call.setOperationName("getSpectrumTypes"); call.setTargetEndpointAddress(new URL(opts.getURL())); DocumentBuilder builder; builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); SOAPBodyElement[] input=new SOAPBodyElement[1]; Document doc=builder.newDocument(); Element cdataElem; cdataElem=doc.createElementNS(opts.getURL(),"getSpectrumTypes"); input[0]=new SOAPBodyElement(cdataElem); Vector elems=(Vector)call.invoke(input); SOAPBodyElement elem=null; Element e=null; elem=(SOAPBodyElement)elems.get(0); e=elem.getAsDOM(); return e.getFirstChild().getTextContent(); } catch ( Exception ex) { throw new BioclipseException(ex.getMessage()); } }
Example 37
From project BMach, under directory /src/jsyntaxpane/actions/.
Source file: XmlPrettifyAction.java

@Override public void actionPerformed(ActionEvent e){ if (transformer == null) { return; } JTextComponent target=getTextComponent(e); try { SyntaxDocument sdoc=ActionUtils.getSyntaxDocument(target); StringWriter out=new StringWriter(sdoc.getLength()); StringReader reader=new StringReader(target.getText()); InputSource src=new InputSource(reader); Document doc=getDocBuilder().parse(src); getTransformer().transform(new DOMSource(doc),new StreamResult(out)); target.setText(out.toString()); } catch ( SAXParseException ex) { showErrorMessage(target,String.format("XML error: %s\nat(%d, %d)",ex.getMessage(),ex.getLineNumber(),ex.getColumnNumber())); ActionUtils.setCaretPosition(target,ex.getLineNumber(),ex.getColumnNumber() - 1); } catch ( TransformerException ex) { showErrorMessage(target,ex.getMessageAndLocation()); } catch ( SAXException ex) { showErrorMessage(target,ex.getLocalizedMessage()); } catch ( IOException ex) { showErrorMessage(target,ex.getLocalizedMessage()); } }
Example 38
From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.
Source file: BoneCPConfig.java

/** * @param xmlConfigFile * @param sectionName * @throws Exception */ private void setXMLProperties(InputStream xmlConfigFile,String sectionName) throws Exception { DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db; try { db=dbf.newDocumentBuilder(); Document doc=db.parse(xmlConfigFile); doc.getDocumentElement().normalize(); Properties settings=parseXML(doc,null); if (sectionName != null) { settings.putAll(parseXML(doc,sectionName)); } setProperties(settings); } catch ( Exception e) { throw e; } }
Example 39
From project Cafe, under directory /webapp/src/org/openqa/selenium/os/.
Source file: WindowsUtils.java

/** * Returns a map of process IDs to command lines * @return a map of process IDs to command lines * @throws Exception - if something goes wrong while reading the process list */ public static Map procMap() throws Exception { log.info("Reading Windows Process List..."); String output=executeCommand(findWMIC(),"process","list","full","/format:rawxml.xsl"); log.info("Done, searching for processes to kill..."); File TempWmicBatchFile=new File("TempWmicBatchFile.bat"); if (TempWmicBatchFile.exists()) { TempWmicBatchFile.delete(); } Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(output.getBytes())); NodeList procList=doc.getElementsByTagName("INSTANCE"); Map<String,String> processes=new HashMap<String,String>(); for (int i=0; i < procList.getLength(); i++) { Element process=(Element)procList.item(i); NodeList propList=process.getElementsByTagName("PROPERTY"); Map<String,Object> procProps=new HashMap<String,Object>(); for (int j=0; j < propList.getLength(); j++) { Element property=(Element)propList.item(j); String propName=property.getAttribute("NAME"); NodeList valList=property.getElementsByTagName("VALUE"); String value=null; if (valList.getLength() != 0) { Element valueElement=(Element)valList.item(0); Text valueNode=(Text)valueElement.getFirstChild(); value=valueNode.getData(); } procProps.put(propName,value); } String processID=(String)procProps.get("ProcessId"); String commandLine=(String)procProps.get("CommandLine"); processes.put(commandLine,processID); } return processes; }
Example 40
From project anadix, under directory /anadix-core/src/main/java/org/anadix/impl/.
Source file: XHTMLReportFormatter.java

private static Node createXHTMLHeading(Report report,Document doc){ Node html=doc.appendChild(doc.createElement("html")); Node head=html.appendChild(doc.createElement("head")); Node title=head.appendChild(doc.createElement("title")); title.setTextContent(String.format("Anadix report for '%s'",report.getSource().getDescription())); Node style=head.appendChild(doc.createElement("style")); style.setTextContent(STYLE); return html.appendChild(doc.createElement("body")); }
Example 41
From project android-client_1, under directory /src/com/googlecode/asmack/.
Source file: XMLUtils.java

/** * Turn an XML String into a DOM. * @param xml The xml String. * @return A XML Document. * @throws SAXException In case of invalid XML. */ public static Document getDocument(String xml) throws SAXException { try { DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder(); return documentBuilder.parse(new InputSource(new StringReader(xml))); } catch ( ParserConfigurationException e) { throw new IllegalStateException("Parser not configured",e); } catch ( IOException e) { throw new IllegalStateException("IOException on read-from-memory",e); } }
Example 42
From project AsmackService, under directory /src/com/googlecode/asmack/.
Source file: XMLUtils.java

/** * Turn an XML String into a DOM. * @param xml The xml String. * @return A XML Document. * @throws SAXException In case of invalid XML. */ public static Document getDocument(String xml) throws SAXException { try { DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder(); return documentBuilder.parse(new InputSource(new StringReader(xml))); } catch ( ParserConfigurationException e) { throw new IllegalStateException("Parser not configured",e); } catch ( IOException e) { throw new IllegalStateException("IOException on read-from-memory",e); } }
Example 43
From project bam, under directory /release/jbossas/tests/activity-management/bean-service/src/main/java/org/overlord/bam/tests/actmgmt/jbossas/beanservice/.
Source file: Transformers.java

private Element toElement(String xml){ DOMResult dom=new DOMResult(); try { TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new StringReader(xml)),dom); } catch ( Exception ex) { ex.printStackTrace(); } return ((Document)dom.getNode()).getDocumentElement(); }
Example 44
From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/org/openscience/cdk/structgen/pubchem/.
Source file: PubchemStructureGenerator.java

/** * @throws Exception * @since JAVA5 */ private static Node xpathJDK5(String pathString,Document doc) throws Exception { XPath xpath=XPathFactory.newInstance().newXPath(); try { Node node=((Node)xpath.evaluate(pathString,doc,XPathConstants.NODE)); return node; } catch ( DOMException e) { throw new Exception(e.toString()); } catch ( XPathExpressionException e) { throw new Exception(e.toString()); } }
Example 45
From project blog_1, under directory /miniprojects/generic-pojo-mappers/src/main/java/net/jakubholy/blog/genericmappers/xml/.
Source file: XmlElements.java

private static Document parseXmlToDocument(String xml) throws RuntimeException { DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); try { DocumentBuilder builder=builderFactory.newDocumentBuilder(); InputSource is=new InputSource(new StringReader(xml)); return builder.parse(is); } catch ( SAXException e) { throw new RuntimeException("Parsing XML failed: " + e + ", xml: "+ xml,e); } catch ( IOException e) { throw new RuntimeException("Parsing XML failed: " + e + ", xml: "+ xml,e); } catch ( ParserConfigurationException e) { throw new RuntimeException("Parsing XML failed: " + e + ", xml: "+ xml,e); } }