private static void validateXMLWithURL(File nmlFile, String schemaUrl) { try { Source schemaFileSource = new StreamSource(schemaUrl); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(schemaFileSource); Validator validator = schema.newValidator(); Source xmlFileSource = new StreamSource(nmlFile); validator.validate(xmlFileSource); System.out.println( "**** File: " + nmlFile + " is VALID according to " + schemaUrl + "!!! ****"); } catch (Exception ex) { System.err.println( "Problem validating xml file: " + nmlFile.getAbsolutePath() + " according to " + schemaUrl + "!!!"); ex.printStackTrace(); System.exit(1); } }
public ArrayList<String> collectLinks(String p) { ArrayList<String> PageLinks = new ArrayList<String>(); try { URL url = new URL(p); BufferedReader br3 = new BufferedReader(new InputStreamReader(url.openStream())); String str = ""; while (null != (str = br3.readLine())) { Pattern link = Pattern.compile( "<a target=\"_top\" href=\"/m/.*", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher match = link.matcher(str); while (match.find()) { String tmp = match.group(); int start = tmp.indexOf('/'); tmp = tmp.substring(start + 1, tmp.indexOf('\"', start + 1)); if (Crawl.contains("http://www.rottentomatoes.com/" + tmp) || ToCrawl.contains("http://www.rottentomatoes.com/" + tmp) || PageLinks.contains("http://www.rottentomatoes.com/" + tmp)) continue; PageLinks.add("http://www.rottentomatoes.com/" + tmp); // bw4.write("http://www.rottentomatoes.com/"+tmp+"\r\n"); } } br3.close(); } catch (Exception ex) { ex.printStackTrace(); } return PageLinks; }
private void deflate(String tmpDir, String path) { String tmpFile = "tmp-" + Utils.timestamp() + ".zip"; try { ZipFile zipFile = new ZipFile(tmpFile); ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); parameters.setIncludeRootFolder(false); zipFile.addFolder(tmpDir, parameters); } catch (Exception e) { e.printStackTrace(); return; } File from = null; File to = null; try { File target = new File(path); if (target.exists()) FileUtils.forceDelete(target); from = new File(tmpFile); to = new File(path); FileUtils.moveFile(from, to); } catch (IOException e) { Utils.onError(new Error.FileMove(tmpFile, path)); } try { FileUtils.deleteDirectory(new File(tmpDir)); } catch (IOException e) { Utils.log("can't delete temporary folder"); } }
private String inflate(String path) { if (!new File(path).canRead()) { Utils.onError(new Error.FileRead(path)); return null; } String tmpDir = "tmp-" + Utils.timestamp(); try { ZipFile zipFile = new ZipFile(path); zipFile.extractAll(tmpDir); } catch (Exception e) { e.printStackTrace(); return null; } return tmpDir; }
/** * Removes empty #text nodes from a document. From James Murty on this StackOverflow post: * http://stackoverflow.com/questions/978810/how-to-strip-whitespace-only-text-nodes-from-a-dom-before-serialization * * @param doc The document to remove empty text nodes from. */ private static void removeEmptyTextNodes(Document doc) { try { XPathFactory xpathFactory = XPathFactory.newInstance(); // XPath to find empty text nodes. XPathExpression xpathExp = xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']"); NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET); // Remove each empty text node from document. for (int i = 0; i < emptyTextNodes.getLength(); i++) { Node emptyTextNode = emptyTextNodes.item(i); emptyTextNode.getParentNode().removeChild(emptyTextNode); } } catch (Exception ex) { ex.printStackTrace(); } }
/** * Gets the string of an XML document containing multiple words for saving purposes. * * @param words The words to save. * @return String containing XML containing all words. */ public static String getMultipleWordXML(Word[] words) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); Element root = doc.createElement("Root"); for (int i = 0; i < words.length; i++) { root.appendChild(words[i].getWordXMLNode(doc)); } doc.appendChild(root); return getStringFromDocument(doc); } catch (Exception ex) { ex.printStackTrace(); return null; } }
/** * Gets the definitions of a word, sets the main one if necessary, and returns it. * * @param overwrite if true, then function will attempt to retrieve from online even if the * definition is already set. * @return String containing the main definition of the word. */ public static Word[] getWordsFromFile(ByteArrayInputStream inputStream) { try { // now to parse the XML DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(inputStream); removeEmptyTextNodes(doc); NodeList wordList = doc.getElementsByTagName("WordDefinitions"); int wordCount = wordList.getLength(); Word[] returnWords = new Word[wordCount]; for (int wordi = 0; wordi < wordCount; wordi++) { NodeList list = ((Element) wordList.item(wordi)).getElementsByTagName("Definition"); Element wordElement = (Element) wordList.item(wordi); String word = wordElement.getAttribute("word"); String mainDefinition = wordElement.getAttribute("mainDefinition"); int numDefinitions = list.getLength(); Definition[] wordOtherDefinitions = new Definition[numDefinitions]; for (int i = 0; i < numDefinitions; i++) { Node node = list.item(i); NodeList children = node.getChildNodes(); // gets each child node of the definition // get all data String definition = children.item(XML_DEFINITION_LOC).getTextContent(); String theWord = children.item(XML_WORD_LOC).getTextContent(); NodeList dictionaryNode = children.item(XML_DICTIONARY_BRANCH_LOC).getChildNodes(); String dictionaryId = dictionaryNode.item(XML_DICTIONARY_ID_LOC).getTextContent(); String dictionaryName = dictionaryNode.item(XML_DICTIONARY_NAME_LOC).getTextContent(); // now we've got all the data lets add it to the array wordOtherDefinitions[i] = new Definition(dictionaryName, dictionaryId, definition, theWord); } if (wordOtherDefinitions.length == 0) { wordOtherDefinitions = new Definition[] {new Definition("nil", "nil", "NO DEFINITION FOUND", word)}; } Word currentWord = new Word(word, mainDefinition); currentWord.setOtherDefinitions(wordOtherDefinitions); returnWords[wordi] = currentWord; } return returnWords; } catch (Exception ex) { ex.printStackTrace(); return null; } }
/** used for cut and paste. */ public void addObjectFromClipboard(String a_value) throws CircularIncludeException { Reader reader = new StringReader(a_value); Document document = null; try { document = UJAXP.getDocument(reader); } catch (Exception e) { e.printStackTrace(); return; } // try-catch Element root = document.getDocumentElement(); if (!root.getNodeName().equals("clipboard")) { return; } // if Node child; for (child = root.getFirstChild(); child != null; child = child.getNextSibling()) { if (!(child instanceof Element)) { continue; } // if Element element = (Element) child; IGlyphFactory factory = GlyphFactory.getFactory(); if (XModule.isMatch(element)) { EModuleInvoke module = (EModuleInvoke) factory.createXModule(element); addModule(module); continue; } // if if (XContour.isMatch(element)) { EContour contour = (EContour) factory.createXContour(element); addContour(contour); continue; } // if if (XInclude.isMatch(element)) { EIncludeInvoke include = (EIncludeInvoke) factory.createXInclude(element); addInclude(include); continue; } // if } // while }
public static String errorMessage(Exception exception) { String message = ""; try { String addErrorMessage = getErrorStackString(exception.getStackTrace()); message = exception.toString(); return "<errortext>" + message + "</errortext>".replaceAll("\"", "'") + "<stack>" + addErrorMessage.replaceAll(">", "-").replaceAll("<", "-") + "</stack>\n\r"; } catch (Exception e) { System.out.println(e); e.printStackTrace(); return ""; } }
/** * Gets XML string for this definition so that it may be printed. * * @return XML node that can be saved of this word. */ public Element getWordXMLNode(Document doc) { try { Element rootWordElement = doc.createElement("WordDefinitions"); rootWordElement.setAttribute("word", this.word); rootWordElement.setAttribute("mainDefinition", this.getMainDefinition()); if (this.otherDefinitions == null) { this.getDefinitions(); } for (int i = 0; i < this.otherDefinitions.length; i++) { // main definition node Element definition = doc.createElement("Definition"); // word Element word = doc.createElement("Word"); word.setTextContent(otherDefinitions[i].getWord()); // dictionary Element dictionary = doc.createElement("Dictionary"); Element id = doc.createElement("Id"); id.setTextContent(otherDefinitions[i].getId()); Element source = doc.createElement("Name"); source.setTextContent(otherDefinitions[i].getSource()); dictionary.appendChild(id); dictionary.appendChild(source); // definition Element wordDefinition = doc.createElement("WordDefinition"); wordDefinition.setTextContent(otherDefinitions[i].getDefinition()); // append all the children definition.appendChild(word); definition.appendChild(dictionary); definition.appendChild(wordDefinition); rootWordElement.appendChild(definition); } return rootWordElement; } catch (Exception ex) { ex.printStackTrace(); return null; } }
/** * Gets a ByteArrayInputStream to parse a word from the definition API. * * @return ByteArrayInputStream containing definition XML, null if trouble parsing or getting the * definition. */ public ByteArrayInputStream getStreamFromOnlineXML() { try { // download the xml definition page of the word String urlSafeWord = URLEncoder.encode(this.word, "UTF-8"); InputStream response = new URL(SERVICE_URL + urlSafeWord).openStream(); Scanner responseReader = new Scanner(response).useDelimiter("\\A"); if (responseReader.hasNext()) { // gets a clean version of xml the document can parse String xml = responseReader.next(); response.close(); xml = xml.trim().replaceFirst("^([\\W]+)<", "<"); ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes("utf-8")); return stream; } else { return null; } } catch (Exception ex) { ex.printStackTrace(); return null; } }
/** * Gets the definitions of a word, sets the main one if necessary, and returns it. * * @param overwrite if true, then function will attempt to retrieve from online even if the * definition is already set. * @return String containing the main definition of the word. */ public String getDefinitions(ByteArrayInputStream inputStream, boolean overwrite) { if (overwrite || (definition == null || definition.isEmpty())) { // get definition from online service // if not able to access internet, then do something try { // now to parse the XML DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(inputStream); removeEmptyTextNodes(doc); NodeList list = doc.getElementsByTagName("Definition"); int numDefinitions = list.getLength(); otherDefinitions = new Definition[numDefinitions]; for (int i = 0; i < numDefinitions; i++) { Node node = list.item(i); NodeList children = node.getChildNodes(); // gets each child node of the definition // get all data String definition = children.item(XML_DEFINITION_LOC).getTextContent(); String word = children.item(XML_WORD_LOC).getTextContent(); NodeList dictionaryNode = children.item(XML_DICTIONARY_BRANCH_LOC).getChildNodes(); String dictionaryId = dictionaryNode.item(XML_DICTIONARY_ID_LOC).getTextContent(); String dictionaryName = dictionaryNode.item(XML_DICTIONARY_NAME_LOC).getTextContent(); // now we've got all the data lets add it to the array otherDefinitions[i] = new Definition(dictionaryName, dictionaryId, definition, word); } if (otherDefinitions.length == 0) { otherDefinitions = new Definition[] {new Definition("nil", "nil", "NO DEFINITION FOUND", word)}; } this.setMainDefinition(otherDefinitions[0].getDefinition()); return otherDefinitions[0].getDefinition(); } catch (Exception ex) { ex.printStackTrace(); return "ERROR! " + ex; } } else { return this.definition; } }
public StartProcess() { super(); Hashtable jndiProps = new Hashtable(); jndiProps.put(Context.PROVIDER_URL, "t3://soaps3.alfa.local:8001/soa-infra"); jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); jndiProps.put(Context.SECURITY_PRINCIPAL, "weblogic"); jndiProps.put(Context.SECURITY_CREDENTIALS, "weblogic1"); jndiProps.put("dedicated.connection", "true"); String inputPayload = "<process xmlns=\"http://xmlns.oracle.com/HelloWorld/Helloworld/BPELProcess1\">" + " <input>hello</input>" + "</process>"; Locator locator = null; try { // connect to the soa server locator = LocatorFactory.createLocator(jndiProps); String compositeDN = "default/Helloworld!1.0"; // find composite Composite composite = locator.lookupComposite("default/Helloworld!1.0"); System.out.println("Got Composite : " + composite.toString()); // find exposed service of the composite Service service = composite.getService("ADFBindingService"); System.out.println("Got serviceName : " + service.toString()); // make the input request and add this to a operation of the service NormalizedMessage input = new NormalizedMessageImpl(); String uuid = "uuid:" + UUID.randomUUID(); input.addProperty(NormalizedMessage.PROPERTY_CONVERSATION_ID, uuid); // payload is the partname of the process operation input.getPayload().put("payload", inputPayload); // process is the operation of the employee service NormalizedMessage res = null; try { res = service.request("process", input); } catch (Exception e) { e.printStackTrace(); } Map payload = res.getPayload(); Element element = (Element) payload.get("payload"); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty("indent", "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(element); transformer.transform(source, result); System.out.println("Result\n" + sw.toString()); System.out.println("instances"); CompositeInstanceFilter filter = new CompositeInstanceFilter(); filter.setMinCreationDate(new java.util.Date((System.currentTimeMillis() - 2000000))); // get composite instances by filter .. List<CompositeInstance> obInstances = composite.getInstances(filter); // for each of the returned composite instances.. for (CompositeInstance instance : obInstances) { System.out.println( " DN: " + instance.getCompositeDN() + " Instance: " + instance.getId() + " creation-date: " + instance.getCreationDate() + " state (" + instance.getState() + "): " + getStateAsString(instance.getState())); // setup a component filter ComponentInstanceFilter cInstanceFilter = new ComponentInstanceFilter(); // get child component instances .. List<ComponentInstance> childComponentInstances = instance.getChildComponentInstances(cInstanceFilter); // for each child component instance (e.g. a bpel process) for (ComponentInstance cInstance : childComponentInstances) { System.out.println( " -> componentinstance: " + cInstance.getComponentName() + " type: " + cInstance.getServiceEngine().getEngineType() + " state: " + getStateAsString(cInstance.getState())); System.out.println("State: " + cInstance.getNormalizedStateAsString()); } } } catch (Exception e) { e.printStackTrace(); } }
public static void main(String args[]) { try { SeleniumHtmlClient client = new SeleniumHtmlClient(); String testFile = null; String testSuite = null; String resultsFilename = null; for (int i = 0; i < args.length; i++) { if (args[i].equals("--host")) { i++; if (i < args.length) { client.setHost(args[i]); } else { throw new BadUsageException("--host must be followed by a hostname"); } } else if (args[i].equals("--port")) { i++; if (i < args.length) { client.setPort(Integer.parseInt(args[i])); } else { throw new BadUsageException("--port must be followed by a port number"); } } else if (args[i].equals("--browser")) { i++; if (i < args.length) { client.setBrowser(args[i]); } else { throw new BadUsageException("--browser must be followed by a browser spec"); } } else if (args[i].equals("--out")) { i++; if (i < args.length) { resultsFilename = args[i]; } else { throw new BadUsageException("--out must be followed by a filename"); } /* } else if (args[i].equals("--outdir")) { i++; if (i < args.length) { client.setResultsDir(new File(args[i])); } else { throw new BadUsageException("--outdir must be followed by a path"); } */ } else if (args[i].equals("--baseurl")) { i++; if (i < args.length) { client.setBaseUrl(args[i]); } else { throw new BadUsageException("--baseurl must be followed by a URL"); } } else if (args[i].equals("--test")) { i++; if (i < args.length) { if (testFile == null) { testFile = args[i]; } else { throw new BadUsageException("only one test file permitted"); } } else { throw new BadUsageException("--test must be followed by a test filepath"); } } else if (args[i].equals("--testsuite")) { i++; if (i < args.length) { testSuite = args[i]; } else { throw new BadUsageException("--testsuite must be followed by a testsuite filepath"); } } else if (args[i].equals("--verbose") || args[i].equals("-v")) { client.setVerbose(true); } else if (args[i].equals("--help") || args[i].equals("-h")) { printUsage(); System.exit(0); } else { throw new BadUsageException("Unknown parameter " + args[i]); } } if (testFile == null && testSuite == null) { throw new BadUsageException("No test or testsuite file specified"); } else if (testFile != null && testSuite != null) { throw new BadUsageException("A test and testsuite file cannot both be specified"); } Writer resultsWriter = null; if (resultsFilename != null) { resultsWriter = new FileWriter(resultsFilename); } else /* if (client.resultsDir == null) */ { resultsWriter = new OutputStreamWriter(System.out); } client.setResultsWriter(resultsWriter); if (testFile != null) { client.runTest(testFile); } else { client.runSuite(testSuite); } if (resultsWriter != null) resultsWriter.close(); } catch (BadUsageException e) { System.err.println("Error: " + e.getMessage()); System.err.println(); printUsage(); System.exit(1); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
private void importItemActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_importItemActionPerformed // Display a file chooser File selectedFile; Model m = null; JFileChooser jfc = new JFileChooser(workingDirectory); jfc.setFileFilter( new FileFilter() { public boolean accept(File f) { return f.isDirectory() || f.getName().endsWith(".xmi"); } public String getDescription() { return "XMI UML files (*.xmi)"; } }); jfc.setCurrentDirectory(workingDirectory); jfc.showDialog(this, "Import"); selectedFile = jfc.getSelectedFile(); if (selectedFile != null) { try { m = importModel(selectedFile); if (m != null) { models.add(m); JOptionPane.showMessageDialog( this, "Model loaded successfully.", "Success!", JOptionPane.INFORMATION_MESSAGE); workingDirectory = jfc.getSelectedFile().getParentFile(); getContentPane().remove(MTP); MTP = new ModelTreePanel(m); getContentPane().add(MTP, BorderLayout.CENTER); try { ObjectOutputStream Out = new ObjectOutputStream( new FileOutputStream(System.getProperty("user.home") + "/" + "WorkSpace.dat")); Out.writeObject(new WorkSpace(workingDirectory.getAbsolutePath())); Out.close(); } catch (Exception ex) { ex.printStackTrace(); } } } catch (FileNotFoundException fnfe) { JOptionPane.showMessageDialog( this, "Could not open the model file: " + fnfe.getMessage(), "File not found", JOptionPane.ERROR_MESSAGE); } catch (ParseException pe) { JOptionPane.showMessageDialog( this, "There was an error in parsing the given model: " + pe.getMessage(), "Parse error", JOptionPane.ERROR_MESSAGE); } catch (LemException le) { JOptionPane.showMessageDialog( this, "There was an error in parsing the given model: " + le.getMessage(), "Parse error", JOptionPane.ERROR_MESSAGE); } catch (IOException ioe) { JOptionPane.showMessageDialog( this, "An input/output error occured while trying to read the model: " + ioe.getMessage(), "Read error", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { e.printStackTrace(); } } setVisible(true); } // GEN-LAST:event_importItemActionPerformed
public void run() { // String a = // "http://neuromorpho.org/neuroMorpho/dableFiles/borst/CNG%20version/dCH-cobalt.CNG.swc"; // // For developer use if (myArgs.length == 0) { String usage = "\nError, missing SWC file containing morphology!\n\nUsage: \n java -cp build cvapp.main swc_file [-test]" + "\n or:\n ./run.sh swc_file [" + TEST_FLAG + "|" + TEST_NOGUI_FLAG + "|" + NEUROML1_EXPORT_FLAG + "|" + NEUROML2_EXPORT_FLAG + "]\n\n" + "where swc_file is the file name or URL of the SWC morphology file\n"; System.out.println(usage); System.exit(0); } String a = myArgs[0]; File baseDir = new File("."); if ((new File(a)).exists()) { baseDir = (new File(a)).getParentFile(); } try { File root = new File(main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()) .getParentFile(); if (!a.startsWith("http://") && !a.startsWith("file://")) { a = "file://" + (new File(a)).getCanonicalPath(); } boolean supressGui = false; if (myArgs.length == 2 && (myArgs[1].equals(TEST_NOGUI_FLAG) || myArgs[1].equals(NEUROML1_EXPORT_FLAG) || myArgs[1].equals(NEUROML2_EXPORT_FLAG))) { supressGui = true; } neuronEditorFrame nef = null; nef = new neuronEditorFrame(700, 600, supressGui); // nef.validate(); nef.pack(); centerWindow(nef); nef.setVisible(!supressGui); nef.setReadWrite(true, true); int indexof = a.lastIndexOf('/') + 1; String directory = a.substring(0, indexof); String fileName = a.substring(indexof, a.length()); URL u = new URL(a); String sdata[] = readStringArrayFromURL(u); nef.setTitle("3DViewer (Modified from CVAPP with permission)-Neuron: " + fileName); nef.loadFile(sdata, directory, fileName); System.out.println("Loaded: " + fileName); if (myArgs.length == 2 && myArgs[1].equals(TEST_ONE_FLAG)) { // Thread.sleep(1000); doTests(nef, fileName); } else if (myArgs.length == 2 && myArgs[1].equals(NEUROML1_EXPORT_FLAG)) { File rootFile = (new File(baseDir, fileName)).getAbsoluteFile(); String nml1FileName = rootFile.getName().endsWith(".swc") ? rootFile.getName().substring(0, rootFile.getName().length() - 4) + ".xml" : rootFile.getName() + ".xml"; File nml1File = new File(rootFile.getParentFile(), nml1FileName); neuronEditorPanel nep = nef.getNeuronEditorPanel(); nep.writeStringToFile(nep.getCell().writeNeuroML_v1_8_1(), nml1File.getAbsolutePath()); System.out.println( "Saved NeuroML representation of the file to: " + nml1File.getAbsolutePath() + ": " + nml1File.exists()); File v1schemaFile = new File(root, "Schemas/v1.8.1/Level3/NeuroML_Level3_v1.8.1.xsd"); validateXML(nml1File, v1schemaFile); System.exit(0); } else if (myArgs.length == 2 && myArgs[1].equals(NEUROML2_EXPORT_FLAG)) { File rootFile = (new File(baseDir, fileName)).getAbsoluteFile(); String nml2FileName = rootFile.getName().endsWith(".swc") ? rootFile.getName().substring(0, rootFile.getName().length() - 4) + ".cell.nml" : rootFile.getName() + ".cell.nml"; if (Character.isDigit(nml2FileName.charAt(0))) { nml2FileName = "Cell_" + nml2FileName; } File nml2File = new File(rootFile.getParentFile(), nml2FileName); neuronEditorPanel nep = nef.getNeuronEditorPanel(); nep.writeStringToFile(nep.getCell().writeNeuroML_v2beta(), nml2File.getAbsolutePath()); System.out.println( "Saved the NeuroML representation of the file to: " + nml2File.getAbsolutePath() + ": " + nml2File.exists()); validateXML(nml2File, new File(root, "Schemas/v2/NeuroML_v2beta4.xsd")); System.exit(0); } else if (myArgs.length == 2 && (myArgs[1].equals(TEST_FLAG) || (myArgs[1].equals(TEST_NOGUI_FLAG)))) { // Thread.sleep(1000); doTests(nef, fileName); File exampleDir = new File("twoCylSwc"); for (File f : exampleDir.listFiles()) { if (f.getName().endsWith(".swc")) { sdata = fileString.readStringArrayFromFile(f.getAbsolutePath()); nef.setTitle("3DViewer (Modified from CVAPP with permission)-Neuron: " + f.getName()); nef.loadFile(sdata, f.getParent(), f.getName()); doTests(nef, f.getAbsolutePath()); } } exampleDir = new File("spherSomaSwc"); for (File f : exampleDir.listFiles()) { if (f.getName().endsWith(".swc")) { sdata = fileString.readStringArrayFromFile(f.getAbsolutePath()); nef.setTitle("3DViewer (Modified from CVAPP with permission)-Neuron: " + f.getName()); nef.loadFile(sdata, f.getParent(), f.getName()); doTests(nef, f.getAbsolutePath()); } } exampleDir = new File("caseExamples"); for (File f : exampleDir.listFiles()) { if (f.getName().endsWith(".swc")) { sdata = fileString.readStringArrayFromFile(f.getAbsolutePath()); nef.setTitle("3DViewer (Modified from CVAPP with permission)-Neuron: " + f.getName()); nef.loadFile(sdata, f.getParent(), f.getName()); doTests(nef, f.getAbsolutePath()); } } if (supressGui) System.exit(0); } } catch (Exception exception) { System.err.println("Error while handling SWC file (" + a + ")"); exception.printStackTrace(); } }
/** * 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 boolean runTest(Test test) throws Exception { String filename = test.file.toString(); if (this.verbose) { System.out.println( "Running " + filename + " against " + this.host + ":" + this.port + " with " + this.browser); } this.document = parseDocument(filename); if (this.baseUrl == null) { NodeList links = this.document.getElementsByTagName("link"); if (links.getLength() != 0) { Element link = (Element) links.item(0); setBaseUrl(link.getAttribute("href")); } } if (this.verbose) { System.out.println("Base URL=" + this.baseUrl); } Node body = this.document.getElementsByTagName("body").item(0); Element resultContainer = document.createElement("div"); resultContainer.setTextContent("Result: "); Element resultElt = document.createElement("span"); resultElt.setAttribute("id", "result"); resultElt.setIdAttribute("id", true); resultContainer.appendChild(resultElt); body.insertBefore(resultContainer, body.getFirstChild()); Element executionLogContainer = document.createElement("div"); executionLogContainer.setTextContent("Execution Log:"); Element executionLog = document.createElement("div"); executionLog.setAttribute("id", "log"); executionLog.setIdAttribute("id", true); executionLog.setAttribute("style", "white-space: pre;"); executionLogContainer.appendChild(executionLog); body.appendChild(executionLogContainer); NodeList tableRows = document.getElementsByTagName("tr"); Element theadRow = (Element) tableRows.item(0); test.name = theadRow.getTextContent(); appendCellToRow(theadRow, "Result"); this.commandProcessor = new HtmlCommandProcessor(this.host, this.port, this.browser, this.baseUrl); String resultState; String resultLog; test.result = true; try { this.commandProcessor.start(); test.commands = new Command[tableRows.getLength() - 1]; for (int i = 1; i < tableRows.getLength(); i++) { Element stepRow = (Element) tableRows.item(i); Command command = executeStep(stepRow); appendCellToRow(stepRow, command.result); test.commands[i - 1] = command; if (command.error) { test.result = false; } if (command.failure) { test.result = false; // break; } } resultState = test.result ? "PASSED" : "FAILED"; resultLog = (test.result ? "Test Complete" : "Error"); this.commandProcessor.stop(); } catch (Exception e) { test.result = false; resultState = "ERROR"; resultLog = "Failed to initialize session\n" + e; e.printStackTrace(); } document.getElementById("result").setTextContent(resultState); Element log = document.getElementById("log"); log.setTextContent(log.getTextContent() + resultLog + "\n"); return test.result; }
/** @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); }
public void CollectData(String link) { try { // Creating an empty XML Document DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); int flag = 0; // create the root element and add it to the document Element movie = doc.createElement("movie"); doc.appendChild(movie); movie.setAttribute("id", String.valueOf(n)); n++; // create sub elements Element genres = doc.createElement("genres"); Element actors = doc.createElement("actors"); Element reviews = doc.createElement("reviews"); URL movieUrl = new URL(link); URL reviewsURL = new URL(link + "reviews/#type=top_critics"); BufferedWriter bw3 = new BufferedWriter(new FileWriter("movies.xml", true)); int count = -1; String auth = ""; BufferedReader br3 = new BufferedReader(new InputStreamReader(movieUrl.openStream())); String str2 = ""; String info = ""; while (null != (str2 = br3.readLine())) { // start reading the html document if (str2.isEmpty()) continue; if (count == 14) break; if (count == 12) { if (!str2.contains("<h3>Cast</h3>")) continue; else count++; } if (count == 13) { if (str2.contains(">ADVERTISEMENT</p>")) { count++; movie.appendChild(actors); continue; } else { if (str2.contains("itemprop=\"name\">")) { Element actor = doc.createElement("actor"); actors.appendChild(actor); Text text = doc.createTextNode(Jsoup.parse(str2.toString()).text()); actor.appendChild(text); } else continue; } } if (count <= 11) { switch (count) { case -1: { if (!str2.contains("property=\"og:image\"")) continue; else { Pattern image = Pattern.compile("http://.*.jpg", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher match = image.matcher(str2); while (match.find()) { Element imageLink = doc.createElement("imageLink"); movie.appendChild(imageLink); Text text = doc.createTextNode(match.group()); imageLink.appendChild(text); count++; } } break; } case 0: { if (str2.contains("<title>")) { Element name = doc.createElement("name"); movie.appendChild(name); Text text = doc.createTextNode( Jsoup.parse(str2.toString().replace(" - Rotten Tomatoes", "")).text()); name.appendChild(text); count++; } break; } case 1: { if (!str2.contains("itemprop=\"ratingValue\"")) break; else { Element score = doc.createElement("score"); movie.appendChild(score); Text text = doc.createTextNode(Jsoup.parse(str2.toString()).text()); score.appendChild(text); count++; } break; } case 2: { if (!str2.contains("itemprop=\"description\">")) continue; else count++; break; } case 3: { if (!str2.contains("itemprop=\"duration\"")) info = info.concat(str2); else { Element MovieInfo = doc.createElement("MovieInfo"); movie.appendChild(MovieInfo); Text text = doc.createTextNode(Jsoup.parse(info.toString()).text()); MovieInfo.appendChild(text); info = str2; count++; } break; } case 4: { if (!str2.contains("itemprop=\"genre\"")) info = info.concat(str2); else { Element duration = doc.createElement("duration"); movie.appendChild(duration); Text text = doc.createTextNode(Jsoup.parse(info.toString()).text()); duration.appendChild(text); info = str2; count++; } break; } case 5: { if (info.contains("itemprop=\"genre\"")) { Element genre = doc.createElement("genre"); genres.appendChild(genre); Text text = doc.createTextNode(Jsoup.parse(info.toString()).text()); genre.appendChild(text); info = ""; } if (str2.contains(">Directed By:<")) { count++; movie.appendChild(genres); continue; } else { if (str2.contains("itemprop=\"genre\"")) { Element genre = doc.createElement("genre"); genres.appendChild(genre); Text text = doc.createTextNode(Jsoup.parse(str2.toString()).text()); genre.appendChild(text); } else continue; } break; } case 6: { if (!str2.contains(">Written By:<")) { if (str2.contains(">In Theaters:<")) { Element director = doc.createElement("director"); movie.appendChild(director); Text text = doc.createTextNode( Jsoup.parse(info.toString().replace("Directed By: ", "")).text()); director.appendChild(text); info = str2; count += 2; break; } info = info.concat(str2); } else { Element director = doc.createElement("director"); movie.appendChild(director); Text text = doc.createTextNode( Jsoup.parse(info.toString().replace("Directed By: ", "")).text()); director.appendChild(text); info = ""; count++; } break; } case 7: { if (!str2.contains(">In Theaters:<")) { if (str2.contains(">On DVD:<")) { Element writer = doc.createElement("writer"); movie.appendChild(writer); Text text = doc.createTextNode(Jsoup.parse(info.toString()).text()); writer.appendChild(text); info = str2; count += 2; break; } info = info.concat(str2); } else { Element writer = doc.createElement("writer"); movie.appendChild(writer); Text text = doc.createTextNode(Jsoup.parse(info.toString()).text()); writer.appendChild(text); info = str2; count++; } break; } case 8: { if (!str2.contains(">On DVD:<")) info = info.concat(str2); else { Element TheatreRelease = doc.createElement("TheatreRelease"); movie.appendChild(TheatreRelease); Text text = doc.createTextNode( Jsoup.parse(info.toString().replace("In Theaters:", "")).text()); TheatreRelease.appendChild(text); info = str2; count++; } break; } case 9: { if (!str2.contains(">US Box Office:<")) { if (str2.contains("itemprop=\"productionCompany\"")) { Element DvdRelease = doc.createElement("DvdRelease"); movie.appendChild(DvdRelease); Text text = doc.createTextNode( Jsoup.parse(info.toString().replace("On DVD:", "")).text()); DvdRelease.appendChild(text); info = str2; count += 2; break; } info = info.concat(str2); } else { Element DvdRelease = doc.createElement("DvdRelease"); movie.appendChild(DvdRelease); Text text = doc.createTextNode( Jsoup.parse(info.toString().replace("On DVD:", "")).text()); DvdRelease.appendChild(text); info = str2; count++; } break; } case 10: { if (!str2.contains("itemprop=\"productionCompany\"")) info = info.concat(str2); else { Element BOCollection = doc.createElement("BOCollection"); movie.appendChild(BOCollection); Text text = doc.createTextNode( Jsoup.parse(info.toString().replace("US Box Office:", "")).text()); BOCollection.appendChild(text); info = str2; count++; } break; } case 11: { if (!str2.contains(">Official Site")) info = info.concat(str2); else { Element Production = doc.createElement("Production"); movie.appendChild(Production); Text text = doc.createTextNode(Jsoup.parse(info.toString()).text()); Production.appendChild(text); info = str2; count++; } break; } default: break; } } } BufferedReader br4 = new BufferedReader(new InputStreamReader(reviewsURL.openStream())); String str3 = ""; String info2 = ""; int count2 = 0; while (null != (str3 = br4.readLine())) { if (count2 == 0) { if (!str3.contains("<div class=\"reviewsnippet\">")) continue; else count2++; } if (count2 == 1) { if (!str3.contains("<p class=\"small subtle\">")) info2 = info2.concat(str3); else { Element review = doc.createElement("review"); reviews.appendChild(review); Text text = doc.createTextNode(Jsoup.parse(info2.toString()).text()); review.appendChild(text); info2 = ""; count2 = 0; } } } movie.appendChild(reviews); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); // create string from xml tree StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source, result); String xmlString = sw.toString(); bw3.write(xmlString); br3.close(); br4.close(); bw3.close(); } catch (Exception ex) { ex.printStackTrace(); } }