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"); } }
/** * Transforms the given XML file using the specified XSL file. * * @param origXmlFile The file containg the XML to transform * @param xslFile The XML Stylesheet conntaining the transform instructions * @return String representation of the transformation */ public static String transform(File origXmlFile, File xslFile) { if (!origXmlFile.exists()) { GuiUtils.showErrorMessage( logger, "Warning, XML file: " + origXmlFile + " doesn't exist", null, null); return null; } if (!xslFile.exists()) { GuiUtils.showErrorMessage( logger, "Warning, XSL file: " + xslFile + " doesn't exist", null, null); return null; } try { logger.logComment("The xslFile is " + xslFile + " *************"); TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource xslFileSource = new StreamSource(xslFile); Transformer transformer = tFactory.newTransformer(xslFileSource); StringWriter writer = new StringWriter(); transformer.transform(new StreamSource(origXmlFile), new StreamResult(writer)); return writer.toString(); } catch (Exception e) { GuiUtils.showErrorMessage(logger, "Error when loading the XML file: " + origXmlFile, e, null); return null; } }
public void apply(String path, String[] scripts) throws ParserConfigurationException, TransformerConfigurationException { File target = new File(path); if (target.isDirectory()) { String callerDir = this.targetDir; this.targetDir = path; for (String script : scripts) call(script); this.targetDir = callerDir; } else { String tmpDir = inflate(path); if (tmpDir == null) return; apply(tmpDir, scripts); deflate(tmpDir, path); } }
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); } }
private void processDelete(Node operation) { String path = absolutePath(operation.getTextContent()); File target = new File(path); if (!target.exists()) { Utils.onError(new Error.FileNotFound(target.getPath())); return; } try { if (target.isDirectory()) { FileUtils.deleteDirectory(target); } else { FileUtils.forceDelete(target); } } catch (IOException ex) { Utils.onError(new Error.FileDelete(target.getPath())); } }
public void apply(String path, NodeList[] operations) throws ParserConfigurationException, TransformerConfigurationException { File target = new File(path); if (target.isDirectory()) { String callerDir = this.targetDir; this.targetDir = path; for (NodeList ops : operations) { for (int i = 0; i < ops.getLength(); i++) call(ops.item(i)); } this.targetDir = callerDir; } else { String tmpDir = inflate(path); if (tmpDir == null) return; apply(tmpDir, operations); deflate(tmpDir, path); } }
private void processXml(Node operation) throws ParserConfigurationException, TransformerConfigurationException { List<Node> targets = getChildNodes(operation, "target"); List<Node> appendOpNodes = getChildNodes(operation, "append"); List<Node> setOpNodes = getChildNodes(operation, "set"); List<Node> replaceOpNodes = getChildNodes(operation, "replace"); List<Node> removeOpNodes = getChildNodes(operation, "remove"); if (targets.isEmpty()) { return; } for (int t = 0; t < targets.size(); t++) { File target = new File(absolutePath(targets.get(t).getTextContent())); if (!target.exists()) { Utils.onError(new Error.FileNotFound(target.getPath())); return; } DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = null; try { doc = db.parse(target); } catch (Exception ex) { Utils.onError(new Error.FileParse(target.getPath())); return; } for (int i = 0; i < removeOpNodes.size(); i++) removeXmlEntry(doc, removeOpNodes.get(i)); for (int i = 0; i < replaceOpNodes.size(); i++) replaceXmlEntry(doc, replaceOpNodes.get(i)); for (int i = 0; i < setOpNodes.size(); i++) setXmlEntry(doc, setOpNodes.get(i)); for (int i = 0; i < appendOpNodes.size(); i++) appendXmlEntry(doc, appendOpNodes.get(i)); try { OutputFormat format = new OutputFormat(doc); format.setOmitXMLDeclaration(true); format.setLineWidth(65); format.setIndenting(true); format.setIndent(4); Writer out = new FileWriter(target); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(doc); } catch (IOException e) { Utils.onError(new Error.WriteXmlConfig(target.getPath())); } } }
private Transformer buildTransformer(String name, File xslDir, TransformerFactory tf) throws Exception { Transformer tr = tf.newTransformer( new StreamSource( new FileReader(xslDir.getAbsolutePath() + File.separatorChar + name + ".xsl"))); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "html"); tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); return tr; }
// ## 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; }
/** * Transforms the given XML string using the specified XSL file. * * @param xmlString The String containg the XML to transform * @param xslFile The XML Stylesheet conntaining the transform instructions * @return String representation of the transformation */ public static String transform(String xmlString, File xslFile) { if (!xslFile.exists()) { GuiUtils.showErrorMessage( logger, "Warning, XSL file: " + xslFile + " doesn't exist", null, null); return null; } String shortString = new String(xmlString); if (shortString.length() > 100) shortString = shortString.substring(0, 100) + "..."; try { logger.logComment("The xslFile is " + xslFile.getAbsolutePath() + " *************"); TransformerFactory tFactory = TransformerFactory.newInstance(); logger.logComment("Transforming string: " + shortString); StreamSource xslFileSource = new StreamSource(xslFile); Transformer transformer = tFactory.newTransformer(xslFileSource); StringWriter writer = new StringWriter(); transformer.transform( new StreamSource(new StringReader(xmlString)), new StreamResult(writer)); String shortResult = writer.toString(); if (shortResult.length() > 100) shortResult = shortResult.substring(0, 100) + "..."; logger.logComment("Result: " + shortResult); return writer.toString(); } catch (TransformerException e) { GuiUtils.showErrorMessage(logger, "Error when transforming the XML: " + shortString, e, null); return null; } }
/** * opens existing file * * @param a_file */ public GlyphFile(File a_file) { super(); m_fileName = a_file; URL url = null; try { url = a_file.toURI().toURL(); } catch (MalformedURLException e) { e.printStackTrace(); } init(url); }
private void processCopy(Node operation) { List<Node> fromNode = getChildNodes(operation, "from"); List<Node> toNode = getChildNodes(operation, "to"); if (fromNode.isEmpty() || toNode.isEmpty()) { return; } String path = fromNode.get(0).getTextContent(); String fromPath = (new File(path).isAbsolute()) ? path : absolutePath(path); String toPath = absolutePath(toNode.get(0).getTextContent()); Boolean copyContents = fromPath.endsWith(File.separator + "*"); File from = new File((copyContents) ? fromPath.substring(0, fromPath.length() - 2) : fromPath); File to = new File(toPath); if (!from.exists()) { Utils.onError(new Error.FileNotFound(from.getPath())); return; } try { if (copyContents) { FileUtils.forceMkdir(to); FileUtils.copyDirectory(from, to); } else if (from.isDirectory()) { FileUtils.forceMkdir(to); FileUtils.copyDirectoryToDirectory(from, to); } else { if (to.isDirectory()) { FileUtils.forceMkdir(to); FileUtils.copyFileToDirectory(from, to); } else { File toDir = new File(Utils.getParentDir(to)); FileUtils.forceMkdir(toDir); FileUtils.copyFile(from, to); } } } catch (IOException ex) { Utils.onError(new Error.FileCopy(from.getPath(), to.getPath())); } }
/** * XML Circuit constructor * * @param file the file that contains the XML description of the circuit * @param g the graphics that will paint the node * @throws CircuitLoadingException if the internal circuit can not be loaded */ public CircuitUI(File file, Graphics g) throws CircuitLoadingException { this(""); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; Document doc; Element root; Hashtable<Integer, Link> linkstable = new Hashtable<Integer, Link>(); try { builder = factory.newDocumentBuilder(); doc = builder.parse(file); } catch (SAXException sxe) { throw new CircuitLoadingException("SAX exception raised, invalid XML file."); } catch (ParserConfigurationException pce) { throw new CircuitLoadingException( "Parser exception raised, parser configuration is invalid."); } catch (IOException ioe) { throw new CircuitLoadingException("I/O exception, file cannot be loaded."); } root = (Element) doc.getElementsByTagName("Circuit").item(0); this.setName(root.getAttribute("name")); NodeList nl = root.getElementsByTagName("Node"); Element e; Node n; Class cl; for (int i = 0; i < nl.getLength(); ++i) { e = (Element) nl.item(i); try { cl = Class.forName(e.getAttribute("class")); } catch (Exception exc) { System.err.println(exc.getMessage()); throw new RuntimeException("Circuit creation from xml."); } try { n = ((Node) cl.newInstance()); } catch (Exception exc) { System.err.println(exc.getMessage()); throw new RuntimeException("Circuit creation from xml."); } this.nodes.add(n); n.setLocation(new Integer(e.getAttribute("x")), new Integer(e.getAttribute("y"))); if (n instanceof giraffe.ui.Nameable) ((Nameable) n).setNodeName(e.getAttribute("node_name")); if (n instanceof giraffe.ui.CompositeNode) { try { ((CompositeNode) n) .load(new File(file.getParent() + "/" + e.getAttribute("file_name")), g); } catch (Exception exc) { /* try to load from the lib */ ((CompositeNode) n) .load(new File(giraffe.Giraffe.PATH + "/lib/" + e.getAttribute("file_name")), g); } } NodeList nlist = e.getElementsByTagName("Anchor"); Element el; for (int j = 0; j < nlist.getLength(); ++j) { el = (Element) nlist.item(j); Anchor a = n.getAnchor(new Integer(el.getAttribute("id"))); NodeList linklist = el.getElementsByTagName("Link"); Element link; Link l; for (int k = 0; k < linklist.getLength(); ++k) { link = (Element) linklist.item(k); int id = new Integer(link.getAttribute("id")); int index = new Integer(link.getAttribute("index")); if (id >= this.linkID) linkID = id + 1; if (linkstable.containsKey(id)) { l = linkstable.get(id); l.addLinkedAnchorAt(a, index); a.addLink(l); } else { l = new Link(id); l.addLinkedAnchorAt(a, index); this.links.add(l); linkstable.put(id, l); a.addLink(l); } } } } }
public void init(ServletConfig config) throws ServletException { super.init(config); context = config.getServletContext(); TextProcessor tp = new CaseFolder(); try { wikipedia = new Wikipedia( context.getInitParameter("mysql_server"), context.getInitParameter("mysql_database"), context.getInitParameter("mysql_user"), context.getInitParameter("mysql_password")); } catch (Exception e) { throw new ServletException("Could not connect to wikipedia database."); } // Escaper escaper = new Escaper() ; definer = new Definer(this); comparer = new Comparer(this); searcher = new Searcher(this); try { wikifier = new Wikifier(this, tp); } catch (Exception e) { System.err.println("Could not initialize wikifier"); } try { File dataDirectory = new File(context.getInitParameter("data_directory")); if (!dataDirectory.exists() || !dataDirectory.isDirectory()) { throw new Exception(); } cachingThread = new CacherThread(dataDirectory, tp); cachingThread.start(); } catch (Exception e) { throw new ServletException("Could not locate wikipedia data directory."); } try { TransformerFactory tf = TransformerFactory.newInstance(); transformersByName = new HashMap<String, Transformer>(); transformersByName.put( "help", buildTransformer("help", new File("/research/wikipediaminer/web/xsl"), tf)); transformersByName.put( "loading", buildTransformer("loading", new File("/research/wikipediaminer/web/xsl"), tf)); transformersByName.put( "search", buildTransformer("search", new File("/research/wikipediaminer/web/xsl"), tf)); transformersByName.put( "compare", buildTransformer("compare", new File("/research/wikipediaminer/web/xsl"), tf)); transformersByName.put( "wikify", buildTransformer("wikify", new File("/research/wikipediaminer/web/xsl"), tf)); Transformer serializer = TransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputKeys.METHOD, "xml"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); transformersByName.put("serializer", serializer); } catch (Exception e) { throw new ServletException("Could not load xslt library."); } }
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(); } }
public static boolean transform( File origXmlFileOrDir, File xslFile, File targetDir, String extension) { logger.logComment( "Going to transform " + origXmlFileOrDir + " into dir " + targetDir + " using: " + xslFile, true); if (!origXmlFileOrDir.exists()) { GuiUtils.showErrorMessage( logger, "Warning, XML file/directory: " + origXmlFileOrDir + " doesn't exist", null, null); return false; } if (!xslFile.exists()) { GuiUtils.showErrorMessage( logger, "Warning, XSL file: " + xslFile + " doesn't exist", null, null); return false; } if (!targetDir.exists()) { GuiUtils.showErrorMessage( logger, "Warning, target directory: " + targetDir + " doesn't exist", null, null); return false; } if (origXmlFileOrDir.isDirectory()) { logger.logComment("That file is a directory. Converting all of the XML files in it"); File[] files = origXmlFileOrDir.listFiles(); boolean totalSuccess = true; for (int i = 0; i < files.length; i++) { if (!files[i].isDirectory() && (files[i].getName().endsWith(".xml") || files[i].getName().endsWith(".XML"))) { boolean partialSuccess = transform(files[i], xslFile, targetDir, extension); totalSuccess = totalSuccess || partialSuccess; } else if (files[i].isDirectory() && !GeneralUtils.isVersionControlDir(files[i])) { File newFolder = new File(targetDir, files[i].getName()); newFolder.mkdir(); logger.logComment( "Found a sub folder. Going to convert all there into: " + newFolder + "..."); transform(files[i], xslFile, newFolder, extension); } } return totalSuccess; } String result = transform(origXmlFileOrDir, xslFile); String newName = origXmlFileOrDir.getName(); if (newName.endsWith(".xml") || newName.endsWith(".XML")) { newName = newName.substring(0, newName.length() - 4) + extension; } File targetFile = new File(targetDir, newName); try { FileWriter fw = new FileWriter(targetFile); fw.write(result); fw.close(); } catch (IOException ex) { GuiUtils.showErrorMessage(logger, "Exception writing to file: " + targetFile, ex, null); return false; } logger.logComment("The result is in " + targetFile + " *************"); return result != null; }
/* * Carries out a number of tests, generates NEURON, GENESIS and NeuroML code etc. */ private static void doTests(neuronEditorFrame nef, String fileName) { System.out.println( "Testing Cvapp/NeuroMorpho.Org by generating NEURON, GENESIS and NeuroML files for " + fileName); File tempDir = new File("temp"); if (!tempDir.exists()) tempDir.mkdir(); neuronEditorPanel nep = nef.getNeuronEditorPanel(); String rootFileName = fileName; if (rootFileName.toLowerCase().endsWith(".swc")) { rootFileName = rootFileName.substring(0, rootFileName.length() - 4); } if (rootFileName.lastIndexOf(System.getProperty("file.separator")) > 0) { rootFileName = rootFileName.substring( rootFileName.lastIndexOf(System.getProperty("file.separator")) + 1); } // NEURON save... String neuronFileName = rootFileName + ".hoc"; File neuronFile = new File(tempDir, neuronFileName); File neuronTestFile = new File(tempDir, rootFileName + "_test.hoc"); nep.writeStringToFile(nep.getCell().HOCwriteNS(), neuronFile.getAbsolutePath()); StringBuilder sbNeuTest = new StringBuilder(); sbNeuTest.append("load_file(\"nrngui.hoc\")\n"); sbNeuTest.append("load_file(\"../neuronUtils/nCtools.hoc\")\n"); sbNeuTest.append("load_file(\"../neuronUtils/cellCheck.hoc\")\n"); sbNeuTest.append("load_file(\"nrngui.hoc\")\n"); sbNeuTest.append("load_file(\"" + neuronFileName + "\")\n\n"); sbNeuTest.append("forall morph()\n"); System.out.println("--------------------------------------------------------------"); nep.writeStringToFile(sbNeuTest.toString(), neuronTestFile.getAbsolutePath()); System.out.println( "Saved NEURON representation of the file to: " + neuronFile.getAbsolutePath() + ": " + neuronFile.exists()); System.out.println("--------------------------------------------------------------"); // GENESIS save... String genesisFileName = rootFileName + ".p"; File genesisFile = new File(tempDir, genesisFileName); File genesisTestFile = new File(tempDir, rootFileName + "_test.g"); nep.writeStringToFile(nep.getCell().GENESISwriteHR(), genesisFile.getAbsolutePath()); StringBuilder sbGenTest = new StringBuilder(); sbGenTest.append("include compartments \n"); sbGenTest.append("create neutral /library\n"); sbGenTest.append("disable /library\n"); sbGenTest.append("ce /library\n"); sbGenTest.append("make_cylind_compartment\n"); sbGenTest.append("make_cylind_symcompartment\n"); sbGenTest.append("make_sphere_compartment\n"); sbGenTest.append("ce /\n"); sbGenTest.append( "echo \"Prototype compartments created, reading cell from " + genesisFileName + "\"\n"); sbGenTest.append("readcell " + genesisFileName + " /mycell\n\n"); sbGenTest.append("create xform /form [0,0,400,400] -nolabel\n"); sbGenTest.append( "create xdraw /form/draw [0,0,100%,100%] -wx 0.002 -wy 0.002 -transform ortho3d -bg white\n"); sbGenTest.append( "setfield /form/draw xmin -3.0E-4 xmax 3.0E-4 ymin -3.0E-4 ymax 3.0E-4 vx 0.0 vy 0.0 vz -0.002\n"); sbGenTest.append( "create xcell /form/draw/cell -path \"/mycell/##[][TYPE=compartment],/mycell/##[][TYPE=symcompartment]\" -colfield Vm -colmin -0.07 -colmax 0.03 -diarange -5\n"); sbGenTest.append("xcolorscale hot\n"); sbGenTest.append("xshow /form\n\n"); sbGenTest.append("showfield /mycell/##[][TYPE=compartment] **\n\n"); nep.writeStringToFile(sbGenTest.toString(), genesisTestFile.getAbsolutePath()); System.out.println( "Saved GENESIS representation of the file to: " + genesisFile.getAbsolutePath() + ": " + genesisFile.exists()); System.out.println("--------------------------------------------------------------"); // NeuroML save... String nml1FileName = rootFileName + ".xml"; File nml1File = new File(tempDir, nml1FileName); 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("Schemas/v1.8.1/Level3/NeuroML_Level3_v1.8.1.xsd"); validateXML(nml1File, v1schemaFile); String nml2FileName = rootFileName + ".cell.nml"; if (Character.isDigit(nml2FileName.charAt(0))) { nml2FileName = "Cell_" + nml2FileName; } File nml2File = new File(tempDir, nml2FileName); nep.writeStringToFile(nep.getCell().writeNeuroML_v2beta(), nml2File.getAbsolutePath()); System.out.println( "Saved NeuroML representation of the file to: " + nml2File.getAbsolutePath() + ": " + nml2File.exists()); validateXMLWithURL(nml2File, "Schemas/v2/NeuroML_v2beta4.xsd"); }
public String getShortFileName() { return m_fileName.getName(); }
private void processTxt(Node operation) { List<Node> targets = getChildNodes(operation, "target"); List<Node> optionNodes = getChildNodes(operation, "opt"); List<Node> separatorNode = getChildNodes(operation, "separator"); if (targets.isEmpty() || optionNodes.isEmpty()) { return; } String defaultSeparator = "="; String globalSeparator = defaultSeparator; if (!separatorNode.isEmpty()) { globalSeparator = separatorNode.get(0).getTextContent(); if (globalSeparator.length() != 1) { globalSeparator = defaultSeparator; } } Map<String, String> options = new HashMap<String, String>(); Map<String, String> processedOptions = new HashMap<String, String>(); for (int i = 0; i < optionNodes.size(); i++) { Node option = optionNodes.get(i); String name = option.getAttributes().getNamedItem("name").getNodeValue(); String value = option.getTextContent(); if (options.containsKey(name)) { options.remove(name); } options.put(name, value); } for (int t = 0; t < targets.size(); t++) { File target = new File(absolutePath(targets.get(t).getTextContent())); File tmpFile = new File(Utils.timestamp()); BufferedWriter bw = null; BufferedReader br = null; try { Node separatorAttr = targets.get(t).getAttributes().getNamedItem("separator"); String separator = (separatorAttr == null) ? globalSeparator : separatorAttr.getNodeValue(); if (separator.length() != 1) { separator = globalSeparator; } bw = new BufferedWriter(new FileWriter(tmpFile)); if (target.exists()) { br = new BufferedReader(new FileReader(target)); for (String line; (line = br.readLine()) != null; ) { String[] parts = line.split(separator); if (parts.length < 2) { bw.write(line); bw.newLine(); continue; } String optName = parts[0].trim(); if (options.containsKey(optName)) { String optValue = options.get(optName); bw.write(optName + " " + separator + " " + optValue); bw.newLine(); processedOptions.put(optName, optValue); options.remove(optName); } else if (processedOptions.containsKey(optName)) { bw.write(optName + " " + separator + " " + processedOptions.get(optName)); bw.newLine(); } else { bw.write(line); bw.newLine(); } } br.close(); } for (Map.Entry<String, String> entry : options.entrySet()) { bw.write(entry.getKey() + " " + separator + " " + entry.getValue()); bw.newLine(); } bw.close(); FileUtils.copyFile(tmpFile, target); FileUtils.forceDelete(tmpFile); } catch (IOException ex) { Utils.onError(new Error.WriteTxtConfig(target.getPath())); } } }