private ClassLoaderStrategy getClassLoaderStrategy(String fullyQualifiedClassName) throws Exception { try { // Get just the package name StringBuffer sb = new StringBuffer(fullyQualifiedClassName); sb.delete(sb.lastIndexOf("."), sb.length()); currentPackage = sb.toString(); // Retrieve the Java classpath from the system properties String cp = System.getProperty("java.class.path"); String sepChar = System.getProperty("path.separator"); String[] paths = StringUtils.pieceList(cp, sepChar.charAt(0)); ClassLoaderStrategy cl = ClassLoaderUtil.getClassLoader(ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {}); // Iterate through paths until class with the specified name is found String classpath = StringUtils.replaceChar(currentPackage, '.', File.separatorChar); for (int i = 0; i < paths.length; i++) { Class[] classes = cl.getClasses(paths[i] + File.separatorChar + classpath, currentPackage); for (int j = 0; j < classes.length; j++) { if (classes[j].getName().equals(fullyQualifiedClassName)) { return ClassLoaderUtil.getClassLoader( ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {paths[i]}); } } } throw new Exception("Class could not be found."); } catch (Exception e) { System.err.println("Exception creating class loader strategy."); System.err.println(e.getMessage()); throw e; } }
// ## 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); } // #] }
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(); }
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); } // #] }
// ## 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 List<GenerationTarget> getTargets() { if (m_targets != null) { return m_targets; } m_targets = new ArrayList<GenerationTarget>(); URL location = getClassLocation(); if (location == null) return m_targets; if (location.getProtocol().equals("file")) { String encoded = location.getFile(); File classFileLocation = null; try { String decoded = URLDecoder.decode(encoded, "UTF-8"); // important classFileLocation = new File(decoded); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } // end try if (classFileLocation != null) { File root = classFileLocation; String classname = GenerationTarget.class.getName(); int levels = countNbChars(classname, '.'); // iterate to the root for (int i = 0; i < levels; i++) { root = root.getParentFile(); } // end while scanFolder(classFileLocation.getParentFile(), root, m_targets); } } else if (location.getProtocol().equals("jar")) { String jarname = location.toExternalForm(); int index = jarname.indexOf(".jar!"); if (index > -1) jarname = jarname.substring(0, index + 4); index = jarname.indexOf("jar:"); if (index > -1) { jarname = jarname.substring(4); } index = jarname.indexOf("file:/"); if (index > -1) { jarname = jarname.substring(6); } index = jarname.indexOf("file:"); if (index > -1) { jarname = jarname.substring(5); } scanJar(new File(jarname), new File(System.getProperty("java.io.tmpdir")), m_targets); } return m_targets; }
// ## 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); } } // #] }
@Test public void parseRootElementWithFile() throws Exception { String xml = "<?xml version=\"1.0\"?><html><head /><body><p>Good morning</p><p>How are you?</p></body></html>"; File f = new File(System.getProperty("java.io.tmpdir"), "test.xml"); Utils.writeFile(f, xml); f.deleteOnExit(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document doc = builder.parse(f); Element root = doc.getDocumentElement(); Assert.assertEquals("html", root.getNodeName()); }
public String toString() { String endl = System.getProperty("line.separator"); String str = ""; if (numRunningJobs != -1) { str += "running jobs: " + numRunningJobs + endl; } if (numWaitingJobs != -1) { str += "waiting jobs: " + numWaitingJobs + endl; } if (usedProcessors != -1) { str += "used processors: " + usedProcessors + endl; } return str; }
@Test public void testgetAttributesWithNamedNodeMap() throws Exception { // builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); File f = new File(System.getProperty("user.dir"), "src/test/resources/sample-springbeans.xml"); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document doc = builder.parse(f); Element root = doc.getDocumentElement(); // System.out.println("* current impl: " + doc.getClass().getName()); // id, class Map<String, String> actualMap = new HashMap<String, String>(); NodeList list = root.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node instanceof Element) { Element elem = (Element) node; if (elem.getTagName().equals("beans:bean")) { // System.out.println("bean[" + elem.getAttribute("id") + "]"); NamedNodeMap map = elem.getAttributes(); String valueId = null; String valueClass = null; for (int x = 0; x < map.getLength(); x++) { Node attr = map.item(x); if (attr.getNodeName().equals("id")) valueId = attr.getNodeValue(); if (attr.getNodeName().equals("class")) valueClass = attr.getNodeValue(); } if (valueId != null && valueClass != null) actualMap.put(valueId, valueClass); } } } Map<String, String> expected = new HashMap<String, String>(); expected.put("authenticationManager", "org.springframework.security.providers.ProviderManager"); expected.put( "daoAuthenticationProvider", "org.springframework.security.providers.dao.DaoAuthenticationProvider"); expected.put( "loggerListener", "org.springframework.security.event.authentication.LoggerListener"); Assert.assertEquals("Attributes with NamedNodeMap", expected, actualMap); }
/** Initialize the GUI */ private void initGUI() { counts theApp_new_counts = new counts(); String sysPath = System.getProperty("user.home") + File.separator + "SRSCKT" + File.separator + "pkg"; File sysDir = new File(sysPath); // if our system folder doesn't exist it creates it if (!sysDir.exists()) sysDir.mkdirs(); String[] SysPkgs = sysDir.list(); for (String x : SysPkgs) { System.out.println(x); package_cls defaultPkgs = new package_cls( x, theApp_new_counts, 1); // sysCall is 1 as System Packages will be installed } connections theApp_new_connections = new connections(); this.setFrame(theApp_new_counts, theApp_new_connections); this.setPath(null); this.setSaved(false); // default false }
// ## operation Chemkin(double,double,String) public Chemkin(double p_rtol, double p_atol, String p_reactorType) { // #[ operation Chemkin(double,double,String) if (p_rtol < 0 || p_atol < 0) throw new InvalidChemkinParameterException("Negative rtol or atol!"); if (p_reactorType == null) throw new NullPointerException(); String dir = System.getProperty("RMG.workingDirectory"); // create the documentTypesDefinitions File docFile = new File("chemkin/documentTypeDefinitions"); docFile.mkdir(); copyFiles( dir + "/software/reactorModel/documentTypeDefinitions/reactorInput.dtd", "chemkin/documentTypeDefinitions/reactorInput.dtd"); copyFiles( dir + "/software/reactorModel/documentTypeDefinitions/reactorOutput.dtd", "chemkin/documentTypeDefinitions/reactorOutput.dtd"); rtol = p_rtol; atol = p_atol; reactorType = p_reactorType; }
// ## 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 static void main(String[] args) { String specloc = System.getProperty("spec"); if (specloc == null) { System.out.print("No spec file given, quitting"); System.exit(0); } DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z"); java.util.Date date = new java.util.Date(); String startstamp = dateFormat.format(date); boolean firstrun = true; while (true) { System.out.println("Loading XML Spec file: " + specloc); // BufferedWriter out = null; SocketAcceptor acceptor = null; SocketAcceptor statusacceptor = null; Vector<MonitorThread> monitorlist = new Vector<MonitorThread>(); try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File(specloc)); doc.getDocumentElement().normalize(); String heartbeatportString = doc.getDocumentElement().getAttribute("heartbeatport"); String statusportString = doc.getDocumentElement().getAttribute("statusport"); String logfiledir = doc.getDocumentElement().getAttribute("logfiledir"); String masterlabel = doc.getDocumentElement().getAttribute("label"); String nodeid = doc.getDocumentElement().getAttribute("id"); String smtphost = doc.getDocumentElement().getAttribute("smtphost"); String l1mailto = doc.getDocumentElement().getAttribute("l1mailto"); String l2mailto = doc.getDocumentElement().getAttribute("l2mailto"); String l2threshold = doc.getDocumentElement().getAttribute("l2threshold"); if (heartbeatportString == null || heartbeatportString.equals("")) { System.out.println("No heartbeat specified in spec, quitting"); System.exit(0); } if (statusportString == null || statusportString.equals("")) { System.out.println("No status port specified in spec, quitting"); System.exit(0); } if (logfiledir == null || logfiledir.equals("")) { System.out.println("No logfile directory location specified in spec, quitting"); System.exit(0); } int heartbeatport = Integer.valueOf(heartbeatportString).intValue(); System.out.println("This Monitor is using port " + heartbeatport + " for heartbeat"); int statusport = Integer.valueOf(statusportString).intValue(); System.out.println("This Monitor is using port " + statusport + " for status updates"); System.out.println("Logging to directory " + logfiledir); Log log = new Log(logfiledir); log.nodelabel = masterlabel; log.setMailer(smtphost, l1mailto, l2mailto, convertStringToInt(l2threshold)); if (firstrun) { firstrun = false; log.logit("Monitor Node Started", "start", null); } log.logit("Logging started", "", null); ThreadPing threadping = new ThreadPing(log, false); Thread pinger = new Thread(threadping); threadping.thisThread = pinger; pinger.start(); log.pinger = threadping; // ShutdownHook hook = new ShutdownHook(out); // Runtime.getRuntime().addShutdownHook(hook); // Starting Heartbeat server acceptor = new NioSocketAcceptor(); acceptor.getSessionConfig().setReuseAddress(true); acceptor.getSessionConfig().setTcpNoDelay(true); acceptor.setReuseAddress(true); // acceptor.getFilterChain().addLast("logger", new LoggingFilter()); acceptor .getFilterChain() .addLast( "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); acceptor.setReuseAddress(true); // acceptor.setCloseOnDeactivation(true); acceptor.getSessionConfig().setTcpNoDelay(true); acceptor.setDefaultLocalAddress(new InetSocketAddress(heartbeatport)); Vector<IoSession> sessionlist = new Vector<IoSession>(); acceptor.setHandler(new HeartBeatHandler(sessionlist)); acceptor.bind(); // Starting Path Monitoring NodeList listOfServers = doc.getElementsByTagName("check"); int totalServers = listOfServers.getLength(); System.out.println("Total # of checks: " + totalServers); // Vector<PingMonitorThread> pinglist = new Vector<PingMonitorThread>(); // Vector<PortMonitorThread> portlist = new Vector<PortMonitorThread>(); // Vector<HeartbeatMonitorThread> heartbeatlist = new Vector<HeartbeatMonitorThread>(); System.out.println(); for (int i = 0; i < totalServers; i++) { Node serverNode = listOfServers.item(i); Element serverNodeElement = (Element) serverNode; String checklabel = serverNodeElement.getAttribute("label"); String host = serverNodeElement .getElementsByTagName("host") .item(0) .getChildNodes() .item(0) .getNodeValue(); String checktype = serverNodeElement .getElementsByTagName("checktype") .item(0) .getChildNodes() .item(0) .getNodeValue(); boolean enabled = true; if (serverNodeElement.getElementsByTagName("enabled").item(0) != null && serverNodeElement .getElementsByTagName("enabled") .item(0) .getChildNodes() .item(0) .getNodeValue() .toLowerCase() .equals("false")) { enabled = false; } String successrateString = serverNodeElement .getElementsByTagName("successrate") .item(0) .getChildNodes() .item(0) .getNodeValue(); String retryrateString = serverNodeElement .getElementsByTagName("retryrate") .item(0) .getChildNodes() .item(0) .getNodeValue(); // String l2thresholdoverride = // serverNodeElement.getElementsByTagName("l2threshold").item(0).getChildNodes().item(0).getNodeValue(); String l2thresholdoverride = getElementValue("l2threshold", serverNodeElement); // String l1mailtoadd = // serverNodeElement.getElementsByTagName("l1mailto").item(0).getChildNodes().item(0).getNodeValue(); String l1mailtoadd = getElementValue("l1mailto", serverNodeElement); // String l2mailtoadd = // serverNodeElement.getElementsByTagName("l2mailto").item(0).getChildNodes().item(0).getNodeValue(); String l2mailtoadd = getElementValue("l2mailto", serverNodeElement); int l2thresholdoverrideint = convertStringToInt(l2thresholdoverride); String[] l1mailtoaddarray = new String[0]; String[] l2mailtoaddarray = new String[0]; if (!l1mailtoadd.equals("")) { l1mailtoaddarray = l1mailtoadd.split(","); } if (!l2mailtoadd.equals("")) { l2mailtoaddarray = l2mailtoadd.split(","); } // System.out.println(l1mailtoaddarray.length + "-" + l2mailtoaddarray.length); int successrate = 30; int retryrate = 30; if (host == null || host.equals("")) { System.out.println("No Host, skipping this path"); enabled = false; } if (successrateString == null || successrateString.equals("")) { System.out.println( "No Success Rate defined, using default (" + successrate + " seconds)"); } else { successrate = Integer.valueOf(successrateString).intValue(); } if (retryrateString == null || retryrateString.equals("")) { System.out.println("No retry rate defined, using default (" + retryrate + " seconds)"); } else { retryrate = Integer.valueOf(retryrateString).intValue(); } System.out.println(checklabel); if (checktype.equals("heartbeat")) { String portString = serverNodeElement .getElementsByTagName("port") .item(0) .getChildNodes() .item(0) .getNodeValue(); if (portString == null || portString.equals("")) { System.out.println("No Heartbeat, skipping this path"); } else { int heartbeat = Integer.valueOf(portString).intValue(); System.out.println("Starting Heartbeat Check:"); System.out.println("Host: " + host); System.out.println("Port: " + heartbeat); System.out.println(); HeartbeatMonitorThread m = new HeartbeatMonitorThread( host, heartbeat, log, successrate, retryrate, checklabel); m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray); Thread t = new Thread(m); m.thisthread = t; if (enabled) { t.start(); log.logit( "Starting Heartbeat Check - " + host + ":" + heartbeat, "enable-" + successrate + "-" + retryrate, m.getStatus()); } else { log.logit( "Heartbeat Check - " + host + ":" + heartbeat + " Disabled on start", "disable", m.getStatus()); } monitorlist.add(m); } } else if (checktype.equals("ping")) { System.out.println("Starting Ping Check:"); System.out.println("Host: " + host); System.out.println(); PingMonitorThread m = new PingMonitorThread(host, log, successrate, retryrate, checklabel); m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray); Thread t = new Thread(m); m.thisthread = t; if (enabled) { t.start(); log.logit( "Starting Ping Check - " + host, "enable-" + successrate + "-" + retryrate, m.getStatus()); } else { log.logit("Ping Check - " + host + " Disabled on start", "disable", m.getStatus()); } monitorlist.add(m); } else if (checktype.equals("port")) { String portString = serverNodeElement .getElementsByTagName("port") .item(0) .getChildNodes() .item(0) .getNodeValue(); if (portString == null || portString.equals("")) { System.out.println("No Port Given, skipping"); } else { int heartbeat = Integer.valueOf(portString).intValue(); System.out.println("Starting Port Check:"); System.out.println("Host: " + host); System.out.println("Port: " + heartbeat); System.out.println(); PortMonitorThread m = new PortMonitorThread(host, heartbeat, log, successrate, retryrate, checklabel); m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray); Thread t = new Thread(m); m.thisthread = t; if (enabled) { t.start(); log.logit( "Starting Port Check - " + host + ":" + heartbeat, "enable-" + successrate + "-" + retryrate, m.getStatus()); } else { log.logit( "Port Check - " + host + ":" + heartbeat + " Disabled on start", "disable", m.getStatus()); } monitorlist.add(m); } } } statusacceptor = new NioSocketAcceptor(); statusacceptor.setReuseAddress(true); // statusacceptor.getFilterChain().addLast("logger", new LoggingFilter()); statusacceptor.getSessionConfig().setTcpNoDelay(true); statusacceptor.getSessionConfig().setKeepAlive(true); statusacceptor.getSessionConfig().setBothIdleTime(5); statusacceptor.getSessionConfig().setReaderIdleTime(5); statusacceptor.getSessionConfig().setWriteTimeout(5); // statusacceptor.setReuseAddress(true); statusacceptor.setCloseOnDeactivation(true); statusacceptor.setDefaultLocalAddress(new InetSocketAddress(statusport)); statusacceptor.setHandler( new StatusHttpProtocolHandler( monitorlist, acceptor, statusacceptor, log, masterlabel, nodeid, sessionlist, startstamp)); statusacceptor.bind(); System.out.println("Status Listener activated..."); } catch (Exception e) { e.printStackTrace(); try { // out.flush(); // out.close(); } catch (Exception e2) { } try { Thread.sleep(30000); } catch (Exception e3) { } } for (int x = 0; x < monitorlist.size(); x++) { if (monitorlist.get(x).getThisThread() != null) { try { monitorlist.get(x).getThisThread().join(); } catch (Exception e) { } } } if (acceptor != null) { while (acceptor.isActive() || !acceptor.isDisposed()) { try { Thread.sleep(1000); } catch (Exception e) { } } } if (statusacceptor != null) { while (statusacceptor.isActive() || !statusacceptor.isDisposed()) { try { Thread.sleep(1000); } catch (Exception e) { } } } System.out.println("Main thread has reached end, reloading..."); /* try { Thread.sleep(9999999); } catch (Exception e) { e.printStackTrace(); } */ } }
/** * This class wrapps WikiTableWriter * * @author shahzad bhatti * <p>modification history date who what 1/9/06 SB created. */ public class WikiTableWriter implements ExtendedHierarchicalStreamWriter { private final PointableWriter writer; private final FastStack elementStack = new FastStack(16); private final char[] lineIndenter; private boolean useLineSeparateBetweenTags; private boolean tagInProgress; private int startPointer; private int depth; private boolean readyForNewLine; private boolean tagIsEmpty; private boolean quickNodeValue; private boolean lastTagHadAttributes; private static final char[] AMP = "&".toCharArray(); private static final char[] LT = "<".toCharArray(); private static final char[] GT = ">".toCharArray(); private static final char[] SLASH_R = "
".toCharArray(); private static final char[] QUOT = """.toCharArray(); private static final char[] APOS = "'".toCharArray(); private static final char[] CLOSE = "</".toCharArray(); private static final String LF = System.getProperty("line.separator"); /** * WikiTableWriter constructor * * @param writer - output writer object * @param lineIdenter - indentation */ public WikiTableWriter(Writer writer, char[] lineIndenter) { this.writer = new PointableWriter(writer); this.lineIndenter = lineIndenter; this.useLineSeparateBetweenTags = true; // context.getConfig().getBoolean("testplayer.fitnesse.use.line.separator.between.tags", true); } /** * WikiTableWriter constructor * * @param writer - output writer object * @param lineIdenter - indentation */ public WikiTableWriter(Writer writer, String lineIndenter) { this(writer, lineIndenter.toCharArray()); } /** * WikiTableWriter constructor * * @param writer - print writer object */ public WikiTableWriter(PrintWriter writer) { this(writer, new char[] {'|'}); } /** * WikiTableWriter constructor * * @param writer - writer object */ public WikiTableWriter(Writer writer) { this(new PrintWriter(writer)); } /** * Marks start of XML node * * @param name - name of node */ public void startNode(String name, Class clazz) { startNode(name); } public void startNode(String name) { startPointer = writer.getPointer(); quickNodeValue = false; lastTagHadAttributes = false; tagIsEmpty = false; finishTag(); if (depth != 0) writer.write(LF); writer.write( WikiTableDriver.DELIM + WikiTableDriver.QUOTES + WikiTableDriver.START_NODE + WikiTableDriver.QUOTES + WikiTableDriver.DELIM); if (this.useLineSeparateBetweenTags) { writer.write(LF + WikiTableDriver.DELIM); } writer.write(name + WikiTableDriver.DELIM); elementStack.push(name); tagInProgress = true; depth++; readyForNewLine = true; tagIsEmpty = true; } /** * Stores value of previously defined XML node * * @param text - value of node */ public void setValue(String text) { readyForNewLine = false; tagIsEmpty = false; finishTag(); if (lastTagHadAttributes) { writer.write( LF + WikiTableDriver.DELIM + WikiTableDriver.QUOTES + WikiTableDriver.SET_VALUE + WikiTableDriver.QUOTES + WikiTableDriver.DELIM); quickNodeValue = false; } else { String startTag = StringHelper.replace( writer.substring(startPointer), WikiTableDriver.START_NODE, WikiTableDriver.SET_NODE_VALUE); if (this.useLineSeparateBetweenTags) { writer.write(LF + WikiTableDriver.DELIM); } writer.setPointer(startPointer); writer.write(startTag); quickNodeValue = true; } writeText(writer, text); writer.write(WikiTableDriver.DELIM); } /** * Adds attribute for XML node * * @param key - name of attribute * @param value - value of attribute */ public void addAttribute(String key, String value) { writer.write( LF + WikiTableDriver.DELIM + WikiTableDriver.QUOTES + WikiTableDriver.ADD_ATTRIBUTE + WikiTableDriver.QUOTES + WikiTableDriver.DELIM); if (this.useLineSeparateBetweenTags) { writer.write(LF + WikiTableDriver.DELIM); } writer.write(key + WikiTableDriver.DELIM); writeAttributeValue(writer, value); writer.write(WikiTableDriver.DELIM); lastTagHadAttributes = true; } /** Marks end of node */ public void endNode() { depth--; if (tagIsEmpty) { String prevTag = (String) elementStack.pop(); // Silently(); if (!quickNodeValue) { writer.write( LF + WikiTableDriver.DELIM + WikiTableDriver.QUOTES + WikiTableDriver.END_NODE + WikiTableDriver.QUOTES + WikiTableDriver.DELIM); if (this.useLineSeparateBetweenTags) { writer.write(LF + WikiTableDriver.DELIM); } writer.write(prevTag + WikiTableDriver.DELIM); } readyForNewLine = false; } else { String prevTag = (String) elementStack.pop(); if (!quickNodeValue) { writer.write( LF + WikiTableDriver.DELIM + WikiTableDriver.QUOTES + WikiTableDriver.END_NODE + WikiTableDriver.QUOTES + WikiTableDriver.DELIM); if (this.useLineSeparateBetweenTags) { writer.write(LF + WikiTableDriver.DELIM); } writer.write(prevTag + WikiTableDriver.DELIM); } } finishTag(); readyForNewLine = true; if (depth == 0) { writer.flush(); } quickNodeValue = false; } /** Flushes output */ public void flush() { writer.flush(); } /** Closes output */ public void close() { writer.close(); } /** Returns underlying writer */ public HierarchicalStreamWriter underlyingWriter() { return this; } ///////////////////////////////////////////////////////////////////////// // private void finishTag() { tagInProgress = false; readyForNewLine = false; tagIsEmpty = false; } private void endOfLine() { writer.write(LF); for (int i = 0; i < depth; i++) { writer.write(lineIndenter); } } private void writeAttributeValue(PointableWriter writer, String text) { int length = text.length(); for (int i = 0; i < length; i++) { char c = text.charAt(i); switch (c) { case '&': this.writer.write(AMP); break; case '<': this.writer.write(LT); break; case '>': this.writer.write(GT); break; case '"': this.writer.write(QUOT); break; case '\'': this.writer.write(APOS); break; case '\r': this.writer.write(SLASH_R); break; default: this.writer.write(c); } } } private void writeText(PointableWriter writer, String text) { int length = text.length(); for (int i = 0; i < length; i++) { char c = text.charAt(i); switch (c) { case '&': this.writer.write(AMP); break; case '<': this.writer.write(LT); break; case '>': this.writer.write(GT); break; case '"': this.writer.write(QUOT); break; case '\'': this.writer.write(APOS); break; case '\r': this.writer.write(SLASH_R); break; default: this.writer.write(c); } } } }
/** * Format this XML data as a String. * * @webref xml:method * @brief Formats XML data as a String * @param indent -1 for a single line (and no declaration), >= 0 for indents and newlines * @return the content * @see XML#toString() */ public String format(int indent) { try { // entities = doctype.getEntities() boolean useIndentAmount = false; TransformerFactory factory = TransformerFactory.newInstance(); if (indent != -1) { try { factory.setAttribute("indent-number", indent); } catch (IllegalArgumentException e) { useIndentAmount = true; } } Transformer transformer = factory.newTransformer(); // Add the XML declaration at the top if this node is the root and we're // not writing to a single line (indent = -1 means single line). if (indent == -1 || parent == null) { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } else { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); } // transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "sample.dtd"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes"); // huh? // transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, // "-//W3C//DTD XHTML 1.0 Transitional//EN"); // transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, // "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"); // For Android, because (at least 2.3.3) doesn't like indent-number if (useIndentAmount) { transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent)); } // transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); // transformer.setOutputProperty(OutputKeys.ENCODING,"UTF8"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS // Always indent, otherwise the XML declaration will just be jammed // onto the first line with the XML code as well. transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Properties p = transformer.getOutputProperties(); // for (Object key : p.keySet()) { // System.out.println(key + " -> " + p.get(key)); // } // If you smell something, that's because this code stinks. No matter // the settings of the Transformer object, if the XML document already // has whitespace elements, it won't bother re-indenting/re-formatting. // So instead, transform the data once into a single line string. // If indent is -1, then we're done. Otherwise re-run and the settings // of the factory will kick in. If you know a better way to do this, // please contribute. I've wasted too much of my Sunday on it. But at // least the Giants are getting blown out by the Falcons. final String decl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; final String sep = System.getProperty("line.separator"); StringWriter tempWriter = new StringWriter(); StreamResult tempResult = new StreamResult(tempWriter); transformer.transform(new DOMSource(node), tempResult); String[] tempLines = PApplet.split(tempWriter.toString(), sep); // PApplet.println(tempLines); if (tempLines[0].startsWith("<?xml")) { // Remove XML declaration from the top before slamming into one line int declEnd = tempLines[0].indexOf("?>") + 2; // if (tempLines[0].length() == decl.length()) { if (tempLines[0].length() == declEnd) { // If it's all the XML declaration, remove it // PApplet.println("removing first line"); tempLines = PApplet.subset(tempLines, 1); } else { // PApplet.println("removing part of first line"); // If the first node has been moved to this line, be more careful // tempLines[0] = tempLines[0].substring(decl.length()); tempLines[0] = tempLines[0].substring(declEnd); } } String singleLine = PApplet.join(PApplet.trim(tempLines), ""); if (indent == -1) { return singleLine; } // Might just be whitespace, which won't be valid XML for parsing below. // https://github.com/processing/processing/issues/1796 // Since indent is not -1, that means they want valid XML, // so we'll give them the single line plus the decl... Lame? sure. if (singleLine.trim().length() == 0) { // You want whitespace? I've got your whitespace right here. return decl + sep + singleLine; } // Since the indent is not -1, bring back the XML declaration // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); // DOMSource source = new DOMSource(node); Source source = new StreamSource(new StringReader(singleLine)); transformer.transform(source, xmlOutput); String outgoing = stringWriter.toString(); // Add the XML declaration to the top if it's not there already if (outgoing.startsWith(decl)) { int declen = decl.length(); int seplen = sep.length(); if (outgoing.length() > declen + seplen && !outgoing.substring(declen, declen + seplen).equals(sep)) { // make sure there's a line break between the XML decl and the code return outgoing.substring(0, decl.length()) + sep + outgoing.substring(decl.length()); } return outgoing; } else { return decl + sep + outgoing; } } catch (Exception e) { e.printStackTrace(); } 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()); } }
/** @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Model model; String insertstmt; String insertmodel = "", insertspecies = "", insertcompartment = "", insertfunction = "", insertunitdef = "", insertunits = "", insertreaction = "", insertreactant = "", insertproduct = ""; String insertmodifier = "", insertklaw = "", insertrules = "", insertconstraint = "", insertdelay = "", inserttrigger = "", insertevent = "", inserteventassign = "", insertparameter = ""; String insertstatement = ""; String server, user, password, dbname, filepath; String Filedata = ""; String cwd = System.getProperty("user.dir"); if (args.length == 0) { server = "localhost"; user = "******"; password = "******"; dbname = "sbmldb2"; /** * Path to extract the SBML files from database, where cwd is * "github\db2sbml\dbtosbml_standalone_Project\dbtosbml" so add a folder in this directory and * mention folder name instead of extractedbm folder */ filepath = cwd + "\\extractedbm\\"; } else { server = args[0]; user = args[1]; password = args[2]; dbname = args[3]; filepath = args[4]; } try { Filedata = readFileAsString(cwd + "\\sbmldbschema.sql"); } catch (Exception e) { e.printStackTrace(); } Mysqlconn sql = new Mysqlconn(server, user, password, dbname); // String modelids.getId() = "MorrisonAllegra" ; ASTNode math = null; int level = 0, version = 0; ArrayList<modellist> modelidlist = sql.getmodels(); insertstatement = "LOCK TABLES `model` WRITE,`species` WRITE,`compartment` WRITE,`functiondefinition` WRITE,"; insertstatement = insertstatement + "`listofunitdefinitions` WRITE,`listofunits` WRITE,`reaction` WRITE,`simplespeciesreference` WRITE,"; insertstatement = insertstatement + "`modifierspeciesreference` WRITE,`kineticlaw` WRITE,`parameter` WRITE,`sbmlconstraint` WRITE,"; insertstatement = insertstatement + "`event` WRITE,`sbmltrigger` WRITE,`delay` WRITE,`eventassignment` WRITE,`rules` WRITE" + ";"; for (modellist modelids : modelidlist) { ArrayList<modellist> modellevel = sql.getmodeldetails(modelids.getId()); for (modellist modellv : modellevel) { level = modellv.getlevel(); version = modellv.getversion(); } SBMLDocument doc = new SBMLDocument(level, version); ArrayList<modellist> modellists = sql.getmodeldetails(modelids.getId()); if (!modellists.isEmpty()) insertmodel = insertmodel + "\nInsert Into model (id, name,SBML_level,version,notes,annotation) Values"; for (modellist models : modellists) { insertmodel = insertmodel + "(\'" + models.getId() + "\',\'" + models.getName() + "\'," + models.getlevel() + "," + models.getversion() + ",\'" + models.getnotes() + "\',\'" + models.getannotation().toString() + "\'),"; model = doc.createModel(models.getId()); model.setName(models.getName()); // System.out.println("model : " + models.getId()); // model.setNotes(models.getnotes()); // there is some null exception is command line run // but run perfectly from netbeans so ommented out if (!models.getannotation().equals("")) { Annotation annot = new Annotation(models.getannotation().toString()); model.setAnnotation(annot); } doc.setModel(model); } if (!modellists.isEmpty()) { insertmodel = insertmodel.substring(0, insertmodel.length() - 1); insertmodel = insertmodel + ';'; } // insertmodel = insertmodel + "\nUNLOCK TABLES;"; // System.out.println(insertmodel); ArrayList<SpeciesList> specieslist = sql.getspecies(modelids.getId()); if (!specieslist.isEmpty()) insertspecies = insertspecies + "\nInsert Into species (id, name, compartment, initialAmount, initialConcentration,substanceUnits,hasOnlySubstanceUnits,boundaryCondition,constant,conversionFactor,model_id,annotation) Values"; for (SpeciesList species : specieslist) { insertspecies = insertspecies + "(\'" + species.getId() + "\',\'" + species.getName() + "\',\'" + species.getcompartment() + "\'," + species.getia() + "," + species.getic() + ",\'" + species.getsu() + "\'," + species.gethosu() + "," + species.getbc() + "," + species.getconstant() + "," + species.getcf() + ",\'" + modelids.getId() + "\',\'" + species.getannotation() + "\'),"; Species sp = doc.getModel().createSpecies(species.getId()); sp.setName(species.getName()); sp.setCompartment(species.getcompartment()); sp.setConstant(species.getconstant()); sp.setInitialAmount(species.getia()); sp.setInitialConcentration(species.getic()); sp.setHasOnlySubstanceUnits(species.gethosu()); if (doc.getModel().getLevel() == 3) sp.setConversionFactor(species.getcf()); sp.setBoundaryCondition(species.getbc()); sp.setSubstanceUnits(species.getsu()); if (!species.getannotation().equals("")) { Annotation annot = new Annotation(species.getannotation().toString()); sp.setAnnotation(annot); } // doc.getModel().addSpecies(sp) ; } if (!specieslist.isEmpty()) { insertspecies = insertspecies.substring(0, insertspecies.length() - 1); insertspecies = insertspecies + ';'; } ArrayList<CompartmentList> complist = sql.getcompartments(modelids.getId()); if (!complist.isEmpty()) insertcompartment = insertcompartment + "\nInsert Into compartment (id, name,constant,model_id,spacialDimensions,size,units) Values"; for (CompartmentList comp : complist) { insertcompartment = insertcompartment + "(\'" + comp.getId() + "\',\'" + comp.getName() + "\'," + comp.getconstant() + ",\'" + modelids.getId() + "\'," + comp.getspatialdimensions() + "," + comp.getsize() + "," + comp.getunits() + "\'),"; Compartment c = doc.getModel().createCompartment(comp.getId()); c.setName(comp.getName()); c.setConstant(comp.getconstant()); c.setSize(comp.getsize()); c.setSpatialDimensions(comp.getspatialdimensions()); if (comp.getspatialdimensions() != 0) c.setUnits(comp.getunits()); // doc.getModel().addSpecies(sp) ; } if (!complist.isEmpty()) { insertcompartment = insertcompartment.substring(0, insertcompartment.length() - 1); insertcompartment = insertcompartment + ';'; } ArrayList<functionList> funclist = sql.getfunctions(modelids.getId()); if (!funclist.isEmpty()) insertfunction = insertfunction + "\nInsert Into functiondefinition (id, xmlns,model_id) Values"; for (functionList func : funclist) { insertfunction = insertfunction + "(\'" + func.getId() + "\',\'" + func.getxmlns() + "\',\'" + modelids.getId() + "\'),"; FunctionDefinition fd = doc.getModel().createFunctionDefinition(func.getId()); try { math = ASTNode.parseFormula(func.getxmlns()); fd.setMath(math); } catch (Exception e) { e.printStackTrace(); } } if (!funclist.isEmpty()) { insertfunction = insertfunction.substring(0, insertfunction.length() - 1); insertfunction = insertfunction + ';'; } ArrayList<unitList> unitlist = sql.getunitlist(modelids.getId()); if (!unitlist.isEmpty()) insertunitdef = insertunitdef + "\nInsert Into listofunitdefinitions (id,name,model_id) Values"; for (unitList units : unitlist) { insertunitdef = insertunitdef + "(\'" + units.getId() + "\',\'" + units.getName() + "\',\'" + modelids.getId() + "\'),"; UnitDefinition ud = doc.getModel().createUnitDefinition(units.getId()); ud.setName(units.getName()); ArrayList<unitList> unitdeflist = sql.getunitdef(units.getId()); if (!unitdeflist.isEmpty()) insertunits = insertunits + "\nInsert Into listofunits (listofunitdefinitions_id,kind, scale,exponent,multiplier) Values"; for (unitList unitdef : unitdeflist) { insertunits = insertunits + "(\'" + units.getId() + "\',\'" + unitdef.getkind() + "\'," + unitdef.getscale() + "," + unitdef.getexponent() + "," + unitdef.getmultiplier() + "),"; Unit u = ud.createUnit(Unit.Kind.valueOf(unitdef.getkind())); u.setScale(unitdef.getscale()); u.setExponent(unitdef.getexponent()); u.setMultiplier(unitdef.getmultiplier()); } // doc.getModel().addSpecies(sp) ; if (!unitdeflist.isEmpty()) { insertunits = insertunits.substring(0, insertunits.length() - 1); insertunits = insertunits + ';'; } } if (!unitlist.isEmpty()) { insertunitdef = insertunitdef.substring(0, insertunitdef.length() - 1); insertunitdef = insertunitdef + ';'; } ArrayList<reactionList> reactionlist = sql.getreactons(modelids.getId()); if (!reactionlist.isEmpty()) insertreaction = insertreaction + "\nInsert Into reaction (id,name, reversible,fast,model_id,compartment,annotation) Values"; for (reactionList reaction : reactionlist) { insertreaction = insertreaction + "(\'" + reaction.getId() + "\',\'" + reaction.getName() + "\'," + reaction.getreversible() + "," + reaction.getfast() + ",\'" + modelids.getId() + "\',\'" + reaction.getcompartment() + "\',\'" + reaction.getannotation() + "\'),"; Reaction rn = doc.getModel().createReaction(reaction.getId()); rn.setName(reaction.getName()); if (doc.getModel().getLevel() == 3) rn.setCompartment(reaction.getcompartment()); rn.setFast(reaction.getfast()); rn.setReversible(reaction.getreversible()); if (!reaction.getannotation().equals("")) { Annotation annot = new Annotation(reaction.getannotation().toString()); rn.setAnnotation(annot); } ArrayList<reactionList> reactantlist = sql.getreactants(reaction.getId()); if (!reactantlist.isEmpty()) insertreactant = insertreactant + "\nInsert Into simplespeciesreference (reaction_id,species, sboTerm,stoichiometry,speciestype,constant) Values"; for (reactionList reactant : reactantlist) { insertreactant = insertreactant + "(\'" + reaction.getId() + "\',\'" + reactant.getspecies() + "\',\'" + reactant.getsboTerm() + "\'," + reactant.getstoichometry() + "," + reactant.getconstant() + ",\'reactants\'),"; SpeciesReference rt = new SpeciesReference(); rt.setName(reactant.getspecies()); rt.setSpecies(reactant.getspecies()); // rt.setSBOTerm(reactant.getsboTerm()); rt.setStoichiometry(reactant.getstoichometry()); // rt.setConstant(reactant.getconstant()); rn.addReactant(rt); } if (!reactantlist.isEmpty()) { insertreactant = insertreactant.substring(0, insertreactant.length() - 1); insertreactant = insertreactant + ';'; } ArrayList<reactionList> productlist = sql.getproducts(reaction.getId()); if (!productlist.isEmpty()) insertproduct = insertproduct + "\nInsert Into simplespeciesreference (reaction_id,species, sboTerm,stoichiometry,constant,speciestype) Values"; for (reactionList product : productlist) { insertproduct = insertproduct + "(\'" + reaction.getId() + "\',\'" + product.getspecies() + "\',\'" + product.getsboTerm() + "\'," + product.getstoichometry() + "," + product.getconstant() + ",\'products\'),"; SpeciesReference pr = new SpeciesReference(); pr.setName(product.getspecies()); pr.setSpecies(product.getspecies()); // pr.setSBOTerm(product.getsboTerm()); pr.setStoichiometry(product.getstoichometry()); // pr.setConstant(product.getconstant()); rn.addProduct(pr); } if (!productlist.isEmpty()) { insertproduct = insertproduct.substring(0, insertproduct.length() - 1); insertproduct = insertproduct + ';'; } ArrayList<reactionList> modifierlist = sql.getmodifiers(reaction.getId()); if (!modifierlist.isEmpty()) insertmodifier = insertmodifier + "\nInsert Into modifierspeciesreference (reaction_id,species, sboTerm,speciestype) Values"; for (reactionList modifier : modifierlist) { insertmodifier = insertmodifier + "(\'" + reaction.getId() + "\',\'" + modifier.getspecies() + "\',\'" + modifier.getsboTerm() + "\',\'modifiers\'),"; ModifierSpeciesReference m = new ModifierSpeciesReference(); m.setName(modifier.getspecies()); m.setSpecies(modifier.getspecies()); // m.setSBOTerm(modifier.getsboTerm()); rn.addModifier(m); } if (!modifierlist.isEmpty()) { insertmodifier = insertmodifier.substring(0, insertmodifier.length() - 1); insertmodifier = insertmodifier + ';'; } ArrayList<reactionList> klawlist = sql.getkineticlaws(reaction.getId()); if (!klawlist.isEmpty()) insertklaw = insertklaw + "\nInsert Into kineticlaw (reaction_id,kid, math,annotation) Values"; for (reactionList klaw : klawlist) { insertklaw = insertklaw + "(\'" + reaction.getId() + "\',\'" + klaw.getId() + "\',\'" + klaw.getmath() + "\',\'" + klaw.getannotation() + "\'),"; KineticLaw kl = rn.createKineticLaw(); try { math = ASTNode.parseFormula(klaw.getmath()); kl.setMath(math); if (!klaw.getannotation().equals("")) { Annotation annot = new Annotation(klaw.getannotation().toString()); kl.setAnnotation(annot); } } catch (Exception e) { e.printStackTrace(); } } if (!klawlist.isEmpty()) { insertklaw = insertklaw.substring(0, insertklaw.length() - 1); insertklaw = insertklaw + ';'; } } if (!reactionlist.isEmpty()) { insertreaction = insertreaction.substring(0, insertreaction.length() - 1); insertreaction = insertreaction + ';'; } ArrayList<parameterList> paralist = sql.getparameters(modelids.getId()); if (!paralist.isEmpty()) insertparameter = insertparameter + "\nInsert Into parameter (id,name,value,units,constant,model_id) Values"; for (parameterList para : paralist) { insertparameter = insertparameter + "(\'" + para.getId() + "\',\'" + para.getName() + "\'," + para.getvalue() + "," + para.getunits() + "," + para.getconstant() + ",\'" + modelids.getId() + "\'),"; Parameter par = doc.getModel().createParameter(para.getId()); par.setName(para.getId()); par.setConstant(para.getconstant()); par.setUnits(para.getunits()); par.setValue(para.getvalue()); } if (!paralist.isEmpty()) { insertparameter = insertparameter.substring(0, insertparameter.length() - 1); insertparameter = insertparameter + ';'; } ArrayList<constraintList> conslist = sql.getconstraints(modelids.getId()); if (!conslist.isEmpty()) insertconstraint = insertconstraint + "\nInsert Into sbmlconstraint (math,message,model_id) Values"; for (constraintList constraint : conslist) { insertconstraint = insertconstraint + "(\'" + constraint.getmath() + "\',\'" + constraint.getmessage() + "\',\'" + modelids.getId() + "\'),"; Constraint cons = doc.getModel().createConstraint(); try { math = ASTNode.parseFormula(constraint.getmath()); cons.setMath(math); cons.setMessage(constraint.getmessage()); } catch (Exception e) { e.printStackTrace(); } } if (!conslist.isEmpty()) { insertconstraint = insertconstraint.substring(0, insertconstraint.length() - 1); insertconstraint = insertconstraint + ';'; } ArrayList<eventsList> eventlist = sql.getevents(modelids.getId()); if (!eventlist.isEmpty()) insertevent = insertevent + "\nInsert Into event (id,name,UseValuesFromTriggerTime,model_id) Values"; for (eventsList events : eventlist) { insertevent = insertevent + "(\'" + events.getId() + "\',\'" + events.getName() + "\'," + events.getuservalues() + ",\'" + modelids.getId() + "\'),"; Event ev = doc.getModel().createEvent(events.getId()); ev.setName(events.getName()); // ev.setUseValuesFromTriggerTime(events.getuservalues()); ArrayList<eventsList> triggerlist = sql.gettriggers(events.getId()); if (!triggerlist.isEmpty()) inserttrigger = inserttrigger + "\nInsert Into sbmltrigger (event_id,initialvalue,persisent,math) Values"; for (eventsList triggers : triggerlist) { Trigger tr = doc.getModel().createTrigger(); try { math = ASTNode.parseFormula(triggers.getmath()); tr.setMath(math); tr.setInitialValue(triggers.getinitialval()); tr.setPersistent(triggers.getpersistent()); } catch (Exception e) { e.printStackTrace(); } } if (!triggerlist.isEmpty()) { inserttrigger = inserttrigger.substring(0, insertmodel.length() - 1); inserttrigger = inserttrigger + ';'; } ArrayList<eventsList> delaylist = sql.getdelays(events.getId()); if (!delaylist.isEmpty()) insertdelay = insertdelay + "\nInsert Into delay (event_id,math) Values"; for (eventsList delays : delaylist) { Delay d = doc.getModel().createDelay(); try { math = ASTNode.parseFormula(delays.getmath()); d.setMath(math); } catch (Exception e) { e.printStackTrace(); } } if (!delaylist.isEmpty()) { insertdelay = insertdelay.substring(0, insertdelay.length() - 1); insertdelay = insertdelay + ';'; } ArrayList<eventsList> evasslist = sql.geteventassignments(events.getId()); if (!evasslist.isEmpty()) inserteventassign = inserteventassign + "\nInsert Into eventassignment (event_id,variable,math) Values"; for (eventsList evassign : evasslist) { EventAssignment ea = doc.getModel().createEventAssignment(); try { math = ASTNode.parseFormula(evassign.getmath()); ea.setMath(math); } catch (Exception e) { e.printStackTrace(); } } if (!evasslist.isEmpty()) { inserteventassign = inserteventassign.substring(0, inserteventassign.length() - 1); inserteventassign = inserteventassign + ';'; } } if (!eventlist.isEmpty()) { insertevent = insertevent.substring(0, insertevent.length() - 1); insertevent = insertevent + ';'; } ArrayList<ruleslist> rulelist = sql.getrules(modelids.getId()); if (!rulelist.isEmpty()) insertrules = insertrules + "\nInsert Into rules (id,math,ruletype,model_id) Values"; for (ruleslist rules : rulelist) { insertrules = insertrules + "(\'" + rules.getId() + "\',\'" + rules.getmath() + "\',\'" + rules.getruletype() + "\',\'" + modelids.getId() + "\'),"; if (rules.getruletype().equals("assignmentrule")) { Rule r = doc.getModel().createAssignmentRule(); r.setMetaId(rules.getId()); try { math = ASTNode.parseFormula(rules.getmath()); r.setMath(math); } catch (Exception e) { e.printStackTrace(); } } } if (!rulelist.isEmpty()) { insertrules = insertrules.substring(0, insertrules.length() - 1); insertrules = insertrules + ';'; } SBMLWriter writer = new SBMLWriter(); try { String Path = filepath + modelids.getId() + ".xml"; writer.write(doc, Path); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(Path); Element root = document.getDocumentElement(); Element newdataset = document.createElement("dataset"); root.appendChild(newdataset); ArrayList<dataset> datasetlist = sql.getdataset(modelids.getId()); for (dataset ds : datasetlist) { // System.out.println(ds.getexpcond()); Element name = document.createElement("experimentalcondition"); name.setAttribute("bioelement", ds.getbioel()); name.setAttribute("name", ds.getName()); name.setAttribute("descr", ds.getdescr()); name.setAttribute("expcond", ds.getexpcond()); name.setAttribute("value", String.valueOf(ds.getvalue())); name.setAttribute("type", ds.gettype()); name.setAttribute("uri", ds.geturi()); newdataset.appendChild(name); } root.appendChild(newdataset); DOMSource source = new DOMSource(document); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); StreamResult result = new StreamResult(filepath + modelids.getId() + "d.xml"); transformer.transform(source, result); System.out.println( "Files : " + modelids.getId() + ".xml and " + modelids.getId() + "d.xml have been generated successfully !!!"); } catch (Exception e) { e.printStackTrace(); } insertstatement = insertstatement + "\n\n" + insertmodel + "\n" + insertspecies + "\n" + insertcompartment + "\n" + insertfunction; insertstatement = insertstatement + "\n" + insertparameter + "\n" + insertreaction + "\n" + insertreactant + "\n" + insertproduct; insertstatement = insertstatement + "\n" + insertmodifier + "\n" + insertklaw + "\n" + insertunitdef + "\n" + insertunits; insertstatement = insertstatement + "\n" + insertrules + "\n" + insertconstraint + "\n" + insertevent + "\n" + inserttrigger + "\n" + insertdelay + "\n" + inserteventassign; insertcompartment = ""; insertmodel = ""; insertspecies = ""; // System.out.println("document : " + doc); } insertstatement = insertstatement + "\nUNLOCK TABLES;"; Filedata = Filedata + "\n\n\n" + insertstatement; try { wrtireStringToFile(Filedata, filepath + "sbmldb.sql"); } catch (IOException e) { e.printStackTrace(); } // System.out.println(insertstatement); }
// ## 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; } // #] }