/** Create DOM builder using JAXP libraries. */ static DocumentBuilder makeBuilder(boolean validate) throws IOException, SAXException { DocumentBuilder builder; DocumentBuilderFactory factory; // create factory according to javax.xml.parsers.SAXParserFactory property // or platform default (i.e. com.sun...) try { factory = DocumentBuilderFactory.newInstance(); factory.setValidating(validate); factory.setNamespaceAware(false); } catch (FactoryConfigurationError err) { notifyFactoryErr(err, "javax.xml.parsers.DocumentBuilderFactory"); // NOI18N throw err; } try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { SAXException sex = new SAXException("Configuration exception."); // NOI18N ErrorManager emgr = ErrorManager.getDefault(); emgr.annotate(sex, ex); emgr.annotate( sex, "Can not create a DOM builder!\nCheck javax.xml.parsers.DocumentBuilderFactory property and the builder library presence on classpath."); // NOI18N throw sex; } return builder; }
/** Возвращает объект Document, который является объектным представлением XML документа. */ private static Document getDocument() throws Exception { try { DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); f.setValidating(false); DocumentBuilder builder = f.newDocumentBuilder(); return builder.parse(new File("app.xml")); } catch (Exception exception) { String message = "XML parsing error!"; throw new Exception(message); } }
public static final Skeleton loadSkeleton(File file) { try { FileInputStream input_stream = new FileInputStream(file); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new GeometryErrorHandler()); Document document = builder.parse(input_stream); Element root = document.getDocumentElement(); return parseSkeleton(root); } catch (Exception e) { throw new RuntimeException(e); } }
static { try { URL url = SpellCheckActivator.bundleContext.getBundle().getResource(RESOURCE_LOC); InputStream stream = url.openStream(); if (stream == null) throw new IOException(); // strict parsing options DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); // parses configuration xml /*- * Warning: Felix is unable to import the com.sun.rowset.internal * package, meaning this can't use the XmlErrorHandler. This causes * a warning and a default handler to be attached. Otherwise this * should have: builder.setErrorHandler(new XmlErrorHandler()); */ DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(stream); // iterates over nodes, parsing contents Node root = doc.getChildNodes().item(1); NodeList categories = root.getChildNodes(); for (int i = 0; i < categories.getLength(); ++i) { Node node = categories.item(i); if (node.getNodeName().equals(NODE_DEFAULTS)) { parseDefaults(node.getChildNodes()); } else if (node.getNodeName().equals(NODE_LOCALES)) { parseLocales(node.getChildNodes()); } else { logger.warn("Unrecognized category: " + node.getNodeName()); } } } catch (IOException exc) { logger.error("Unable to load spell checker parameters", exc); } catch (SAXException exc) { logger.error("Unable to parse spell checker parameters", exc); } catch (ParserConfigurationException exc) { logger.error("Unable to parse spell checker parameters", exc); } }
public void setValidating(boolean validating) { fact.setValidating(validating); }
// ## operation readReactorOutputFile(ReactionModel) public SystemSnapshot readReactorOutputFile(ReactionModel p_reactionModel) { // #[ operation readReactorOutputFile(ReactionModel) try { // open output file and build the DOM tree String dir = System.getProperty("RMG.workingDirectory"); String filename = "chemkin/reactorOutput.xml"; File inputFile = new File(filename); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); // validate the document with the DTD factory.setIgnoringElementContentWhitespace(true); // ignore whitespace DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(inputFile); // get root element and its children Element root = doc.getDocumentElement(); NodeList rootchildren = root.getChildNodes(); // header is rootchildren.item(0) // get return message and check for successful run Element returnmessageElement = (Element) rootchildren.item(1); Text returnmessageText = (Text) returnmessageElement.getFirstChild(); String returnmessage = returnmessageText.toString(); returnmessage = returnmessage.trim(); if (!returnmessage.contains("SUCCESSFULLY COMPLETED RUN.")) { System.out.println("External reactor model failed!"); System.out.println("Reactor model error message: " + returnmessage); System.exit(0); } // get outputvalues element and its children Element outputvaluesElement = (Element) rootchildren.item(2); NodeList children = outputvaluesElement.getChildNodes(); // get time Element timeElement = (Element) children.item(0); Text timeText = (Text) timeElement.getFirstChild(); double time = Double.parseDouble(timeText.getData()); String timeUnits = timeElement.getAttribute("units"); // get systemstate element and its children Element systemstateElement = (Element) children.item(1); NodeList states = systemstateElement.getChildNodes(); // get temperature and its units Element temperatureElement = (Element) states.item(0); String tempUnits = temperatureElement.getAttribute("units"); Text temperatureText = (Text) temperatureElement.getFirstChild(); double temp = Double.parseDouble(temperatureText.getData()); Temperature T = new Temperature(temp, tempUnits); // get pressure and its units Element pressureElement = (Element) states.item(1); String presUnits = pressureElement.getAttribute("units"); Text pressureText = (Text) pressureElement.getFirstChild(); double pres = Double.parseDouble(pressureText.getData()); Pressure P = new Pressure(pres, presUnits); // get species amounts (e.g. concentrations) ArrayList speciesIDs = new ArrayList(); ArrayList amounts = new ArrayList(); ArrayList fluxes = new ArrayList(); String amountUnits = null; String fluxUnits = null; // loop thru all the species // begin at i=2, since T and P take already the first two position of states int nSpe = (states.getLength() - 2) / 2; int index = 0; LinkedHashMap inertGas = new LinkedHashMap(); for (int i = 2; i < nSpe + 2; i++) { // get amount element and the units Element amountElement = (Element) states.item(i); amountUnits = amountElement.getAttribute("units"); Element fluxElement = (Element) states.item(i + nSpe); fluxUnits = fluxElement.getAttribute("units"); // get speciesid and store in an array list String thisSpeciesID = amountElement.getAttribute("speciesid"); // get amount (e.g. concentraion) and store in an array list Text amountText = (Text) amountElement.getFirstChild(); double thisAmount = Double.parseDouble(amountText.getData()); if (thisAmount < 0) { double aTol = ReactionModelGenerator.getAtol(); // if (Math.abs(thisAmount) < aTol) thisAmount = 0; // else throw new NegativeConcentrationException("Negative concentration in // reactorOutput.xml: " + thisSpeciesID); if (thisAmount < -100.0 * aTol) throw new NegativeConcentrationException( "Species " + thisSpeciesID + " has negative concentration: " + String.valueOf(thisAmount)); } // get amount (e.g. concentraion) and store in an array list Text fluxText = (Text) fluxElement.getFirstChild(); double thisFlux = Double.parseDouble(fluxText.getData()); if (thisSpeciesID.compareToIgnoreCase("N2") == 0 || thisSpeciesID.compareToIgnoreCase("Ne") == 0 || thisSpeciesID.compareToIgnoreCase("Ar") == 0) { inertGas.put(thisSpeciesID, new Double(thisAmount)); } else { speciesIDs.add(index, thisSpeciesID); amounts.add(index, new Double(thisAmount)); fluxes.add(index, new Double(thisFlux)); index++; } } // print results for debugging purposes /** * System.out.println(returnmessage); System.out.println("Temp = " + temp + " " + tempUnits); * System.out.println("Pres = " + pres + " " + presUnits); for (int i = 0; i < amounts.size(); * i++) { System.out.println(speciesIDs.get(i) + " " + amounts.get(i) + " " + amountUnits); } */ ReactionTime rt = new ReactionTime(time, timeUnits); LinkedHashMap speStatus = generateSpeciesStatus(p_reactionModel, speciesIDs, amounts, fluxes); SystemSnapshot ss = new SystemSnapshot(rt, speStatus, T, P); ss.inertGas = inertGas; return ss; } catch (Exception e) { System.out.println("Error reading reactor model output: " + e.getMessage()); System.exit(0); return null; } // #] }
public static MiningResult importFile(InputStream input) throws IOException { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document doc; // NodeList netNodes; dbf.setValidating(false); dbf.setIgnoringComments(true); dbf.setIgnoringElementContentWhitespace(true); // dbf.setExpandEntityReferences(false); // dbf.setNamespaceAware(false); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver( new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) { if (systemId.indexOf("ARIS-Export") != -1) { return new InputSource("file:" + About.EXTLIBLOCATION() + "ARIS-Export101.dtd"); } else { return null; } } }); InputSource inpStream = new InputSource(input); inpStream.setSystemId("file:" + System.getProperty("user.dir", "")); doc = db.parse(inpStream); // check if root element is a aml tag Message.add("parsing done" + doc, Message.DEBUG); if (!(doc.getDocumentElement().getNodeName().equals("AML"))) { Message.add("aml tag not found", Message.ERROR); throw new Exception("aml tag not found"); } else { Message.add("aml root element found"); } EPCResult result = new EPCResult(null, (EPC) null); HashMap ObjDef_LinkId = new HashMap(); HashMap modelid_net = new HashMap(); HashMap ObjDef_Name = new HashMap(); HashMap function_LinkId = new HashMap(); HashMap ModelId_ModelType = new HashMap(); traverseAMLforObjectNames( ObjDef_Name, doc.getDocumentElement(), ObjDef_LinkId, ModelId_ModelType); Iterator findLinkToEpc = ObjDef_LinkId.keySet().iterator(); while (findLinkToEpc.hasNext()) { String currentObjDef = (String) findLinkToEpc.next(); String Links = (String) ObjDef_LinkId.get(currentObjDef); StringTokenizer linkSet = new StringTokenizer(Links); String realEpcLink = ""; while (linkSet.hasMoreTokens()) { String currentLink = linkSet.nextToken(); if (ModelId_ModelType.get(currentLink).equals("MT_EEPC")) { realEpcLink = currentLink; break; } } if (realEpcLink.equals(" ")) { ObjDef_LinkId.remove(currentObjDef); } else { ObjDef_LinkId.put(currentObjDef, realEpcLink); } } result = traverseAML( result, doc.getDocumentElement(), null, ObjDef_Name, ObjDef_LinkId, modelid_net, function_LinkId); Iterator hierarchicalFunctions = function_LinkId.keySet().iterator(); while (hierarchicalFunctions.hasNext()) { EPCSubstFunction f = (EPCSubstFunction) hierarchicalFunctions.next(); f.setSubstitutedEPC((EPC) modelid_net.get(function_LinkId.get(f))); // Message.add(f.getSubstitutedEPC().getName()); } return result; } catch (Throwable x) { Message.add(x.toString()); throw new IOException(x.getMessage()); } }
protected Document parse(InputStream inputStream) throws LibraryException { Map<Integer, SongBean> songMap = new HashMap<Integer, SongBean>(); Map<Integer, AlbumBean> albumMap = new HashMap<Integer, AlbumBean>(); Map<Integer, AlbumBean> secondaryAlbumMap = new HashMap<Integer, AlbumBean>(); warningList.clear(); try { // Create a builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setNamespaceAware(true); factory.setIgnoringElementContentWhitespace(true); factory.setIgnoringComments(true); // Create the builder and parse the file DocumentBuilder builder = factory.newDocumentBuilder(); // Set an error listener and parse the document builder.setErrorHandler(new iTradeTunesLibraryErrorHandler()); builder.setEntityResolver(new iTradeTunesLibraryResolver()); Document document = builder.parse(inputStream); synchronized (libraryList) { // Query the library document and build the library list XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression xPathExpression = xPath.compile(XPATH_LIBRARY_LIST); NodeList nodelist = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET); // Process the elements in the nodelist SongBean song = null; for (int i = 0; i < nodelist.getLength(); i++) { boolean isTrackID = false; // Get element and child nodes Element elem = (Element) nodelist.item(i); NodeList list = elem.getChildNodes(); // Get node value Node childKey = list.item(0); String key = childKey.getNodeValue(); // Check if we have to create a new bean if (SongBean.NAME_TRACK_ID.equals(key)) { isTrackID = true; SongBean previousSong = song; song = new SongBean(); if (previousSong != null && !("AAC audio file".equals(previousSong.getKind()) || "MPEG audio file".equals(previousSong.getKind()))) { songMap.remove(previousSong.getTrack_ID()); } else { // Add an album bean addOrUpdateAlbum(albumMap, previousSong, false); } } // The first parameter is the key String prop = childKey.getNodeValue().replace(' ', '_'); // The second parameter is the value i++; // Get element and child nodes elem = (Element) nodelist.item(i); // Check for boolean properties Object value = null; // Get node value list = elem.getChildNodes(); childKey = list.item(0); value = (childKey == null) ? elem.getNodeName() : childKey.getNodeValue(); if (isTrackID) { isTrackID = false; } // Set the property of the song bean Statement stmt = new Statement(song, "set" + prop, new Object[] {value}); try { stmt.execute(); } catch (Exception e) { // Ignore that field, we do not have it in our bean } // If the property is the track ID, add the song to the hash // map if (SongBean.NAME_TRACK_ID.equals(key)) { int trackID = Integer.valueOf((String) value); songMap.put(trackID, song); } } // Update album for last song addOrUpdateAlbum(albumMap, song, false); // Check the album map for inconsistencies Iterator<AlbumBean> albums = albumMap.values().iterator(); while (albums.hasNext()) { AlbumBean album = albums.next(); if (album.checkConsistency()) { libraryList.add(album); album.setHashCode(); } else { // Add an inconsistent album only using the album title SongBean[] songs = album.getSongs(); for (int i = 0; i < songs.length; i++) { addOrUpdateAlbum(secondaryAlbumMap, songs[i], true); } } } // Check secondary album map for consistency albums = secondaryAlbumMap.values().iterator(); while (albums.hasNext()) { AlbumBean album = albums.next(); if (album.checkConsistency()) { libraryList.add(album); album.setHashCode(); } else { // This album cannot be matched // TODO: Add to warning message } } setChanged(); } return document; } catch (IOException ioe) { // Log an expected connect exception throw new LibraryException(ioe); } catch (SAXException se) { // Catch all other exceptions throw new LibraryException(se); } catch (ParserConfigurationException pce) { // Catch all other exceptions Utils.logSevere(pce); throw new LibraryException(pce); } catch (XPathExpressionException xpe) { // Catch all other exceptions Utils.logSevere(xpe); throw new LibraryException(xpe); } catch (NumberFormatException nfe) { // Catch all other exceptions throw new LibraryException(nfe); } }
@Override protected DocumentBuilderFactory getDocBuilderFactory() { DocumentBuilderFactory factory = super.getDocBuilderFactory(); factory.setValidating(true); return factory; }