Java Code Examples for javax.xml.parsers.DocumentBuilderFactory
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
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 2
From project cidb, under directory /ncbieutils-access-service/src/main/java/edu/toronto/cs/cidb/ncbieutils/.
Source file: NCBIEUtilsAccessService.java

private org.w3c.dom.Document readXML(String url){ try { BufferedInputStream in=new BufferedInputStream(new URL(url).openStream()); DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder=dbFactory.newDocumentBuilder(); org.w3c.dom.Document result=dBuilder.parse(in); result.getDocumentElement().normalize(); return result; } catch ( Exception ex) { this.logger.error("Error while trying to retrieve data from URL " + url + " "+ ex.getClass().getName()+ " "+ ex.getMessage(),ex); return null; } }
Example 3
From project as3-commons-jasblocks, under directory /src/main/java/org/as3commons/asblocks/impl/.
Source file: SWCResourceRoot.java

private Document loadDoc(InputStream in) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory fact=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=fact.newDocumentBuilder(); InputSource is=new InputSource(in); is.setSystemId(CATALOG_FILENAME); return builder.parse(is); }
Example 4
From project addis, under directory /application/src/main/java/org/drugis/addis/util/.
Source file: ConvertDiabetesDatasetUtil.java

private Document getPubMedXML(PubMedIdList pubmed) throws ParserConfigurationException, IOException, SAXException { String id=pubmed.get(0).getId(); String url=PubMedIDRetriever.PUBMED_API + "efetch.fcgi?db=pubmed&id=" + id+ "&retmode=xml"; DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setNamespaceAware(false); dbf.setIgnoringElementContentWhitespace(true); DocumentBuilder db=dbf.newDocumentBuilder(); InputStream openStream=PubMedIDRetriever.openUrl(url); Document doc=db.parse(openStream); return doc; }
Example 5
From project agile, under directory /agile-storage/src/main/java/org/headsupdev/agile/storage/.
Source file: HibernateUtil.java

/** * Parse a document with validation switched off and the loading of external dtds disabled * @param resourcePath The path to a resource on the classpath * @return a parsed document, without validation * @throws Exception if there was a problem parsing the file */ public static org.w3c.dom.Document parseConfiguration(String resourcePath) throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setAttribute("http://xml.org/sax/features/validation",Boolean.FALSE); factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd",Boolean.FALSE); DocumentBuilder builder=factory.newDocumentBuilder(); return builder.parse(builder.getClass().getResourceAsStream(resourcePath)); }
Example 6
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 7
/** * 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 8
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 9
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 10
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 Document getDocument(String doc) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder documentbuilder=factory.newDocumentBuilder(); return documentbuilder.parse(new InputSource(new StringReader(doc))); }
Example 11
From project bbb-java, under directory /src/main/java/org/mconf/bbb/api/.
Source file: ParserConfiguration.java

public ParserConfiguration(String xml) throws Exception { log.debug(xml); DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); doc=db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8"))); doc.getDocumentElement().normalize(); }
Example 12
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 13
From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.
Source file: Parser.java

private static DocumentBuilderFactory getDocumentBuilderFactory(){ if (documentBuilderFactory == null) { DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); documentBuilderFactory=dbf; } return documentBuilderFactory; }
Example 14
From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/model/test/data/.
Source file: SendDataSpecification.java

private void generateLiteralDataFromTemplate(ActivityContext context){ try { String expandedTemplate=expandTemplateToString(context,fDataTemplate); DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document docExpanded=dbf.newDocumentBuilder().parse(new InputSource(new StringReader(expandedTemplate))); fLiteralData=docExpanded.getDocumentElement(); context.saveSentMessage(fLiteralData); } catch ( Exception ex) { setStatus(ArtefactStatus.createErrorStatus("Template expansion fault: " + ex.getLocalizedMessage(),ex)); } }
Example 15
From project bpm-console, under directory /server/war/src/main/java/org/jboss/bpm/console/server/util/.
Source file: DOMUtils.java

protected DocumentBuilder initialValue(){ try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); DocumentBuilder builder=factory.newDocumentBuilder(); setEntityResolver(builder); return builder; } catch ( ParserConfigurationException e) { throw new RuntimeException("Failed to create DocumentBuilder",e); } }
Example 16
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 17
From project C-Cat, under directory /util/src/main/java/gov/llnl/ontology/text/corpora/.
Source file: NYTDocumentReader.java

/** * Parse a file containing an XML document, into a DOM object. * @param filename A path to a valid file. * @param validating True iff validating should be turned on. * @return A DOM Object containing a parsed XML document or a null value ifthere is an error in parsing. * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ private static Document getDOMObject(String filename,boolean validating) throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); if (!validating) { factory.setValidating(validating); factory.setSchema(null); factory.setNamespaceAware(false); } DocumentBuilder builder=factory.newDocumentBuilder(); Document doc=builder.parse(new File(filename)); return doc; }
Example 18
From project capedwarf-blue, under directory /common/src/main/java/org/jboss/capedwarf/common/xml/.
Source file: XmlUtils.java

public static Document parseXml(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder=dbFactory.newDocumentBuilder(); Document doc=dBuilder.parse(inputStream); doc.getDocumentElement().normalize(); return doc; }
Example 19
From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/util/.
Source file: SamlUtils.java

private static org.w3c.dom.Document toDom(final Document doc){ try { final XMLOutputter xmlOutputter=new XMLOutputter(); final StringWriter elemStrWriter=new StringWriter(); xmlOutputter.output(doc,elemStrWriter); final byte[] xmlBytes=elemStrWriter.toString().getBytes(); final DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); return dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xmlBytes)); } catch ( final Exception e) { return null; } }
Example 20
From project cascading, under directory /src/xml/cascading/operation/xml/.
Source file: XPathOperation.java

@Override public void prepare(FlowProcess flowProcess,OperationCall<Pair<DocumentBuilder,Tuple>> operationCall){ try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); operationCall.setContext(new Pair<DocumentBuilder,Tuple>(factory.newDocumentBuilder(),Tuple.size(1))); } catch ( ParserConfigurationException exception) { throw new OperationException("could not create document builder",exception); } }
Example 21
From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/templatecompiler/model/.
Source file: ElementsHandler.java

/** * Default constructor. <p/> It is up to a JAXB provider to decide which DOM implementation to use or how that is configured. */ public ElementsHandler(){ DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance(); try { this.builder=docFactory.newDocumentBuilder(); } catch ( ParserConfigurationException e) { throw new IllegalArgumentException("No documentBuilderFactory"); } }
Example 22
From project cilia-workbench, under directory /cilia-workbench-common/src/fr/liglab/adele/cilia/workbench/common/xml/.
Source file: XMLHelpers.java

private static DocumentBuilder getDocumentBuilder() throws CiliaException { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder=factory.newDocumentBuilder(); } catch ( ParserConfigurationException e) { throw new CiliaException("Can't get document builder ",e); } return builder; }
Example 23
From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/azure/client/.
Source file: MicrosoftAzureModelUtils.java

private static DocumentBuilder createDocumentBuilder(){ DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); try { dbf.setNamespaceAware(false); return dbf.newDocumentBuilder(); } catch ( ParserConfigurationException e) { throw new IllegalStateException(e); } }
Example 24
From project codjo-segmentation, under directory /codjo-segmentation-server/src/main/java/net/codjo/segmentation/server/plugin/.
Source file: PreferenceGuiHome.java

private DocumentBuilder initFactory() throws ParserConfigurationException { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); builder.setErrorHandler(new MyErrorHandler()); return builder; }
Example 25
From project components, under directory /common/common/src/test/java/org/switchyard/component/common/selector/.
Source file: OperationSelectorTest.java

@Override protected Document extractDomDocument(String content) throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); InputSource is=new InputSource(new StringReader(extractString(content))); return builder.parse(is); }
Example 26
From project core_1, under directory /test/src/main/java/org/switchyard/test/.
Source file: SwitchYardTestKit.java

/** * Read a classpath resource and return as an XML DOM Document. * @param path The path to the classpath resource. The specified path can berelative to the test class' location on the classpath. * @return The resource as a Document. */ public Document readResourceDocument(String path){ try { DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db=dbf.newDocumentBuilder(); return db.parse(getResourceAsStream(path)); } catch ( Exception e) { Assert.fail("Unexpected exception reading classpath resource '" + path + "' as a DOM Document."+ e.getMessage()); return null; } }
Example 27
From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/xml/.
Source file: XMLUtils.java

public static String getXPathValue(IFile file,String xPath) throws Exception { DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(false); docFactory.setValidating(false); DocumentBuilder builder=docFactory.newDocumentBuilder(); XPathFactory factory=XPathFactory.newInstance(); XPath xpath=factory.newXPath(); final XPathExpression exp=xpath.compile(xPath); Document doc=builder.parse(new InputSource(file.getContents())); final NodeList nodeList=(NodeList)exp.evaluate(doc,XPathConstants.NODESET); return XMLUtils.getNodeValue(nodeList); }
Example 28
From project des, under directory /daemon/lib/apache-log4j-1.2.16/tests/src/java/org/apache/log4j/.
Source file: HTMLLayoutTest.java

/** * Parses the string as the body of an XML document and returns the document element. * @param source source string. * @return document element. * @throws Exception if parser can not be constructed or source is not a valid XML document. */ private Document parse(final String source) throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); factory.setCoalescing(true); DocumentBuilder builder=factory.newDocumentBuilder(); Reader reader=new StringReader(source); return builder.parse(new InputSource(reader)); }
Example 29
From project dev-examples, under directory /template/src/main/java/org/richfaces/example/.
Source file: XMLBody.java

/** * Load XML document and parse it into DOM. * @param input * @throws ParsingException */ public void loadXML(InputStream input,boolean namespaceAware) throws ParsingException { try { DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance(); docFactory.setIgnoringElementContentWhitespace(true); docFactory.setValidating(false); docFactory.setNamespaceAware(namespaceAware); DocumentBuilder docBuilder=docFactory.newDocumentBuilder(); docBuilder.setEntityResolver(new EntityResolver(){ public InputSource resolveEntity( String publicId, String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); } } ); xmlDocument=docBuilder.parse(input); rootElement=xmlDocument.getDocumentElement(); } catch ( Exception e) { throw new ParsingException("Error load XML ",e); } }
Example 30
private DocumentBuilder newDocumentBuilder(){ try { DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance(); return builderFactory.newDocumentBuilder(); } catch ( ParserConfigurationException e) { throw new RuntimeException(e); } }
Example 31
From project dozer, under directory /core/src/main/java/org/dozer/loader/xml/.
Source file: XMLParserFactory.java

public DocumentBuilder createParser(){ DocumentBuilderFactory factory=createDocumentBuilderFactory(); try { return createDocumentBuilder(factory); } catch ( ParserConfigurationException e) { throw new MappingException("Failed to create XML Parser !",e); } }
Example 32
From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-core-scaffolderproxy/src/main/java/org/easysoa/scaffolding/.
Source file: WodenFormGenerator.java

/** * Return true is the WSDl version is 2.0, false othervise * @param xmlSource The WSDL File to check * @return True if the document version is 2.0, false otherwise * @throws Exception If a problem occurs */ private boolean isWsdl2(String xmlSource) throws Exception { File file=new File(new URI(xmlSource)); DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); Document doc=db.parse(file); doc.getDocumentElement().normalize(); if ("definitions".equalsIgnoreCase(doc.getDocumentElement().getNodeName().substring(doc.getDocumentElement().getNodeName().indexOf(":") + 1))) { return false; } else { return true; } }
Example 33
From project Ebselen, under directory /ebselen-core/src/main/java/com/lazerycode/ebselen/handlers/.
Source file: XMLHandler.java

private void createDocumentAndCollectPrefixes(InputSource documentSource,boolean scanEntireDocument) throws Exception { DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); this.xmlDocument=domFactory.newDocumentBuilder().parse(documentSource); this.namespaceMappings.findNamespaces(this.xmlDocument.getFirstChild(),scanEntireDocument); }
Example 34
From project echo2, under directory /src/exampleapp/chatserver/src/java/echo2example/chatserver/.
Source file: ChatServerServlet.java

/** * Creates the response DOM document, containing a 'chat-server-response' document element. * @return the response document */ private Document createResponseDocument() throws IOException { try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder=factory.newDocumentBuilder(); Document document=builder.newDocument(); document.appendChild(document.createElement("chat-server-response")); return document; } catch ( ParserConfigurationException ex) { throw new IOException("Cannot create document: " + ex); } }
Example 35
From project echo3, under directory /src/server-java/app/nextapp/echo/app/util/.
Source file: DomUtil.java

/** * @see java.lang.ThreadLocal#initialValue() */ protected Object initialValue(){ try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder=factory.newDocumentBuilder(); builder.setEntityResolver(entityResolver); return builder; } catch ( ParserConfigurationException ex) { throw new RuntimeException(ex); } }
Example 36
From project eclipse-integration-cloudfoundry, under directory /org.cloudfoundry.ide.eclipse.server.tests/src/org/cloudfoundry/ide/eclipse/server/tests/sts/util/.
Source file: StsTestUtil.java

public static String canocalizeXml(String originalServerXml) throws Exception { DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=documentBuilderFactory.newDocumentBuilder(); Document document=builder.parse(new InputSource(new StringReader(originalServerXml))); document.normalize(); TransformerFactory factory=TransformerFactory.newInstance(); Transformer transformer=factory.newTransformer(); StringWriter writer=new StringWriter(); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.transform(new DOMSource(document.getDocumentElement()),new StreamResult(writer)); return writer.toString().replace("\\s+\\n","\\n"); }
Example 37
From project eclipse-integration-commons, under directory /org.springsource.ide.eclipse.commons.content.core/src/org/springsource/ide/eclipse/commons/content/core/util/.
Source file: ContentUtil.java

public static DocumentBuilder createDocumentBuilder() throws CoreException { if (SPRING_IDE_AVAILABLE) { return SpringCoreUtils.getDocumentBuilder(); } else { DocumentBuilderFactory xmlFact=DocumentBuilderFactory.newInstance(); try { return xmlFact.newDocumentBuilder(); } catch ( ParserConfigurationException e) { throw new CoreException(null); } } }
Example 38
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 39
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 40
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 41
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 42
From project any23, under directory /core/src/test/java/org/apache/any23/extractor/html/.
Source file: DomUtilsTest.java

@Test public void testSerializeToXML() throws ParserConfigurationException, TransformerException, IOException { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); DOMImplementation impl=builder.getDOMImplementation(); Document doc=impl.createDocument(null,null,null); Node n1=doc.createElement("DIV"); Node n2=doc.createElement("SPAN"); Node n3=doc.createElement("P"); n1.setTextContent("Content 1"); n2.setTextContent("Content 2"); n3.setTextContent("Content 3"); n1.appendChild(n2); n2.appendChild(n3); doc.appendChild(n1); Assert.assertEquals("<DIV>Content 1<SPAN>Content 2<P>Content 3</P></SPAN></DIV>",DomUtils.serializeToXML(doc,false)); }
Example 43
From project aranea, under directory /server/src/main/java/no/dusken/aranea/admin/control/.
Source file: ImportStvMediaController.java

private Document parseXmlFile(File file){ Document dom=null; DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); try { DocumentBuilder db=dbf.newDocumentBuilder(); dom=db.parse(file); } catch ( ParserConfigurationException pce) { pce.printStackTrace(); } catch ( SAXException se) { se.printStackTrace(); } catch ( IOException ioe) { ioe.printStackTrace(); } return dom; }
Example 44
From project arquillian-core, under directory /config/impl-base/src/test/java/org/jboss/arquillian/config/descriptor/impl/.
Source file: ArquillianDescriptorTestCase.java

private void validateXML(String xml) throws Exception { DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); dbf.setValidating(true); dbf.setNamespaceAware(true); dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage","http://www.w3.org/2001/XMLSchema"); DocumentBuilder db=dbf.newDocumentBuilder(); db.setErrorHandler(new ErrorHandler(){ @Override public void warning( SAXParseException exception) throws SAXException { throw exception; } @Override public void fatalError( SAXParseException exception) throws SAXException { throw exception; } @Override public void error( SAXParseException exception) throws SAXException { throw exception; } } ); db.setEntityResolver(new EntityResolver(){ @Override public InputSource resolveEntity( String publicId, String systemId) throws SAXException, IOException { if ("http://jboss.org/schema/arquillian/arquillian_1_0.xsd".equals(systemId)) { return new InputSource(this.getClass().getClassLoader().getResourceAsStream("arquillian_1_0.xsd")); } return null; } } ); db.parse(new ByteArrayInputStream(xml.getBytes())); }
Example 45
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 46
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 47
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 48
From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/org/openscience/cdk/structgen/pubchem/.
Source file: PubchemStructureGenerator.java

private final void initRefreshRequestDocument() throws ParserConfigurationException { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); org.w3c.dom.Document doc=builder.newDocument(); String[] tagNames=new String[]{"PCT-Data_input","PCT-InputData","PCT-InputData_request","PCT-Request"}; doc.appendChild(doc.createElement("PCT-Data")); Element element=doc.getDocumentElement(); for (int i=0; i < tagNames.length; i++) { String tagname=tagNames[i]; Element child=doc.createElement(tagname); element.appendChild(child); element=child; } Element reqid=doc.createElement("PCT-Request_reqid"); reqid.appendChild(doc.createTextNode(this.getRequestID())); Element type=doc.createElement("PCT-Request_type"); type.setAttribute("value","status"); element.appendChild(reqid); element.appendChild(type); this.requestDocument=doc; }
Example 49
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); } }
Example 50
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 51
From project CCR-Validator, under directory /src/main/java/org/openhealthdata/validation/.
Source file: CCRV1SchemaValidator.java

private Document parseFile(File source,boolean validating){ try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setValidating(validating); factory.setNamespaceAware(true); Document doc=factory.newDocumentBuilder().parse(source); return doc; } catch ( SAXException e) { logger.log(Level.SEVERE,"A parsing error occurred; the xml input is not valid",e); e.printStackTrace(); return null; } catch ( ParserConfigurationException e) { logger.log(Level.SEVERE,"A parsing error occurred; the xml input is not valid",e); e.printStackTrace(); return null; } catch ( IOException e) { logger.log(Level.SEVERE,"A parsing error occurred; the xml input is not valid",e); e.printStackTrace(); return null; } }
Example 52
From project CheckIn4Me, under directory /src/com/davidivins/checkin4me/facebook/.
Source file: FacebookService.java

/** * FacebookService * @param resources */ public FacebookService(int service_id,SharedPreferences persistent_storage,Resources resources){ this.service_id=service_id; this.persistent_storage=persistent_storage; config=new Properties(); try { InputStream config_file=resources.openRawResource(GeneratedResources.getRaw("facebook")); config.load(config_file); oauth_connector=new FacebookOAuthConnector(config); api_adapter=new FacebookAPI(config,service_id); } catch ( Exception e) { Log.e(TAG,"Failed to open config file"); } settings=new HashMap<String,ServiceSetting>(); try { InputStream is=resources.openRawResource(GeneratedResources.getRaw("facebook_settings")); DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); Document dom=builder.parse(is); Element root=dom.getDocumentElement(); NodeList settings_nodes=root.getElementsByTagName("setting"); if (settings != null && settings_nodes.getLength() > 0) { for (int i=0; i < settings_nodes.getLength(); i++) { Element setting_xml=(Element)settings_nodes.item(i); ServiceSetting current_setting=new ServiceSetting(setting_xml,persistent_storage); settings.put(current_setting.getPrefName(),current_setting); } } } catch ( Exception e) { Log.e(TAG,"Failed to parse Facebook settings"); } }
Example 53
From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/inputtools/jplugin/.
Source file: ChukwaMetricsList.java

public String toXml() throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder=null; docBuilder=factory.newDocumentBuilder(); Document doc=docBuilder.newDocument(); Element root=doc.createElement(getRecordType()); doc.appendChild(root); root.setAttribute("ts",getTimestamp() + ""); for ( ChukwaMetrics metrics : getMetricsList()) { Element elem=doc.createElement("Metrics"); elem.setAttribute("key",metrics.getKey()); for ( Entry<String,String> attr : metrics.getAttributes().entrySet()) { elem.setAttribute(attr.getKey(),attr.getValue()); } root.appendChild(elem); } Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("indent","yes"); StringWriter sw=new StringWriter(); transformer.transform(new DOMSource(doc),new StreamResult(sw)); return sw.toString(); }
Example 54
From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/framework/data/.
Source file: XmlTools.java

public static Node streamToNode(InputStream is) throws CiliaException { DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder=null; try { builder=domFactory.newDocumentBuilder(); } catch ( ParserConfigurationException e) { e.printStackTrace(); throw new CiliaException("Unable to create DocumentBuilder in XmlTools: " + e.getMessage()); } Document doc=null; try { doc=builder.parse(is); } catch ( SAXException e) { e.printStackTrace(); throw new CiliaException("Unable to create org.w3c.dom.Node from URL in XmlTools: " + e.getMessage()); } catch ( IOException e) { e.printStackTrace(); throw new CiliaException(e.getMessage()); } return doc; }
Example 55
From project cipango, under directory /cipango-console/src/main/java/org/cipango/console/.
Source file: SvgServlet.java

private byte[] doXsl(byte[] source){ try { ByteArrayOutputStream os=new ByteArrayOutputStream(); StreamResult result=new StreamResult(os); TransformerFactory factory=TransformerFactory.newInstance(); DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder(); Node doc=documentBuilder.parse(new ByteArrayInputStream(source)); Transformer transformer=factory.newTransformer(new StreamSource(getClass().getResourceAsStream("dataToSvg.xsl"))); transformer.transform(new DOMSource(doc),result); return os.toByteArray(); } catch ( Throwable e) { _logger.warn("Unable to do XSL transformation",e); return source; } }
Example 56
From project CIShell, under directory /clients/gui/org.cishell.reference.gui.menumanager/src/org/cishell/reference/gui/menumanager/menu/.
Source file: MenuAdapter.java

private void parseXMLFile(String menuFilePath){ DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance(); documentBuilderFactory.setCoalescing(true); try { DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder(); this.documentObjectModel=documentBuilder.parse(menuFilePath); } catch ( ParserConfigurationException parserConfigurationException) { parserConfigurationException.printStackTrace(); } catch ( SAXException saxException) { saxException.printStackTrace(); } catch ( IOException ioException) { ioException.printStackTrace(); } }
Example 57
From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/utils/.
Source file: AppConfigHelper.java

private static Document readXML(InputSource input){ DocumentBuilderFactory dBF=DocumentBuilderFactory.newInstance(); dBF.setIgnoringComments(true); DocumentBuilder builder=null; try { builder=dBF.newDocumentBuilder(); } catch ( ParserConfigurationException e) { e.printStackTrace(); } Document doc=null; try { doc=builder.parse(input); } catch ( SAXException e) { e.printStackTrace(); } catch ( IOException e) { e.printStackTrace(); } return doc; }
Example 58
From project Codeable_Objects, under directory /SoftObjects/src/com/ui/.
Source file: SVGReader.java

public boolean readSVGFile(String path){ polygons.clear(); try { File fXmlFile=new File(ScreenManager.parent.sketchPath + "/" + path); DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance(); dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false); DocumentBuilder dBuilder=dbFactory.newDocumentBuilder(); Document doc=dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); if (doc.getDocumentElement().getNodeName() != "svg") { System.out.println("ERROR: This is not a valid SVG file"); return false; } if (!parseRectangles(doc)) { System.out.println("ERROR: Failed to parse a rect object from the SVG file"); return false; } if (!parsePolygonObjects(doc,"polygon")) { System.out.println("ERROR: Failed to parse a polygon object from the SVG file"); return false; } if (!parsePolygonObjects(doc,"polyline")) { System.out.println("ERROR: Failed to parse a polyline object from the SVG file"); return false; } if (!parseLines(doc)) { System.out.println("ERROR: Failed to parse a line object from the SVG file"); return false; } } catch ( Exception e) { e.printStackTrace(); return false; } return true; }
Example 59
From project com.cedarsoft.serialization, under directory /test-utils/src/main/java/com/cedarsoft/serialization/test/utils/.
Source file: DomTest.java

@Test public void testIt() throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder documentBuilder=factory.newDocumentBuilder(); Document doc=documentBuilder.parse(new ByteArrayInputStream("<a/>".getBytes())); Element element=doc.getDocumentElement(); assertThat(element).isNotNull(); assertThat(element.getTagName()).isEqualTo("a"); assertThat(element.getNamespaceURI()).isEqualTo(null); element.setAttribute("daAttr","daval"); element.appendChild(doc.createElementNS("manuallyChangedChildNS","DaNewChild")); element.appendChild(doc.createElement("child2WithoutNS")); new XmlNamespaceTranslator().addTranslation(null,"MyNS").translateNamespaces(doc,false); StringWriter out=new StringWriter(); XmlCommons.out(doc,out); assertThat(out.toString()).isEqualTo("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<a daAttr=\"daval\" xmlns=\"MyNS\">\n" + " <DaNewChild xmlns=\"manuallyChangedChildNS\"/>\n"+ " <child2WithoutNS/>\n"+ "</a>\n"); }
Example 60
From project Core_2, under directory /parser-xml/src/main/java/org/jboss/forge/parser/xml/.
Source file: XMLParser.java

public static byte[] toXMLByteArray(final Node node){ try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder=factory.newDocumentBuilder(); Document root=builder.newDocument(); writeRecursive(root,node); Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); ByteArrayOutputStream stream=new ByteArrayOutputStream(); StreamResult result=new StreamResult(stream); transformer.transform(new DOMSource(root),result); return stream.toByteArray(); } catch ( Exception e) { throw new XMLParserException("Could not export Node strcuture to XML",e); } }
Example 61
From project Cours-3eme-ann-e, under directory /XML/DOM-examples/DOMExample1/.
Source file: DOMExample1.java

public static void main(String[] args) throws ParserConfigurationException { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setIgnoringElementContentWhitespace(false); factory.setValidating(false); DocumentBuilder parser=factory.newDocumentBuilder(); DOMImplementation domImpl=parser.getDOMImplementation(); String[] features={"Core","XML","HTML","Views","StyleSheets","CSS","CSS2","Events","UIEvents","MouseEvents","MutationEvents","HTMLEvents","Traversal","Range"}; System.out.println("Implementation: " + domImpl.getClass().getName()); for (int i=0; i < features.length; i++) if (domImpl.hasFeature(features[i],"2.0")) System.out.println("Supports " + features[i]); else System.out.println("Does not support " + features[i]); try { System.out.println("Parsing XML document..."); Document doc=parser.parse(args[0]); System.out.println("Displaying XML document..."); System.out.println("<?xml version=\"" + doc.getXmlVersion() + "\" encoding=\""+ doc.getXmlEncoding()+ "\"?>"); displayNode(doc); } catch ( SAXException e) { System.err.println("SAXException"); System.err.println(e.getMessage()); } catch ( IOException e) { System.err.println("IOException"); System.err.println(e.getMessage()); } }
Example 62
From project CraftMania, under directory /CraftMania/src/org/craftmania/blocks/.
Source file: BlockXMLLoader.java

public static void parseXML() throws Exception { File fXmlFile=new File("res/blocks.xml"); DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder=dbFactory.newDocumentBuilder(); Document doc=dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); NodeList blocksList=doc.getElementsByTagName("block"); for (int i=0; i < blocksList.getLength(); ++i) { Node node=blocksList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element=(Element)node; BlockType blockType=parseBlockType(element); BlockManager.getInstance().addBlock(blockType); } } BlockManager.getInstance().load(); }
Example 63
From project cxf-dosgi, under directory /systests/multi_bundle_distro/src/test/java/org/apache/cxf/dosgi/systests/multibundle/.
Source file: MultiBundleDistributionResolver.java

static File[] getDistribution() throws Exception { File distroRoot=new File(System.getProperty("basedir") + "/../../distribution/multi-bundle"); File distroFile=new File(distroRoot,"target/classes/distro_bundles.xml"); DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); Document doc=builder.parse(distroFile); List<File> files=new ArrayList<File>(); NodeList nodes=doc.getDocumentElement().getChildNodes(); for (int i=0; i < nodes.getLength(); i++) { Node n=nodes.item(i); if ("bundle".equals(n.getNodeName())) { String location=n.getTextContent(); File bundleFile=new File(distroRoot,"target/" + location); files.add(bundleFile.getCanonicalFile()); } } return files.toArray(new File[files.size()]); }
Example 64
From project danbooru-gallery-android, under directory /src/tw/idv/palatis/danboorugallery/siteapi/.
Source file: DanbooruStyleAPI.java

@Deprecated protected List<Tag> fetchTagsIndexXML(String url_format,int page,String name,int limit){ TreeSet<Tag> ret=new TreeSet<Tag>(new Tag.CompareById()); String keywords[]=new HashSet<String>(Arrays.asList(name.split("\\+"))).toArray(new String[]{}); for ( String keyword : keywords) { keyword=keyword.trim().replace(' ','_'); try { URL fetchUrl=new URL(String.format(url_format,page,keyword,limit)); D.Log.v("DanbooruStyleAPI::fetchTagsIndexXML(): fetching %s",fetchUrl); DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); Document doc=db.parse(new InputSource(fetchUrl.openStream())); doc.getDocumentElement().normalize(); NodeList nodes=doc.getElementsByTagName("tag"); int length=nodes.getLength(); for (int i=0; i < length; ++i) { ret.add(new Tag((Element)nodes.item(i))); if (isCanceled()) return null; } } catch ( UnsupportedEncodingException e) { D.Log.wtf(e); } catch ( IOException e) { D.Log.wtf(e); } catch ( SAXException e) { D.Log.wtf(e); } catch ( ParserConfigurationException e) { D.Log.wtf(e); } } return Arrays.asList(ret.toArray(new Tag[]{})); }
Example 65
From project data-bus, under directory /databus-core/src/main/java/com/inmobi/databus/.
Source file: DatabusConfigParser.java

private void parseXmlFile(String fileName) throws Exception { DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); Document dom; if (fileName == null) { fileName="databus.xml"; } File file=new File(fileName); if (file.exists()) { dom=db.parse(file); } else { dom=db.parse(ClassLoader.getSystemResourceAsStream(fileName)); } if (dom != null) parseDocument(dom); else throw new Exception("databus.xml file not found"); }
Example 66
From project descriptors, under directory /spi/src/main/java/org/jboss/shrinkwrap/descriptor/spi/node/dom/.
Source file: XmlDomDescriptorExporterImpl.java

/** * {@inheritDoc} * @see org.jboss.shrinkwrap.descriptor.spi.node.NodeDescriptorExporterImpl#to(org.jboss.shrinkwrap.descriptor.spi.node.Node,java.io.OutputStream) */ @Override public void to(final Node node,final OutputStream out) throws DescriptorExportException { try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder=factory.newDocumentBuilder(); Document root=builder.newDocument(); root.setXmlStandalone(true); writeRecursive(root,node); Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.setOutputProperty(OutputKeys.STANDALONE,"yes"); StreamResult result=new StreamResult(out); transformer.transform(new DOMSource(root),result); } catch ( Exception e) { throw new DescriptorExportException("Could not export Node structure to XML",e); } }
Example 67
From project dolphin, under directory /org.adarsh.jutils/src/org/adarsh/jutils/internal/.
Source file: ConfigurationXMLParser.java

/** * Retrieves the content of the child tag if it's found enclosed by the parent tag. * @param parentTag the name of the parent tag. * @param childTag the name of the child tag. * @return a <tt>String</tt> containing the data. */ public static String retrieveTagContents(String parentTag,String childTag){ DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); String contents=""; try { DocumentBuilder docBuilder=factory.newDocumentBuilder(); InputStream input=ConfigurationXMLParser.class.getResourceAsStream(ConfigurationConstants.DEFAULT_CONFIG_FILE); Document document=docBuilder.parse(input); NodeList parentNodeList=document.getElementsByTagName(parentTag); Element parentElement=(Element)parentNodeList.item(0); NodeList childNodeList=parentElement.getElementsByTagName(childTag); Element childElement=(Element)childNodeList.item(0); contents=childElement.getFirstChild().getNodeValue(); input.close(); } catch ( ParserConfigurationException e) { Logger.error("Error parsing configuration XML",e); } catch ( SAXException e) { Logger.error("Error parsing configuration XML",e); } catch ( IOException e) { Logger.error("Error parsing configuration XML",e); } return contents.trim() + "\n"; }
Example 68
From project droidtv, under directory /src/com/chrulri/droidtv/.
Source file: StreamActivity.java

private Document getDomElement(InputStream xmlStream){ Document doc=null; DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); try { DocumentBuilder db=dbf.newDocumentBuilder(); InputSource is=new InputSource(); is.setByteStream(xmlStream); doc=db.parse(is); } catch ( ParserConfigurationException e) { Log.e(TAG,e.getMessage()); return null; } catch ( SAXException e) { Log.e("Error: ",e.getMessage()); return null; } catch ( IOException e) { Log.e("Error: ",e.getMessage()); return null; } return doc; }
Example 69
From project drools-chance, under directory /drools-shapes/drools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/.
Source file: SemanticXSDModelImpl.java

private String compactXML(String source) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException, TransformerException { DocumentBuilderFactory doxFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=doxFactory.newDocumentBuilder(); InputSource is=new InputSource(new StringReader(source)); Document dox=builder.parse(is); dox.normalize(); XPathFactory xpathFactory=XPathFactory.newInstance(); XPathExpression xpathExp=xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']"); NodeList emptyTextNodes=(NodeList)xpathExp.evaluate(dox,XPathConstants.NODESET); for (int i=0; i < emptyTextNodes.getLength(); i++) { Node emptyTextNode=emptyTextNodes.item(i); emptyTextNode.getParentNode().removeChild(emptyTextNode); } TransformerFactory tFactory=TransformerFactory.newInstance(); tFactory.setAttribute("indent-number",new Integer(2)); Transformer transformer=tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); DOMSource domSrc=new DOMSource(dox); ByteArrayOutputStream baos=new ByteArrayOutputStream(); StreamResult result=new StreamResult(baos); transformer.transform(domSrc,result); return new String(baos.toByteArray()); }
Example 70
From project droolsjbpm-integration, under directory /drools-camel/src/test/java/org/drools/camel/component/.
Source file: BatchTest.java

public String prettyPrintXml(String xmlSource){ try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); Document doc=builder.parse(new InputSource(new StringReader(xmlSource))); TransformerFactory tfactory=TransformerFactory.newInstance(); tfactory.setAttribute("indent-number",4); Transformer serializer; ByteArrayOutputStream baos=new ByteArrayOutputStream(); serializer=tfactory.newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); serializer.transform(new DOMSource(doc),new StreamResult(new OutputStreamWriter(baos,"UTF-8"))); return new String(baos.toByteArray()); } catch ( Exception e) { throw new RuntimeException(e); } }
Example 71
From project droolsjbpm-tools, under directory /drools-eclipse/org.guvnor.tools/src/org/guvnor/tools/utils/webdav/.
Source file: StreamProcessingUtils.java

public static Map<String,ResourceProperties> parseListing(String base,InputStream is) throws Exception { Map<String,ResourceProperties> res=new HashMap<String,ResourceProperties>(); DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder parser=factory.newDocumentBuilder(); Document doc=parser.parse(is); NodeList nl=doc.getElementsByTagNameNS(DAV_NS,"response"); for (int i=0; i < nl.getLength(); i++) { Element oneElem=(Element)nl.item(i); NodeList resName=oneElem.getElementsByTagNameNS(DAV_NS,"href"); assert(resName.getLength() == 1); String bareName=extractOverlap(base,URLDecoder.decode(resName.item(0).getTextContent(),"UTF-8")); if (bareName.trim().length() > 0) { ResourceProperties props=new ResourceProperties(); NodeList propList=oneElem.getElementsByTagNameNS(DAV_NS,"resourcetype"); assert(propList.getLength() == 1); NodeList resTypeList=((Element)propList.item(0)).getElementsByTagNameNS(DAV_NS,"collection"); assert(resTypeList.getLength() < 2); if (resTypeList.getLength() == 1) { props.setDirectory(true); } propList=oneElem.getElementsByTagNameNS(DAV_NS,"creationdate"); if (propList.getLength() > 0) { props.setCreationDate(propList.item(0).getTextContent()); } propList=oneElem.getElementsByTagNameNS(DAV_NS,"getlastmodified"); if (propList.getLength() > 0) { props.setLastModifiedDate(propList.item(0).getTextContent()); } String normBase=base.trim().endsWith("/") ? base.trim() : base.trim() + "/"; props.setBase(normBase); res.put(bareName,props); } } return res; }
Example 72
From project DTE, under directory /src/cl/nic/dte/extension/.
Source file: BOLETADefTypeExtensionHandler.java

public static VerifyResult verifySignature(BOLETADefType dte){ cl.sii.siiDte.dsig.SignatureType sign=dte.getSignature(); if (sign == null || sign.isNil()) { return new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG,false,Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NOTFOUND")); } Date date=dte.getDocumento().getTmstFirma().getTime(); HashMap<String,String> namespaces=new HashMap<String,String>(); namespaces.put("","http://www.sii.cl/SiiDte"); namespaces.put("xsi","http://www.w3.org/2001/XMLSchema-instance"); XmlOptions opts=new XmlOptions(); opts.setSaveOuter(); opts.setSaveImplicitNamespaces(namespaces); try { DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document dte2=dbf.newDocumentBuilder().parse(dte.newInputStream(opts)); NodeList nl=dte2.getElementsByTagNameNS(XMLSignature.XMLNS,"Signature"); if (nl.getLength() == 0) { return new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG,false,Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NOTFOUND")); } return (XMLUtil.verifySignature(nl.item(0),date)); } catch ( SAXException e) { return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG,false,Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNKNOWN") + ": " + e.getMessage())); } catch ( IOException e) { return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG,false,Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNKNOWN") + ": " + e.getMessage())); } catch ( ParserConfigurationException e) { return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG,false,Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNKNOWN") + ": " + e.getMessage())); } }
Example 73
From project Absolute-Android-RSS, under directory /src/com/AA/Other/.
Source file: RSSParse.java

/** * Get the XML document for the RSS feed * @return the XML Document for the feed on success, on error returns null */ private static Document getDocument(){ Document doc=null; try { DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); DefaultHttpClient client=new DefaultHttpClient(); HttpGet request=new HttpGet(URI); HttpResponse response=client.execute(request); doc=builder.parse(response.getEntity().getContent()); } catch ( java.io.IOException e) { return null; } catch ( SAXException e) { Log.e("AARSS","Parse Exception in RSS feed",e); return null; } catch ( Exception e) { return null; } return doc; }
Example 74
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 75
private Document readIdeaFile(@NotNull File ideaFile,final String defaultTemplate){ Document result=null; try { DocumentBuilder reader=DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputStream is; if (!env.forceBuild() && ideaFile.exists()) { is=new FileInputStream(ideaFile); } else if (template != null && template.exists()) { is=new FileInputStream(template); } else { is=getClass().getResourceAsStream(defaultTemplate); } result=reader.parse(is); } catch ( ParserConfigurationException e) { env.handle(e); } catch ( IOException e) { env.handle(e); } catch ( SAXException e) { env.handle(e); } return result; }
Example 76
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 77
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 78
From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/dbunit/dataset/xml/.
Source file: DtdResolver.java

/** * @param xmlFile * @return name of DTD file specified in the !DOCTYPE or null if not specified. */ public String resolveDtdLocation(final String xmlFile){ final InputStream xmlStream=Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFile); try { final DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); builder.setEntityResolver(new EntityResolver(){ @Override public InputSource resolveEntity( String publicId, String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); } } ); final Document document=builder.parse(xmlStream); if (document.getDoctype() == null) { return null; } return document.getDoctype().getSystemId(); } catch ( Exception e) { throw new RuntimeException("Unable to resolve dtd for " + xmlFile,e); } }
Example 79
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 80
From project bam, under directory /modules/activity-analysis/service-dependency-svg/src/main/java/org/overlord/bam/service/dependency/svg/.
Source file: SVGServiceGraphGenerator.java

/** * This method returns the named template file. * @param name The svg template name * @return The template, or null if failed to load */ protected org.w3c.dom.Document loadTemplate(String name){ org.w3c.dom.Document ret=null; try { String template="templates" + java.io.File.separator + name+ ".svg"; java.io.InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream("/" + template); if (is == null) { is=Thread.currentThread().getContextClassLoader().getResourceAsStream(template); } DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); ret=builder.parse(is); is.close(); } catch ( Exception e) { LOG.log(Level.SEVERE,MessageFormat.format(java.util.PropertyResourceBundle.getBundle("service-dependency-svg.Messages").getString("SERVICE-DEPENDENCY-SVG-1"),name),e); } return (ret); }
Example 81
From project big-data-plugin, under directory /src/org/pentaho/di/job/.
Source file: JobEntrySerializationHelper.java

/** * Handle reading of the input (object) from the kettle repository by getting the xml from the repository attribute string and then re-hydrate the object with our already existing read method. * @param object * @param rep * @param id_job * @param databases * @param slaveServers * @throws KettleException */ public static void loadRep(Object object,Repository rep,ObjectId id_job,List<DatabaseMeta> databases,List<SlaveServer> slaveServers) throws KettleException { try { String xml=rep.getJobEntryAttributeString(id_job,"job-xml"); ByteArrayInputStream bais=new ByteArrayInputStream(xml.getBytes()); Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(bais); read(object,doc.getDocumentElement()); } catch ( ParserConfigurationException ex) { throw new KettleException(ex.getMessage(),ex); } catch ( SAXException ex) { throw new KettleException(ex.getMessage(),ex); } catch ( IOException ex) { throw new KettleException(ex.getMessage(),ex); } }
Example 82
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 83
From project BMach, under directory /src/jsyntaxpane/actions/.
Source file: XmlPrettifyAction.java

public static DocumentBuilderFactory getDocBuilderFactory(){ if (docBuilderFactory == null) { docBuilderFactory=DocumentBuilderFactory.newInstance(); } return docBuilderFactory; }
Example 84
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 85
From project caseconductor-platform, under directory /utest-portal-webapp/src/main/java/com/utest/portal/log/.
Source file: RepositorySelector.java

private static void loadLog4JConfig(final ServletContext servletContext,final Hierarchy hierarchy) throws ServletException { try { final String log4jFile="/WEB-INF/config/log4j.xml"; final InputStream log4JConfig=servletContext.getResourceAsStream(log4jFile); final Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(log4JConfig); final DOMConfigurator conf=new DOMConfigurator(); conf.doConfigure(doc.getDocumentElement(),hierarchy); } catch ( final Exception e) { throw new ServletException(e); } }
Example 86
From project ceres, under directory /ceres-site/src/main/java/com/bc/ceres/site/util/.
Source file: ExclusionListBuilder.java

static void addPomToExclusionList(File exclusionList,URL pom) throws ParserConfigurationException, IOException, SAXException { BufferedWriter writer=new BufferedWriter(new FileWriter(exclusionList,true)); try { final DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); final Document w3cDoc=builder.parse(pom.openStream()); final DOMBuilder domBuilder=new DOMBuilder(); final org.jdom.Document doc=domBuilder.build(w3cDoc); final Element root=doc.getRootElement(); final Namespace namespace=root.getNamespace(); final List<Element> modules=root.getChildren(MODULES_NODE,namespace); if (modules != null) { final Element modulesNode=modules.get(0); final List<Element> modulesList=(List<Element>)modulesNode.getChildren(MODULE_NAME,namespace); for ( Element module : modulesList) { addModuleToExclusionList(exclusionList,writer,module.getText()); } } } catch ( Exception e) { e.printStackTrace(); } finally { writer.close(); } }
Example 87
From project CloudReports, under directory /src/main/java/cloudreports/extensions/.
Source file: ExtensionsLoader.java

/** * Loads an instance of <code>Document</code> that contains the classnames.xml file. * @return a <code>Document</code> object containing the classnames.xml file. * @since 1.0 */ private static Document getClassnamesXml(){ File classnamesXmlFile=new File(classnamesXmlPath); if (!classnamesXmlFile.exists() || !classnamesXmlFile.isFile()) { return null; } DocumentBuilder db; try { db=DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is=new InputSource(classnamesXmlFile.toURI().toURL().openStream()); Document classnamesXmlDocument=db.parse(is); return classnamesXmlDocument; } catch ( Exception ex) { Logger.getLogger(ExtensionsLoader.class.getName()).log(Level.INFO,null,ex); return null; } }
Example 88
public String authenticate(){ InputStream res=get(String.format(LOGIN_URI,_prefs.getUsername(),_prefs.getPassword())); if (res != null) { DocumentBuilder docBuilder=null; try { docBuilder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc=docBuilder.parse(res); _ticket=doc.getDocumentElement().getFirstChild().getNodeValue(); } catch ( Exception e) { Log.e(CMIS.class.getSimpleName(),"Error getting Alfresco ticket",e); } } return _ticket; }
Example 89
From project code_swarm, under directory /src/org/codeswarm/repositoryevents/.
Source file: CodeSwarmEventsSerializer.java

/** * actually serializes the list to the file denoted by pathToFile * @param pathToFile the path to the xml file to serialize to.It gets created if it doesn't exist. * @throws javax.xml.parsers.ParserConfigurationException When the serialization failed * @throws javax.xml.transform.TransformerConfigurationException When the serialization failed * @throws java.io.IOException When the serialization failed * @throws javax.xml.transform.TransformerException When the serialization failed */ public void serialize(String pathToFile) throws ParserConfigurationException, TransformerConfigurationException, IOException, TransformerException { Document d=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element events=d.createElement("file_events"); for ( Event e : list.getEvents()) { Element event=d.createElement("event"); event.setAttribute("filename",e.getFilename()); event.setAttribute("date",String.valueOf(e.getDate())); event.setAttribute("author",e.getAuthor()); events.appendChild(event); } d.appendChild(events); Transformer t=TransformerFactory.newInstance().newTransformer(); File f=new File(pathToFile); if (!f.exists()) { f.createNewFile(); } FileOutputStream out=new FileOutputStream(f); StreamResult result=new StreamResult(out); t.transform(new DOMSource(d),result); out.close(); }
Example 90
From project code_swarm-gource-my-conf, under directory /src/org/codeswarm/repositoryevents/.
Source file: CodeSwarmEventsSerializer.java

/** * actually serializes the list to the file denoted by pathToFile * @param pathToFile the path to the xml file to serialize to. It gets created if it doesn't exist. * @throws javax.xml.parsers.ParserConfigurationException When the serialization failed * @throws javax.xml.transform.TransformerConfigurationException When the serialization failed * @throws java.io.IOException When the serialization failed * @throws javax.xml.transform.TransformerException When the serialization failed */ public void serialize(String pathToFile) throws ParserConfigurationException, TransformerConfigurationException, IOException, TransformerException { Document d=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element events=d.createElement("file_events"); for ( Event e : list.getEvents()) { Element event=d.createElement("event"); event.setAttribute("filename",e.getFilename()); event.setAttribute("date",String.valueOf(e.getDate())); event.setAttribute("author",e.getAuthor()); events.appendChild(event); } d.appendChild(events); Transformer t=TransformerFactory.newInstance().newTransformer(); File f=new File(pathToFile); if (!f.exists()) { f.createNewFile(); } FileOutputStream out=new FileOutputStream(f); StreamResult result=new StreamResult(out); t.transform(new DOMSource(d),result); out.close(); }
Example 91
From project comm, under directory /src/main/java/io/s4/comm/util/.
Source file: ConfigParser.java

private static Document createDocument(String configFilename){ try { Document document; javax.xml.parsers.DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setIgnoringComments(true); dbf.setIgnoringElementContentWhitespace(true); javax.xml.parsers.DocumentBuilder parser=dbf.newDocumentBuilder(); parser.setErrorHandler(new org.xml.sax.ErrorHandler(){ public void warning( SAXParseException e){ logger.warn("WARNING: " + e.getMessage(),e); } public void error( SAXParseException e){ logger.error("ERROR: " + e.getMessage(),e); } public void fatalError( SAXParseException e) throws SAXException { logger.error("FATAL ERROR: " + e.getMessage(),e); throw e; } } ); InputStream is=getResourceStream(configFilename); if (is == null) { throw new RuntimeException("Unable to find config file:" + configFilename); } document=parser.parse(is); return document; } catch ( Exception e) { throw new RuntimeException(e); } }
Example 92
From project cw-advandroid, under directory /Honeycomb/WeatherFragment/src/com/commonsware/android/weather/.
Source file: WeatherBinder.java

private ArrayList<Forecast> buildForecasts(String raw) throws Exception { ArrayList<Forecast> forecasts=new ArrayList<Forecast>(); DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc=builder.parse(new InputSource(new StringReader(raw))); NodeList times=doc.getElementsByTagName("start-valid-time"); for (int i=0; i < times.getLength(); i++) { Element time=(Element)times.item(i); Forecast forecast=new Forecast(); forecasts.add(forecast); forecast.setTime(time.getFirstChild().getNodeValue()); } NodeList temps=doc.getElementsByTagName("value"); for (int i=0; i < temps.getLength(); i++) { Element temp=(Element)temps.item(i); Forecast forecast=forecasts.get(i); forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue())); } NodeList icons=doc.getElementsByTagName("icon-link"); for (int i=0; i < icons.getLength(); i++) { Element icon=(Element)icons.item(i); Forecast forecast=forecasts.get(i); forecast.setIcon(icon.getFirstChild().getNodeValue()); } return (forecasts); }
Example 93
From project cw-android, under directory /Files/Static/src/com/commonsware/android/files/.
Source file: StaticFileDemo.java

@Override public void onCreate(Bundle icicle){ super.onCreate(icicle); setContentView(R.layout.main); selection=(TextView)findViewById(R.id.selection); try { InputStream in=getResources().openRawResource(R.raw.words); DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc=builder.parse(in,null); NodeList words=doc.getElementsByTagName("word"); for (int i=0; i < words.getLength(); i++) { items.add(((Element)words.item(i)).getAttribute("value")); } in.close(); } catch ( Throwable t) { Toast.makeText(this,"Exception: " + t.toString(),Toast.LENGTH_LONG).show(); } setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items)); }
Example 94
From project cw-omnibus, under directory /Internet/Weather/src/com/commonsware/android/weather/.
Source file: WeatherFragment.java

private ArrayList<Forecast> buildForecasts(String raw) throws Exception { ArrayList<Forecast> forecasts=new ArrayList<Forecast>(); DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc=builder.parse(new InputSource(new StringReader(raw))); NodeList times=doc.getElementsByTagName("start-valid-time"); for (int i=0; i < times.getLength(); i++) { Element time=(Element)times.item(i); Forecast forecast=new Forecast(); forecasts.add(forecast); forecast.setTime(time.getFirstChild().getNodeValue()); } NodeList temps=doc.getElementsByTagName("value"); for (int i=0; i < temps.getLength(); i++) { Element temp=(Element)temps.item(i); Forecast forecast=forecasts.get(i); forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue())); } NodeList icons=doc.getElementsByTagName("icon-link"); for (int i=0; i < icons.getLength(); i++) { Element icon=(Element)icons.item(i); Forecast forecast=forecasts.get(i); forecast.setIcon(icon.getFirstChild().getNodeValue()); } return (forecasts); }
Example 95
From project drools-mas, under directory /drools-mas-util/src/main/java/org/drools/mas/util/.
Source file: InspectMessageHelper.java

public static String inspect(ACLMessage message,String path) throws ParseException, XPathExpressionException, ParserConfigurationException, IOException, SAXException { AbstractMessageContent content=inspectContent(message); if (content.getEncodedContent() != null || !content.getEncodedContent().equals("")) { switch (message.getEncoding()) { case JSON: Object res=JsonPath.read(content.getEncodedContent(),path); return (res != null) ? res.toString() : null; case XML: XPath accessor=XPathFactory.newInstance().newXPath(); InputStream inStream=new ByteArrayInputStream(content.getEncodedContent().getBytes()); Document dox=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inStream); return (String)accessor.evaluate(path,dox,XPathConstants.STRING); default : throw new ParseException("Unable to access byte-encoded message body",0); } } return null; }
Example 96
From project eclim, under directory /org.eclim.core/java/org/eclim/plugin/core/project/.
Source file: ProjectManagement.java

/** * Handle deleting the stale project if it exists. * @param name The project name. * @param folder The project folder. */ protected static void deleteStaleProject(String name,String folder) throws Exception { File projectFile=new File(folder + File.separator + ".project"); if (projectFile.exists()) { if (xpath == null) { xpath=XmlUtils.createXPathExpression("/projectDescription/name/text()"); factory=DocumentBuilderFactory.newInstance(); } Document document=factory.newDocumentBuilder().parse(projectFile); String projectName=(String)xpath.evaluate(document); if (!projectName.equals(name)) { IProject project=ProjectUtils.getProject(projectName); if (project.exists()) { project.delete(false,true,null); } else { projectFile.delete(); } } } }
Example 97
From project Eclipse, under directory /com.mobilesorcery.sdk.core/src/com/mobilesorcery/sdk/core/.
Source file: MoSyncTool.java

private Document getPropertiesXMLDoc() throws ParserConfigurationException, IOException { File propertiesFile=getPropertiesFile().toFile(); if (!propertiesFile.getParentFile().exists()) { propertiesFile.getParentFile().mkdirs(); } if (propertiesFile.exists()) { try { return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(propertiesFile); } catch ( SAXException e) { } } Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root=doc.createElement("Config"); doc.appendChild(root); return doc; }