// ## operation writeChemkinInputFile(ReactionModel,SystemSnapshot) public static void writeChemkinInputFile( final ReactionModel p_reactionModel, SystemSnapshot p_beginStatus) { // #[ operation writeChemkinInputFile(ReactionModel,SystemSnapshot) StringBuilder result = new StringBuilder(); result.append(writeChemkinHeader()); result.append(writeChemkinElement()); double start = System.currentTimeMillis(); result.append(writeChemkinSpecies(p_reactionModel, p_beginStatus)); result.append(writeChemkinThermo(p_reactionModel)); Global.chemkinThermo = Global.chemkinThermo + (System.currentTimeMillis() - start) / 1000 / 60; start = System.currentTimeMillis(); result.append( writeChemkinPdepReactions( p_reactionModel, p_beginStatus)); // 10/26/07 gmagoon: changed to pass p_beginStatus // result.append(writeChemkinPdepReactions(p_reactionModel)); Global.chemkinReaction = Global.chemkinReaction + (System.currentTimeMillis() - start) / 1000 / 60; String dir = System.getProperty("RMG.workingDirectory"); if (!dir.endsWith("/")) dir += "/"; dir += "software/reactorModel/"; String file = "chemkin/chem.inp"; try { FileWriter fw = new FileWriter(file); fw.write(result.toString()); fw.close(); } catch (Exception e) { System.out.println("Error in writing chemkin input file chem.inp!"); System.out.println(e.getMessage()); System.exit(0); } if (PDepRateConstant.getMode() == Mode.CHEBYSHEV || PDepRateConstant.getMode() == Mode.PDEPARRHENIUS || PDepRateConstant.getMode() == Mode.RATE) { StringBuilder gridOfRateCoeffs = new StringBuilder(); gridOfRateCoeffs.append(writeGridOfRateCoeffs(p_reactionModel)); String newFile = "chemkin/tableOfRateCoeffs.txt"; try { FileWriter fw = new FileWriter(newFile); fw.write(gridOfRateCoeffs.toString()); fw.close(); } catch (Exception e) { System.out.println("Error in writing tableOfRateCoeffs.txt"); System.out.println(e.getMessage()); System.exit(0); } } // #] }
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws ParserException { Caller targeting = (Caller) targetMap.get(qName); if (null == targeting) throw new ParserException("No target found for tag: " + qName + "!"); targeting = (Caller) targeting.duplicate(); XMLOp actor = (XMLOp) actionMap.get(qName); if (null == actor) throw new ParserException("No action found for tag: " + qName + "!"); if (null == targeting.getTargetObject() && 0 < stack.size()) { Caller parent = null; try { parent = (Caller) stack.peek(); } catch (Exception e) { throw new ParserException( "Typecast exception, unknown object placed in stack! " + e.getMessage()); } Object targetObject = parent.parameter(0); int idx = stack.indexOf(parent); // climb stack for next available parent (stack may have no-ops in it. while (null == targetObject && 0 < idx) { { } // System.out.println("Climbing stack for next available parent.."); try { parent = (Caller) stack.get(--idx); } catch (Exception e) { throw new ParserException( "Typecast exception, unknown object placed in stack! " + e.getMessage()); } targetObject = parent.parameter(0); } targeting.setTargetObject(targetObject); } Object o; try { actor.initialize(attributeMap(qName, atts)); o = actor.process(); } catch (Exception e) { try { actor.initialize(attributeMap(qName, atts)); o = actor.process(); } catch (Exception r) { throw new ParserException( "Could not execute action for tag: " + qName + "! " + e.getMessage()); } } targeting.resetParameters(new Object[] {o}); stack.push(targeting); }
// ## operation checkChemkinMessage() public void checkChemkinMessage() { // #[ operation checkChemkinMessage() try { String dir = System.getProperty("RMG.workingDirectory"); String filename = "chemkin/chem.message"; FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); String line = br.readLine().trim(); if (line.startsWith("NO ERRORS FOUND ON INPUT")) { return; } else if (line.startsWith("WARNING...THERE IS AN ERROR IN THE LINKING FILE")) { System.out.println("Error in chemkin linking to reactor!"); System.exit(0); } else { System.out.println("Unknown message in chem.message!"); System.exit(0); } } catch (Exception e) { System.out.println("Can't read chem.message!"); System.out.println(e.getMessage()); System.exit(0); } // #] }
// ## operation runReactor() public void runReactor() { // #[ operation runReactor() // run reactor String dir = System.getProperty("RMG.workingDirectory"); try { // system call for reactor String[] command = {dir + "/software/reactorModel/reactor.exe"}; File runningDir = new File("chemkin"); Process reactor = Runtime.getRuntime().exec(command, null, runningDir); InputStream ips = reactor.getInputStream(); InputStreamReader is = new InputStreamReader(ips); BufferedReader br = new BufferedReader(is); String line = null; while ((line = br.readLine()) != null) { // System.out.println(line); } int exitValue = reactor.waitFor(); } catch (Exception e) { System.out.println("Error in running reactor!"); System.out.println(e.getMessage()); System.exit(0); } // #] }
public static void writeChemkinInputFile(ReactionSystem rs) { // #[ operation writeChemkinInputFile(ReactionModel,SystemSnapshot) StringBuilder result = new StringBuilder(); result.append(writeChemkinHeader()); result.append(writeChemkinElement()); double start = System.currentTimeMillis(); result.append(writeChemkinSpecies(rs.reactionModel, rs.initialStatus)); result.append(writeChemkinThermo(rs.reactionModel)); Global.chemkinThermo = Global.chemkinThermo + (System.currentTimeMillis() - start) / 1000 / 60; start = System.currentTimeMillis(); result.append(writeChemkinPdepReactions(rs)); Global.chemkinReaction = Global.chemkinReaction + (System.currentTimeMillis() - start) / 1000 / 60; String dir = System.getProperty("RMG.workingDirectory"); if (!dir.endsWith("/")) dir += "/"; dir += "software/reactorModel/"; String file = "chemkin/chem.inp"; try { FileWriter fw = new FileWriter(file); fw.write(result.toString()); fw.close(); } catch (Exception e) { System.out.println("Error in writing chemkin input file chem.inp!"); System.out.println(e.getMessage()); System.exit(0); } // #] }
private static SAXParserFactory createFastSAXParserFactory() throws ParserConfigurationException, SAXException { if (fastParserFactoryClass == null) { try { fastParserFactoryClass = Class.forName("org.apache.crimson.jaxp.SAXParserFactoryImpl"); // NOI18N } catch (Exception ex) { useFastSAXParserFactory = false; if (System.getProperty("java.version").startsWith("1.4")) { // NOI18N ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); } } } if (fastParserFactoryClass != null) { try { SAXParserFactory factory = (SAXParserFactory) fastParserFactoryClass.newInstance(); return factory; } catch (Exception ex) { useFastSAXParserFactory = false; throw new ParserConfigurationException(ex.getMessage()); } } return SAXParserFactory.newInstance(); }
private Map attributeMap(String tagName, Attributes atts) throws ParserException { if (null == tagName || null == atts) return null; Map mapping = null; try { mapping = (Map) attributeMaps.get(tagName); } catch (Exception e) { throw new ParserException( "Typecast error, unknown element found in attribute list mappings! " + e.getMessage()); } if (null == mapping) return null; Map resultMapping = new HashMap(); for (int i = 0; i < atts.getLength(); i++) { String xmlName = atts.getQName(i); String value = atts.getValue(i); TagMap.AttributeMapping aMap = null; try { aMap = (TagMap.AttributeMapping) mapping.get(xmlName); } catch (Exception e) { throw new ParserException( "Typecast error, unknown element found in property mapping! " + e.getMessage()); } if (null == aMap) throw new ParserException( "No attribute mapping specified for attribute: " + xmlName + " in tag: " + tagName); String propertyName = aMap.getPropertyName(); try { resultMapping.put(propertyName, aMap.convertValue(value)); } catch (Exception e) { throw new ParserException( "Can not convert given value: \"" + value + "\" to specified type: " + aMap.getType() + " for attribute: " + xmlName + " in tag: " + tagName + "! " + e.getMessage()); } } checkForRequiredAttributes(tagName, resultMapping, mapping); addDefaultValues(resultMapping, mapping); return resultMapping; }
public void endElement(String namespaceURI, String localName, String qName) throws ParserException { { } // System.out.println("end Element"); Caller targeting = (Caller) stack.pop(); try { targeting.process(); } catch (Exception e) { throw new ParserException("Could not place " + qName + " into system!\n" + e.getMessage()); } }
/** * Get the named properties for this resource and (potentially) its children. * * @param names an arrary of property names to retrieve * @return a MultiStatus of PropertyResponses * @exception com.ibm.webdav.WebDAVException */ public MultiStatus getProperties(PropertyName[] names) throws WebDAVException { MultiStatus multiStatus = resource.getProperties(resource.getContext()); MultiStatus newMultiStatus = new MultiStatus(); Enumeration responses = multiStatus.getResponses(); while (responses.hasMoreElements()) { PropertyResponse response = (PropertyResponse) responses.nextElement(); PropertyResponse newResponse = new PropertyResponse(response.getResource()); newResponse.setDescription(response.getDescription()); newMultiStatus.addResponse(newResponse); Hashtable properties = (Hashtable) response.getPropertiesByPropName(); // Hashtable newProperties = (Hashtable) newResponse.getProperties(); for (int i = 0; i < names.length; i++) { if (properties.containsKey(names[i])) { PropertyValue srcval = response.getProperty(names[i]); newResponse.setProperty(names[i], srcval); // newProperties.put(names[i], properties.get(names[i])); } else { Document factory = null; try { factory = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } catch (Exception e) { throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } // we'll create an xml element with no value because that's // what webdav will need to return for most methods... even if the // property doesn't exist. That's because the // distinction between a propertyname and propertyvalue // is fuzzy in WebDAV xml. A property name is // essentially an empty property value because // all property values have their property // name stuck on. // if we decide to set reviewStatus to null instead (as // we did previously, then the code for MultiStatus.asXML() // needs to be updated to expect null values. // (jlc 990520) Element elTm = factory.createElementNS("X", "X:" + names[i].getLocal()); elTm.setAttribute("xmlns:X", names[i].getNamespace()); newResponse.addProperty(names[i], elTm, WebDAVStatus.SC_NOT_FOUND); } } } return newMultiStatus; }
@Override public VPackage parse() { logger.debug("Starting parsing package: " + xmlFile.getAbsolutePath()); long startParsing = System.currentTimeMillis(); try { Document document = getDocument(); Element root = document.getDocumentElement(); _package = new VPackage(xmlFile); Node name = root.getElementsByTagName(EL_NAME).item(0); _package.setName(name.getTextContent()); Node descr = root.getElementsByTagName(EL_DESCRIPTION).item(0); _package.setDescription(descr.getTextContent()); NodeList list = root.getElementsByTagName(EL_CLASS); boolean initPainters = false; for (int i = 0; i < list.getLength(); i++) { PackageClass pc = parseClass((Element) list.item(i)); if (pc.getPainterName() != null) { initPainters = true; } } if (initPainters) { _package.initPainters(); } logger.info( "Parsing the package '{}' finished in {}ms.\n", _package.getName(), (System.currentTimeMillis() - startParsing)); } catch (Exception e) { collector.collectDiagnostic(e.getMessage(), true); if (RuntimeProperties.isLogDebugEnabled()) { e.printStackTrace(); } } try { checkProblems("Error parsing package file " + xmlFile.getName()); } catch (Exception e) { return null; } return _package; }
public void save(String filename) { try { Document document = element.getOwnerDocument(); document.getDocumentElement().normalize(); TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setAttribute("indent-number", new Integer(4)); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(document); File file = new File(filename); StreamResult result = new StreamResult(file); transformer.transform(source, result); } catch (Exception e) { severe("Could not save XML file: " + e.getMessage()); } }
private static Document getDocument(String docString) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); factory.setValidating(true); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(docString); } catch (Exception ex) { System.out.println(ex.getMessage()); } return null; }
public static void main(String[] args) { try { // open existing file File xmlFile = new File(userFile); DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder dbuild = dbfac.newDocumentBuilder(); Document doc = dbuild.parse(xmlFile); // DocumentBuilderFactory dbfac2 = DocumentBuilderFactory.newInstance(); // DocumentBuilder docBuilder = dbfac2.newDocumentBuilder(); // Document doc2 = docBuilder.parse(xmlFile); // doc.getDocumentElement().normalize(); } catch (Exception e) { System.err.println(e.getMessage()); } }
public XMLHelper(String filename, String root) { this(); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); try { Document document = builder.parse(new File(filename)); setElement((Element) document.getElementsByTagName(root).item(0)); } catch (Exception e) { Document document = builder.newDocument(); setElement((Element) document.appendChild(document.createElement(root))); warning("Could not load XML file: " + e.getMessage()); } } catch (ParserConfigurationException e) { // Not quite sure when this would happen severe("Could not extantiate XML builder: " + e.getMessage()); } }
private static Element readXmlFile(GenericFile file) { try { BufferedReader reader = new BufferedReader(file.getReader()); StringBuilder sBuilder = new StringBuilder(); for (String line = reader.readLine(); line != null; line = reader.readLine()) { sBuilder.append(line); sBuilder.append("\n"); } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new ByteArrayInputStream(sBuilder.toString().getBytes())); doc.getDocumentElement().normalize(); return doc.getDocumentElement(); } catch (Exception e) { e.printStackTrace(); System.err.println(e.getMessage()); return null; } }
public Command executeStep(Element stepRow) throws Exception { Command command = new Command(); NodeList stepFields = stepRow.getElementsByTagName("td"); String cmd = stepFields.item(0).getTextContent().trim(); command.cmd = cmd; ArrayList<String> argList = new ArrayList<String>(); if (stepFields.getLength() == 1) { // skip comments command.result = "OK"; return command; } for (int i = 1; i < stepFields.getLength(); i++) { String content = stepFields.item(i).getTextContent(); content = content.replaceAll(" +", " "); content = content.replace('\u00A0', ' '); content = content.trim(); argList.add(content); } String args[] = argList.toArray(new String[0]); command.args = args; if (this.verbose) { System.out.println(cmd + " " + Arrays.asList(args)); } try { command.result = this.commandProcessor.doCommand(cmd, args); command.error = false; } catch (Exception e) { command.result = e.getMessage(); command.error = true; } command.failure = command.error && !cmd.startsWith("verify"); if (this.verbose) { System.out.println(command.result); } return command; }
@Override public HashSet<ScoredAnnotation> solveSa2W(String text) throws AnnotationException { HashSet<ScoredAnnotation> res; try { res = new HashSet<ScoredAnnotation>(); lastTime = Calendar.getInstance().getTimeInMillis(); URL wikiApi = new URL(url); String parameters = "references=true&repeatMode=all&minProbability=0.0&source=" + URLEncoder.encode(text, "UTF-8"); HttpURLConnection slConnection = (HttpURLConnection) wikiApi.openConnection(); slConnection.setRequestProperty("accept", "text/xml"); slConnection.setDoOutput(true); slConnection.setDoInput(true); slConnection.setRequestMethod("POST"); slConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); slConnection.setRequestProperty("charset", "utf-8"); slConnection.setRequestProperty( "Content-Length", "" + Integer.toString(parameters.getBytes().length)); slConnection.setUseCaches(false); DataOutputStream wr = new DataOutputStream(slConnection.getOutputStream()); wr.writeBytes(parameters); wr.flush(); wr.close(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(slConnection.getInputStream()); /* URL wikiApi = new URL(url+"?references=true&repeatMode=all&minProbability=0.0&source="+URLEncoder.encode(text, "UTF-8")); URLConnection wikiConnection = wikiApi.openConnection(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(wikiConnection.getInputStream()); */ lastTime = Calendar.getInstance().getTimeInMillis() - lastTime; XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression idExpr = xpath.compile("//detectedTopic/@id"); XPathExpression weightExpr = xpath.compile("//detectedTopic/@weight"); XPathExpression referenceExpr = xpath.compile("//detectedTopic/references"); NodeList ids = (NodeList) idExpr.evaluate(doc, XPathConstants.NODESET); NodeList weights = (NodeList) weightExpr.evaluate(doc, XPathConstants.NODESET); NodeList references = (NodeList) referenceExpr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < weights.getLength(); i++) { if (weights.item(i).getNodeType() != Node.TEXT_NODE) { int id = Integer.parseInt(ids.item(i).getNodeValue()); float weight = Float.parseFloat(weights.item(i).getNodeValue()); // System.out.println("ID="+ids.item(i).getNodeValue()+" weight="+weight); XPathExpression startExpr = xpath.compile("//detectedTopic[@id=" + id + "]/references/reference/@start"); XPathExpression endExpr = xpath.compile("//detectedTopic[@id=" + id + "]/references/reference/@end"); NodeList starts = (NodeList) startExpr.evaluate(references.item(i), XPathConstants.NODESET); NodeList ends = (NodeList) endExpr.evaluate(references.item(i), XPathConstants.NODESET); for (int j = 0; j < starts.getLength(); j++) { int start = Integer.parseInt(starts.item(j).getNodeValue()); int end = Integer.parseInt(ends.item(j).getNodeValue()); int len = end - start; res.add(new ScoredAnnotation(start, len, id, weight)); } } } } catch (Exception e) { e.printStackTrace(); throw new AnnotationException( "An error occurred while querying Wikipedia Miner API. Message: " + e.getMessage()); } return res; }
/** * XML Circuit constructor * * @param file the file that contains the XML description of the circuit * @param g the graphics that will paint the node * @throws CircuitLoadingException if the internal circuit can not be loaded */ public CircuitUI(File file, Graphics g) throws CircuitLoadingException { this(""); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; Document doc; Element root; Hashtable<Integer, Link> linkstable = new Hashtable<Integer, Link>(); try { builder = factory.newDocumentBuilder(); doc = builder.parse(file); } catch (SAXException sxe) { throw new CircuitLoadingException("SAX exception raised, invalid XML file."); } catch (ParserConfigurationException pce) { throw new CircuitLoadingException( "Parser exception raised, parser configuration is invalid."); } catch (IOException ioe) { throw new CircuitLoadingException("I/O exception, file cannot be loaded."); } root = (Element) doc.getElementsByTagName("Circuit").item(0); this.setName(root.getAttribute("name")); NodeList nl = root.getElementsByTagName("Node"); Element e; Node n; Class cl; for (int i = 0; i < nl.getLength(); ++i) { e = (Element) nl.item(i); try { cl = Class.forName(e.getAttribute("class")); } catch (Exception exc) { System.err.println(exc.getMessage()); throw new RuntimeException("Circuit creation from xml."); } try { n = ((Node) cl.newInstance()); } catch (Exception exc) { System.err.println(exc.getMessage()); throw new RuntimeException("Circuit creation from xml."); } this.nodes.add(n); n.setLocation(new Integer(e.getAttribute("x")), new Integer(e.getAttribute("y"))); if (n instanceof giraffe.ui.Nameable) ((Nameable) n).setNodeName(e.getAttribute("node_name")); if (n instanceof giraffe.ui.CompositeNode) { try { ((CompositeNode) n) .load(new File(file.getParent() + "/" + e.getAttribute("file_name")), g); } catch (Exception exc) { /* try to load from the lib */ ((CompositeNode) n) .load(new File(giraffe.Giraffe.PATH + "/lib/" + e.getAttribute("file_name")), g); } } NodeList nlist = e.getElementsByTagName("Anchor"); Element el; for (int j = 0; j < nlist.getLength(); ++j) { el = (Element) nlist.item(j); Anchor a = n.getAnchor(new Integer(el.getAttribute("id"))); NodeList linklist = el.getElementsByTagName("Link"); Element link; Link l; for (int k = 0; k < linklist.getLength(); ++k) { link = (Element) linklist.item(k); int id = new Integer(link.getAttribute("id")); int index = new Integer(link.getAttribute("index")); if (id >= this.linkID) linkID = id + 1; if (linkstable.containsKey(id)) { l = linkstable.get(id); l.addLinkedAnchorAt(a, index); a.addLink(l); } else { l = new Link(id); l.addLinkedAnchorAt(a, index); this.links.add(l); linkstable.put(id, l); a.addLink(l); } } } } }
// ## operation writeReactorInputFile(ReactionModel,ReactionTime,ReactionTime,SystemSnapshot) public boolean writeReactorInputFile( ReactionModel p_reactionModel, ReactionTime p_beginTime, ReactionTime p_endTime, SystemSnapshot p_beginStatus) { // #[ operation writeReactorInputFile(ReactionModel,ReactionTime,ReactionTime,SystemSnapshot) // construct "input" string String input = "<?xml version=\"1.0\" standalone=\"no\"?>" + "\n"; String dir = System.getProperty("RMG.workingDirectory"); if (!dir.endsWith("/")) dir += "/"; String dtd = dir + "software/reactorModel/documentTypeDefinitions/reactorInput.dtd"; input += "<!DOCTYPE reactorinput SYSTEM \"" + dtd + "\">" + "\n"; input += "<reactorinput>" + "\n"; input += "<header>" + "\n"; input += "<title>Reactor Input File</title>" + "\n"; input += "<description>RMG-generated file used to call an external reactor model</description>" + "\n"; input += "</header>" + "\n"; input += "<inputvalues>" + "\n"; input += "<integrationparameters>" + "\n"; input += "<reactortype>" + reactorType + "</reactortype>" + "\n"; input += "<starttime units=\"" + p_beginTime.getUnit() + "\">" + MathTool.formatDouble(p_beginTime.getTime(), 15, 6) + "</starttime>" + "\n"; input += "<endtime units=\"" + p_endTime.getUnit() + "\">" + MathTool.formatDouble(p_endTime.getTime(), 15, 6) + "</endtime>" + "\n"; // input += "<starttime units=\"" + p_beginTime.unit + "\">" + // MathTool.formatDouble(p_beginTime.time,15,6) + "</starttime>" + "\n"; // input += "<endtime units=\"" + p_endTime.unit + "\">" + // MathTool.formatDouble(p_endTime.time,15,6) + "</endtime>" + "\n"; input += "<rtol>" + rtol + "</rtol>" + "\n"; input += "<atol>" + atol + "</atol>" + "\n"; input += "</integrationparameters>" + "\n"; input += "<chemistry>" + "\n"; input += "</chemistry>" + "\n"; input += "<systemstate>" + "\n"; input += "<temperature units=\"K\">" + MathTool.formatDouble(p_beginStatus.getTemperature().getK(), 15, 6) + "</temperature>" + "\n"; input += "<pressure units=\"Pa\">" + MathTool.formatDouble(p_beginStatus.getPressure().getPa(), 15, 6) + "</pressure>" + "\n"; for (Iterator iter = p_beginStatus.getSpeciesStatus(); iter.hasNext(); ) { SpeciesStatus spcStatus = (SpeciesStatus) iter.next(); Species thisSpecies = spcStatus.getSpecies(); CoreEdgeReactionModel cerm = (CoreEdgeReactionModel) p_reactionModel; if (cerm.containsAsReactedSpecies(thisSpecies)) { String spcChemkinName = thisSpecies.getChemkinName(); double concentration = spcStatus.getConcentration(); input += "<amount units=\"molPerCm3\" speciesid=\"" + spcChemkinName + "\">" + concentration + "</amount>" + "\n"; } } for (Iterator iter = p_beginStatus.getInertGas(); iter.hasNext(); ) { String name = (String) iter.next(); double conc = p_beginStatus.getInertGas(name); if (conc != 0.0) input += "<amount units=\"molPerCm3\" speciesid=\"" + name + "\">" + conc + "</amount>" + "\n"; } input += "</systemstate>" + "\n"; input += "</inputvalues>" + "\n"; input += "</reactorinput>" + "\n"; // write "input" string to file try { String file = "chemkin/reactorInput.xml"; FileWriter fw = new FileWriter(file); fw.write(input); fw.close(); return true; } catch (Exception e) { System.out.println("Error in writing reactorInput.xml!"); System.out.println(e.getMessage()); return false; } // #] }
public void saveUnsaved() throws SaveAbortedException { if (!saved) { int option = 0; if (loadedFile == null) option = JOptionPane.showConfirmDialog( this, new JLabel("Save changes to UNTITLED?"), "Warning", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); else option = JOptionPane.showConfirmDialog( this, new JLabel("Save changes to " + loadedFile.getName() + "?"), "Warning", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (option == JOptionPane.YES_OPTION) { if (loadedFile == null) // SAVE NEW FILE { if (nameTF.getText().equals("")) { JOptionPane.showMessageDialog( this, new JLabel("Please type in the Scale Name"), "Warning", JOptionPane.WARNING_MESSAGE); throw new SaveAbortedException(); } fileChooser.setFileFilter(filter); int option2 = fileChooser.showSaveDialog(this); if (option2 == JFileChooser.APPROVE_OPTION) { File target = fileChooser.getSelectedFile(); try { PrintStream stream = new PrintStream(new FileOutputStream(target), true); save(stream); stream.close(); } catch (Exception ex) { JOptionPane.showMessageDialog( this, new JLabel("Error: " + ex.getMessage()), "Error", JOptionPane.ERROR_MESSAGE); } } else throw new SaveAbortedException(); ; } else // save LOADED FILE { try { PrintStream stream = new PrintStream(new FileOutputStream(loadedFile), true); save(stream); stream.close(); } catch (Exception ex) { JOptionPane.showMessageDialog( this, new JLabel("Error: " + ex.getMessage()), "Error", JOptionPane.ERROR_MESSAGE); } } } else if (option == JOptionPane.CANCEL_OPTION) throw new SaveAbortedException(); ; } }
// реализуем метод парсинга @Override public List<Root.News> parse(File fileToParse) { try { // создаем фабрику документов, в наш документ парсим файл DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); // парсим файл в документ dom = db.parse(fileToParse); } catch (SAXException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } catch (Exception e) { System.out.println(e.getMessage()); } // root элемент Element root = dom.getDocumentElement(); // NodeList новостей NodeList elementsNodeList = root.getElementsByTagName("news").item(0).getChildNodes(); // перебираем все элементы for (int i = 0; i < elementsNodeList.getLength(); i++) { Node item = elementsNodeList.item(i); if (item.getNodeType() != Node.ELEMENT_NODE) { // если вернуло что-то не то continue; } Element element = (Element) item; Root.News myNews = new Root.News(); // дата String tempDate = element.getElementsByTagName("date").item(0).getTextContent(); SimpleDateFormat format = new SimpleDateFormat(Constants.DATE_FORMAT_IN); Date date = null; try { date = format.parse(tempDate); } catch (ParseException e) { e.printStackTrace(); } // описание String description = element.getElementsByTagName("description").item(0).getTextContent(); // id int id = Integer.parseInt(element.getElementsByTagName("id").item(0).getTextContent()); // ключевые слова List<String> keywordsList = new ArrayList<String>(); // перебираем ключевые слова NodeList keywords = element.getElementsByTagName("keywords").item(0).getChildNodes(); for (int j = 0; j < keywords.getLength(); j++) { Node itemKey = keywords.item(j); if (itemKey.getNodeType() != Node.ELEMENT_NODE) { // если вернуло что-то не то continue; } keywordsList.add(itemKey.getFirstChild().getTextContent()); } // заголовок String title = element.getElementsByTagName("title").item(0).getTextContent(); // буленовская переменная boolean isVisible = Boolean.parseBoolean(element.getElementsByTagName("visible").item(0).getTextContent()); // записываем данные в экземпляр новости myNews.setDescription(description); myNews.setDate(date); myNews.setTitle(title); myNews.setId(id); myNews.setKeywords(keywordsList); myNews.setVisible(isVisible); // добавляем новость в список news.add(myNews); } System.out.println("---> Парсинг файла " + "\"" + fileToParse + "\" завершен!"); return news; }
// ## 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 void actionPerformed(ActionEvent e) { JButton b = (JButton) e.getSource(); if (b.getText() == "PLAY") { if (scoreP != null) scoreP.playScale(sp.getScale(), tempoP.getValue()); } else if (b.getText() == "New") { try { saveUnsaved(); } catch (SaveAbortedException ex) { return; } sp.notes.removeAllElements(); sp.repaint(); nameTF.setText(""); loadedFile = null; } else if (b.getText() == "Save") { if (nameTF.getText().equals("")) { JOptionPane.showMessageDialog( this, new JLabel("Please type in the Scale Name"), "Warning", JOptionPane.WARNING_MESSAGE); return; } fileChooser.setFileFilter(filter); int option = fileChooser.showSaveDialog(this); if (option == JFileChooser.APPROVE_OPTION) { File target = fileChooser.getSelectedFile(); if (target.getName().indexOf(".scl") == -1) target = new File(target.getPath() + ".scl"); try { PrintStream stream = new PrintStream(new FileOutputStream(target), true); save(stream); stream.close(); } catch (Exception ex) { JOptionPane.showMessageDialog( this, new JLabel("Error: " + ex.getMessage()), "Error", JOptionPane.ERROR_MESSAGE); } } } else if (b.getText() == "Load") { try { saveUnsaved(); } catch (SaveAbortedException ex) { return; } fileChooser.setFileFilter(filter); int option = fileChooser.showOpenDialog(this); if (option == JFileChooser.APPROVE_OPTION) { loadedFile = fileChooser.getSelectedFile(); SAXParserFactory factory = SAXParserFactory.newInstance(); ScaleParser handler = new ScaleParser(false); try { SAXParser parser = factory.newSAXParser(); parser.parse(loadedFile, handler); // System.out.println("success"); } catch (Exception ex) { // System.out.println("no!!!!!! exception: "+e); // System.out.println(ex.getMessage()); ex.printStackTrace(); } // -----now :P:P--------------- System.out.println("name: " + handler.getName()); nameTF.setText(handler.getName()); sp.notes.removeAllElements(); int[] scale = handler.getScale(); for (int i = 0; i < scale.length; i++) { sp.addNote(scale[i]); } sp.repaint(); } else loadedFile = null; } }