/** Initialize the panel UI component values from the current site profile settings. */ public void updatePanel() { { File dir = pApp.getHomeDirectory(); if (dir == null) { String home = System.getProperty("user.home"); if (home != null) { File hdir = new File(home); if ((hdir != null) && hdir.isDirectory()) dir = hdir.getParentFile(); } } if (dir == null) dir = new File("/home"); pHomeDirComp.setDir(dir); } { File dir = pApp.getTemporaryDirectory(); if (dir == null) dir = new File("/var/tmp"); pTempDirComp.setDir(dir); } { File dir = pApp.getUnixJavaHome(); if (dir == null) dir = new File(pApp.getJavaHome()); pJavaHomeDirComp.setDir(dir); } pJavadocDirComp.setDir(pApp.getUnixLocalJavadocDirectory()); pExtraJavaLibsComp.setJars(pApp.getUnixLocalJavaLibraries()); }
protected void fileNew() { if (currentFile != null) { if (!currentFile.isDirectory()) { currentFile = currentFile.getParentFile(); } } graph.clear(); gp.update(gp.getGraphics()); }
/** * The FileEvent listener. * * @param event the event. */ public void fileEventOccurred(FileEvent event) { File file = event.getFile(); if (file != null) { String dirPath; if (file.isDirectory()) dirPath = file.getAbsolutePath(); else dirPath = file.getParentFile().getAbsolutePath(); properties.setProperty("directory", dirPath); } else properties.remove("directory"); }
/** * Delete the given files. Refuses to delete files outside the user plugin directory. This method * throws no errors is the files don't exist or deletion failed. * * @param filenames An array of names of the files to be deleted. */ public static void deletePluginsOnStartup(String[] filenames) { for (String s : filenames) { File f = new File(s); if (f.getParentFile().equals(PluginCore.userPluginDir)) { // if (s.startsWith(PluginCore.userPluginDir.getPath())) { boolean success = f.delete(); } else System.out.println("File outside of user plugin dir: " + s); } }
/** Returns false if Exception is thrown. */ private boolean setDirectory() { String pathStr = dirTF.getText().trim(); if (pathStr.equals("")) pathStr = System.getProperty("user.dir"); try { File dirPath = new File(pathStr); if (!dirPath.isDirectory()) { if (!dirPath.exists()) { if (recursiveCheckBox.isSelected()) throw new NotDirectoryException(dirPath.getAbsolutePath()); else throw new NotFileException(dirPath.getAbsolutePath()); } else { convertSet.setFile(dirPath); convertSet.setDestinationPath(dirPath.getParentFile()); } } else { // Set the descriptors setMatchingFileNames(); FlexFilter flexFilter = new FlexFilter(); flexFilter.addDescriptors(descriptors); flexFilter.setFilesOnly(!recursiveCheckBox.isSelected()); convertSet.setSourcePath(dirPath, flexFilter); convertSet.setDestinationPath(dirPath); } } catch (NotDirectoryException e1) { final String caption = ResourceHandler.getMessage("notdirectory_dialog.caption1"); MessageFormat formatter; String info_msg; if (pathStr.equals("")) { info_msg = ResourceHandler.getMessage("notdirectory_dialog.info5"); } else { formatter = new MessageFormat(ResourceHandler.getMessage("notdirectory_dialog.info0")); info_msg = formatter.format(new Object[] {pathStr}); } final String info = info_msg; JOptionPane.showMessageDialog(this, info, caption, JOptionPane.ERROR_MESSAGE); return false; } catch (NotFileException e2) { final String caption = ResourceHandler.getMessage("notdirectory_dialog.caption0"); MessageFormat formatter = new MessageFormat(ResourceHandler.getMessage("notdirectory_dialog.info1")); final String info = formatter.format(new Object[] {pathStr}); JOptionPane.showMessageDialog(this, info, caption, JOptionPane.ERROR_MESSAGE); return false; } return true; // no exception thrown }
public GalaxyViewer(Settings settings, boolean animatorFrame) throws Exception { super("Stars GalaxyViewer"); this.settings = settings; this.animatorFrame = animatorFrame; if (settings.gameName.equals("")) throw new Exception("GameName not defined in settings."); setDefaultCloseOperation(EXIT_ON_CLOSE); File dir = new File(settings.directory); File map = new File(dir, settings.getGameName() + ".MAP"); if (map.exists() == false) { File f = new File(dir.getParentFile(), settings.getGameName() + ".MAP"); if (f.exists()) map = f; else { String error = "Could not find " + map.getAbsolutePath() + "\n"; error += "Export this file from Stars! (Only needs to be done one time pr game)"; throw new Exception(error); } } Vector<File> mFiles = new Vector<File>(); Vector<File> hFiles = new Vector<File>(); for (File f : dir.listFiles()) { if (f.getName().toUpperCase().endsWith("MAP")) continue; if (f.getName().toUpperCase().endsWith("HST")) continue; if (f.getName().toUpperCase().startsWith(settings.getGameName() + ".M")) mFiles.addElement(f); else if (f.getName().toUpperCase().startsWith(settings.getGameName() + ".H")) hFiles.addElement(f); } if (mFiles.size() == 0) throw new Exception("No M-files found matching game name."); if (hFiles.size() == 0) throw new Exception("No H-files found matching game name."); parseMapFile(map); Vector<File> files = new Vector<File>(); files.addAll(mFiles); files.addAll(hFiles); p = new Parser(files); calculateColors(); // UI: JPanel cp = (JPanel) getContentPane(); cp.setLayout(new BorderLayout()); cp.add(universe, BorderLayout.CENTER); JPanel south = createPanel(0, hw, new JLabel("Search: "), search, names, zoom, colorize); search.setPreferredSize(new Dimension(100, -1)); cp.add(south, BorderLayout.SOUTH); hw.addActionListener(this); names.addActionListener(this); zoom.addChangeListener(this); search.addKeyListener(this); colorize.addActionListener(this); setSize(800, 600); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screen.width - getWidth()) / 2, (screen.height - getHeight()) / 2); setVisible(animatorFrame == false); if (animatorFrame) names.setSelected(false); }
@Nullable private static File findOldConfigDir( @NotNull File configDir, @Nullable String customPathSelector) { final File selectorDir = CONFIG_RELATED_PATH.isEmpty() ? configDir : configDir.getParentFile(); final File parent = selectorDir.getParentFile(); if (parent == null || !parent.exists()) { return null; } File maxFile = null; long lastModified = 0; final String selector = PathManager.getPathsSelector() != null ? PathManager.getPathsSelector() : selectorDir.getName(); final String prefix = getPrefixFromSelector(selector); final String customPrefix = customPathSelector != null ? getPrefixFromSelector(customPathSelector) : null; for (File file : parent.listFiles( new FilenameFilter() { @Override public boolean accept(@NotNull File file, @NotNull String name) { return StringUtil.startsWithIgnoreCase(name, prefix) || customPrefix != null && StringUtil.startsWithIgnoreCase(name, customPrefix); } })) { File options = new File(file, CONFIG_RELATED_PATH + OPTIONS_XML); if (!options.exists()) { continue; } long modified = options.lastModified(); if (modified > lastModified) { lastModified = modified; maxFile = file; } } return maxFile != null ? new File(maxFile, CONFIG_RELATED_PATH) : null; }
private void updateLinuxServiceInstaller() { try { File dir = new File(directory, "CTP"); if (suppressFirstPathElement) dir = dir.getParentFile(); Properties props = new Properties(); String ctpHome = dir.getAbsolutePath(); cp.appendln(Color.black, "...CTP_HOME: " + ctpHome); ctpHome = ctpHome.replaceAll("\\\\", "\\\\\\\\"); props.put("CTP_HOME", ctpHome); File javaHome = new File(System.getProperty("java.home")); String javaBin = (new File(javaHome, "bin")).getAbsolutePath(); cp.appendln(Color.black, "...JAVA_BIN: " + javaBin); javaBin = javaBin.replaceAll("\\\\", "\\\\\\\\"); props.put("JAVA_BIN", javaBin); File linux = new File(dir, "linux"); File install = new File(linux, "ctpService-ubuntu.sh"); cp.appendln(Color.black, "Linux service installer:"); cp.appendln(Color.black, "...file: " + install.getAbsolutePath()); String bat = getFileText(install); bat = replace(bat, props); // do the substitutions bat = bat.replace("\r", ""); setFileText(install, bat); // If this is an ISN installation, put the script in the correct place. String osName = System.getProperty("os.name").toLowerCase(); if (programName.equals("ISN") && !osName.contains("windows")) { install = new File(linux, "ctpService-red.sh"); cp.appendln(Color.black, "ISN service installer:"); cp.appendln(Color.black, "...file: " + install.getAbsolutePath()); bat = getFileText(install); bat = replace(bat, props); // do the substitutions bat = bat.replace("\r", ""); File initDir = new File("/etc/init.d"); File initFile = new File(initDir, "ctpService"); if (initDir.exists()) { setOwnership(initDir, "edge", "edge"); setFileText(initFile, bat); initFile.setReadable(true, false); // everybody can read //Java 1.6 initFile.setWritable(true); // only the owner can write //Java 1.6 initFile.setExecutable(true, false); // everybody can execute //Java 1.6 } } } catch (Exception ex) { ex.printStackTrace(); System.err.println("Unable to update the Linux service ctpService.sh file"); } }
public static byte[] recvFile(Socket sock, File out) throws IOException, NoSuchAlgorithmException { FileOutputStream mainOut = new FileOutputStream(out); byte[] ret = null; boolean reading = true; MessageDigest major = MessageDigest.getInstance(SecureUtils.STD_HASH); int block = 0; while (reading) { // while there is data to be read long readln = readInteger(sock.getInputStream()); // read the length of the next block if (readln == TRANS_FINISH) { // if there are no more block mainOut.close(); ret = major.digest(); sock.getOutputStream().write(ret); // send my major hash long finishReply = readInteger(sock.getInputStream()); // read the reply if (finishReply == TRANS_FINISH) { // if the major hash was correct reading = false; // complete the transaction } else { // else the major has was incorrect out.delete(); // delete the file mainOut = new FileOutputStream(out); // reset the output streams // start again block = 0; major = MessageDigest.getInstance(SecureUtils.STD_HASH); ret = null; } } else { // else there are more blocks File tempOut = new File(out.getParentFile(), out.getName() + ".part" + block); FileOutputStream partStream = new FileOutputStream(tempOut); // spawn a temporary file byte[] hash = hashpipe(sock.getInputStream(), partStream, readln); // read the block to temp file partStream.close(); sock.getOutputStream().write(hash); // send my minor hash long minorReply = readInteger(sock.getInputStream()); // read the reply if (minorReply == TRANS_SUCCESS) { // if the transfer was correct FileInputStream partIn = new FileInputStream(tempOut); hashpipe(partIn, mainOut, readln, major); // send the temp file to the main file block++; } else { // if the transfer was wrong // do nothing } tempOut.delete(); // delete the temp file } } return ret; }
private static boolean deleteWithSubordinates(File file) { final String baseName = file.getName(); final File[] files = file.getParentFile() .listFiles( new FileFilter() { @Override public boolean accept(final File pathname) { return pathname.getName().startsWith(baseName); } }); boolean ok = true; if (files != null) { for (File f : files) { ok &= FileUtil.delete(f); } } return ok; }
// If this is a new installation, ask the user for a // port for the server; otherwise, return the negative // of the configured port. If the user selects an illegal // port, return zero. private int getPort() { // Note: directory points to the parent of the CTP directory. File ctp = new File(directory, "CTP"); if (suppressFirstPathElement) ctp = ctp.getParentFile(); File config = new File(ctp, "config.xml"); if (!config.exists()) { // No config file - must be a new installation. // Figure out whether this is Windows or something else. String os = System.getProperty("os.name").toLowerCase(); int defPort = ((os.contains("windows") && !programName.equals("ISN")) ? 80 : 1080); int userPort = 0; while (userPort == 0) { String port = JOptionPane.showInputDialog( null, "This is a new " + programName + " installation.\n\n" + "Select a port number for the web server.\n\n", Integer.toString(defPort)); try { userPort = Integer.parseInt(port.trim()); } catch (Exception ex) { userPort = -1; } if ((userPort < 80) || (userPort > 32767)) userPort = 0; } return userPort; } else { try { Document doc = getDocument(config); Element root = doc.getDocumentElement(); Element server = getFirstNamedChild(root, "Server"); String port = server.getAttribute("port"); return -Integer.parseInt(port); } catch (Exception ex) { } } return 0; }
private void updateWindowsServiceInstaller() { try { File dir = new File(directory, "CTP"); if (suppressFirstPathElement) dir = dir.getParentFile(); File windows = new File(dir, "windows"); File install = new File(windows, "install.bat"); cp.appendln(Color.black, "Windows service installer:"); cp.appendln(Color.black, "...file: " + install.getAbsolutePath()); String bat = getFileText(install); Properties props = new Properties(); String home = dir.getAbsolutePath(); cp.appendln(Color.black, "...home: " + home); home = home.replaceAll("\\\\", "\\\\\\\\"); props.put("home", home); bat = replace(bat, props); setFileText(install, bat); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Unable to update the windows service install.barfile."); } }
private void installConfigFile(int port) { if (port > 0) { System.out.println("Looking for /config/config.xml"); InputStream is = getClass().getResourceAsStream("/config/config.xml"); if (is != null) { try { File ctp = new File(directory, "CTP"); if (suppressFirstPathElement) ctp = ctp.getParentFile(); File config = new File(ctp, "config.xml"); Document doc = getDocument(is); Element root = doc.getDocumentElement(); Element server = getFirstNamedChild(root, "Server"); System.out.println("...setting the port to " + port); server.setAttribute("port", Integer.toString(port)); adjustConfiguration(root, ctp); setFileText(config, toString(doc)); } catch (Exception ex) { System.err.println("...Error: unable to install the config.xml file"); } } else System.err.println("...could not find it."); } }
/** * Class constructor; creates a new Installer object, displays a JFrame introducing the program, * allows the user to select an install directory, and copies files from the jar into the * directory. */ public Installer(String args[]) { // Inputs are --install-dir INSTALL_DIR for (int k = 0; k < args.length; k = k + 2) { switch (args[k]) { case "--install-dir": directory = new File(args[k + 1]); System.out.println(directory); break; case "--port": port = Integer.parseInt(args[k + 1]); break; } } cp = new Stream(); // Find the installer program so we can get to the files. installer = getInstallerProgramFile(); String name = installer.getName(); programName = (name.substring(0, name.indexOf("-"))).toUpperCase(); // Get the installation information thisJava = System.getProperty("java.version"); thisJavaBits = System.getProperty("sun.arch.data.model") + " bits"; // Find the ImageIO Tools and get the version String javaHome = System.getProperty("java.home"); File extDir = new File(javaHome); extDir = new File(extDir, "lib"); extDir = new File(extDir, "ext"); File clib = getFile(extDir, "clibwrapper_jiio", ".jar"); File jai = getFile(extDir, "jai_imageio", ".jar"); imageIOTools = (clib != null) && clib.exists() && (jai != null) && jai.exists(); if (imageIOTools) { Hashtable<String, String> jaiManifest = getManifestAttributes(jai); imageIOVersion = jaiManifest.get("Implementation-Version"); } // Get the CTP.jar parameters Hashtable<String, String> manifest = getJarManifestAttributes("/CTP/libraries/CTP.jar"); programDate = manifest.get("Date"); buildJava = manifest.get("Java-Version"); // Get the util.jar parameters Hashtable<String, String> utilManifest = getJarManifestAttributes("/CTP/libraries/util.jar"); utilJava = utilManifest.get("Java-Version"); // Get the MIRC.jar parameters (if the plugin is present) Hashtable<String, String> mircManifest = getJarManifestAttributes("/CTP/libraries/MIRC.jar"); if (mircManifest != null) { mircJava = mircManifest.get("Java-Version"); mircDate = mircManifest.get("Date"); mircVersion = mircManifest.get("Version"); } // Set up the installation information for display if (imageIOVersion.equals("")) { imageIOVersion = "<b><font color=\"red\">not installed</font></b>"; } else if (imageIOVersion.startsWith("1.0")) { imageIOVersion = "<b><font color=\"red\">" + imageIOVersion + "</font></b>"; } if (thisJavaBits.startsWith("64")) { thisJavaBits = "<b><font color=\"red\">" + thisJavaBits + "</font></b>"; } boolean javaOK = (thisJava.compareTo(buildJava) >= 0); javaOK &= (thisJava.compareTo(utilJava) >= 0); javaOK &= (thisJava.compareTo(mircJava) >= 0); if (!javaOK) { thisJava = "<b><font color=\"red\">" + thisJava + "</font></b>"; } if (directory == null) exit(); // Point to the parent of the directory in which to install the program. // so the copy process works correctly for directory trees. // // If the user has selected a directory named "CTP", // then assume that this is the directory in which // to install the program. // // If the directory is not CTP, see if it is called "RSNA" and contains // the Launcher program, in which case we can assume that it is an // installation that was done with Bill Weadock's all-in-one installer for Windows. // // If neither of those cases is true, then this is already the parent of the // directory in which to install the program if (directory.getName().equals("CTP")) { directory = directory.getParentFile(); } else if (directory.getName().equals("RSNA") && (new File(directory, "Launcher.jar")).exists()) { suppressFirstPathElement = true; } // Cleanup old releases cleanup(directory); // Get a port for the server. if (port < 0) { if (checkServer(-port, false)) { System.err.println( "CTP appears to be running.\nPlease stop CTP and run the installer again."); System.exit(0); } } // Now install the files and report the results. int count = unpackZipFile(installer, "CTP", directory.getAbsolutePath(), suppressFirstPathElement); if (count > 0) { // Create the service installer batch files. updateWindowsServiceInstaller(); updateLinuxServiceInstaller(); // If this was a new installation, set up the config file and set the port installConfigFile(port); // Make any necessary changes in the config file to reflect schema evolution fixConfigSchema(); System.out.println("Installation complete."); System.out.println(programName + " has been installed successfully."); System.out.println(count + " files were installed."); } else { System.err.println("Installation failed."); System.err.println(programName + " could not be fully installed."); } if (!programName.equals("ISN") && startRunner(new File(directory, "CTP"))) System.exit(0); }
@Override public void run() { try { StringBuilder filePath = new StringBuilder(); filePath.append(Constants.IO.imageBaseDir).append(File.separator); filePath .append(card.hashCode()) .append(".") .append(card.getName().replace(":", "").replace("//", "-")) .append(".jpg"); File temporaryFile = new File(filePath.toString()); String imagePath = CardImageUtils.generateImagePath(card); TFile outputFile = new TFile(imagePath); if (!outputFile.exists()) { outputFile.getParentFile().mkdirs(); } File existingFile = new File(imagePath.replaceFirst("\\w{3}.zip", "")); if (existingFile.exists()) { new TFile(existingFile).cp_rp(outputFile); synchronized (sync) { update(cardIndex + 1, count); } existingFile.delete(); File parent = existingFile.getParentFile(); if (parent != null && parent.isDirectory() && parent.list().length == 0) { parent.delete(); } return; } BufferedOutputStream out; // Logger.getLogger(this.getClass()).info(url.toString()); URLConnection httpConn = url.openConnection(p); httpConn.connect(); if (((HttpURLConnection) httpConn).getResponseCode() == 200) { try (BufferedInputStream in = new BufferedInputStream(((HttpURLConnection) httpConn).getInputStream())) { // try (BufferedInputStream in = new // BufferedInputStream(url.openConnection(p).getInputStream())) { out = new BufferedOutputStream(new TFileOutputStream(temporaryFile)); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) != -1) { // user cancelled if (cancel) { in.close(); out.flush(); out.close(); temporaryFile.delete(); return; } out.write(buf, 0, len); } } out.flush(); out.close(); if (card.isTwoFacedCard()) { BufferedImage image = ImageIO.read(temporaryFile); if (image.getHeight() == 470) { BufferedImage renderedImage = new BufferedImage(265, 370, BufferedImage.TYPE_INT_RGB); renderedImage.getGraphics(); Graphics2D graphics2D = renderedImage.createGraphics(); if (card.isTwoFacedCard() && card.isSecondSide()) { graphics2D.drawImage(image, 0, 0, 265, 370, 313, 62, 578, 432, null); } else { graphics2D.drawImage(image, 0, 0, 265, 370, 41, 62, 306, 432, null); } graphics2D.dispose(); writeImageToFile(renderedImage, outputFile); } else { new TFile(temporaryFile).cp_rp(outputFile); } temporaryFile.delete(); } else { new TFile(temporaryFile).cp_rp(outputFile); temporaryFile.delete(); } } else { Logger.getLogger(this.getClass()) .error(convertStreamToString(((HttpURLConnection) httpConn).getErrorStream())); } } catch (Exception e) { log.error(e, e); } synchronized (sync) { update(cardIndex + 1, count); } }
public void actionPerformed(ActionEvent e) { if (isDirectorySelected()) { File dir = getDirectory(); if (dir != null) { try { // Strip trailing ".." dir = ShellFolder.getNormalizedFile(dir); } catch (IOException ex) { // Ok, use f as is } changeDirectory(dir); return; } } JFileChooser chooser = getFileChooser(); String filename = getFileName(); FileSystemView fs = chooser.getFileSystemView(); File dir = chooser.getCurrentDirectory(); if (filename != null) { // Remove whitespaces from end of filename int i = filename.length() - 1; while (i >= 0 && filename.charAt(i) <= ' ') { i--; } filename = filename.substring(0, i + 1); } if (filename == null || filename.length() == 0) { // no file selected, multiple selection off, therefore cancel the approve action resetGlobFilter(); return; } File selectedFile = null; File[] selectedFiles = null; // Unix: Resolve '~' to user's home directory if (File.separatorChar == '/') { if (filename.startsWith("~/")) { filename = System.getProperty("user.home") + filename.substring(1); } else if (filename.equals("~")) { filename = System.getProperty("user.home"); } } if (chooser.isMultiSelectionEnabled() && filename.length() > 1 && filename.charAt(0) == '"' && filename.charAt(filename.length() - 1) == '"') { List<File> fList = new ArrayList<File>(); String[] files = filename.substring(1, filename.length() - 1).split("\" \""); // Optimize searching files by names in "children" array Arrays.sort(files); File[] children = null; int childIndex = 0; for (String str : files) { File file = fs.createFileObject(str); if (!file.isAbsolute()) { if (children == null) { children = fs.getFiles(dir, false); Arrays.sort(children); } for (int k = 0; k < children.length; k++) { int l = (childIndex + k) % children.length; if (children[l].getName().equals(str)) { file = children[l]; childIndex = l + 1; break; } } } fList.add(file); } if (!fList.isEmpty()) { selectedFiles = fList.toArray(new File[fList.size()]); } resetGlobFilter(); } else { selectedFile = fs.createFileObject(filename); if (!selectedFile.isAbsolute()) { selectedFile = fs.getChild(dir, filename); } // check for wildcard pattern FileFilter currentFilter = chooser.getFileFilter(); if (!selectedFile.exists() && isGlobPattern(filename)) { changeDirectory(selectedFile.getParentFile()); if (globFilter == null) { globFilter = new GlobFilter(); } try { globFilter.setPattern(selectedFile.getName()); if (!(currentFilter instanceof GlobFilter)) { actualFileFilter = currentFilter; } chooser.setFileFilter(null); chooser.setFileFilter(globFilter); return; } catch (PatternSyntaxException pse) { // Not a valid glob pattern. Abandon filter. } } resetGlobFilter(); // Check for directory change action boolean isDir = (selectedFile != null && selectedFile.isDirectory()); boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile)); boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled(); boolean isFileSelEnabled = chooser.isFileSelectionEnabled(); boolean isCtrl = (e != null && (e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0); if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) { changeDirectory(selectedFile); return; } else if ((isDir || !isFileSelEnabled) && (!isDir || !isDirSelEnabled) && (!isDirSelEnabled || selectedFile.exists())) { selectedFile = null; } } if (selectedFiles != null || selectedFile != null) { if (selectedFiles != null || chooser.isMultiSelectionEnabled()) { if (selectedFiles == null) { selectedFiles = new File[] {selectedFile}; } chooser.setSelectedFiles(selectedFiles); // Do it again. This is a fix for bug 4949273 to force the // selected value in case the ListSelectionModel clears it // for non-existing file names. chooser.setSelectedFiles(selectedFiles); } else { chooser.setSelectedFile(selectedFile); } chooser.approveSelection(); } else { if (chooser.isMultiSelectionEnabled()) { chooser.setSelectedFiles(null); } else { chooser.setSelectedFile(null); } chooser.cancelSelection(); } }
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(); } }
private void process() { int width = Integer.parseInt(xres.getText()); int height = Integer.parseInt(yres.getText()); boolean preserveAspect = aspect.isSelected(); Color bg = new Color(red.getValue(), green.getValue(), blue.getValue()); String outDir = output.getText(); String suffix = ((String) format.getSelectedItem()).toLowerCase(); String preText = prepend.getText(); String appText = append.getText(); int scaleType = -1; String alg = (String) algorithm.getSelectedItem(); if (alg.equals("Smooth")) scaleType = Image.SCALE_SMOOTH; else if (alg.equals("Standard")) scaleType = Image.SCALE_DEFAULT; else if (alg.equals("Fast")) scaleType = Image.SCALE_FAST; else if (alg.equals("Replicate")) scaleType = Image.SCALE_REPLICATE; else if (alg.equals("Area averaging")) { scaleType = Image.SCALE_AREA_AVERAGING; } DefaultListModel model = (DefaultListModel) list.getModel(); int size = model.size(); progress.setValue(0); progress.setMaximum(4 * size); for (int i = 0; i < size; i++) { ThumbFile tf = (ThumbFile) model.elementAt(i); list.setSelectedValue(tf, true); String tail = " (" + (i + 1) + " of " + size + ")"; progress.setValue(4 * i); progress.setString("Reading" + tail); // construct input and output filenames String inFile = tf.getPath(); String outFile = outDir + SLASH + tf.getName(); int ndx = outFile.lastIndexOf(SLASH); String s1 = outFile.substring(0, ndx + SLASH.length()); String s2 = outFile.substring(ndx + SLASH.length()); int dot_ndx = s2.lastIndexOf("."); if (dot_ndx >= 0) s2 = s2.substring(0, dot_ndx); // make the thumbnail file name outFile = s1 + preText + s2 + appText + "." + suffix; // read in the file to an image BufferedImage image = null; try { image = ImageIO.read(new File(inFile)); } catch (IOException exc) { exc.printStackTrace(); } progress.setValue(4 * i + 1); progress.setString("Resizing" + tail); // resize image int w, h; if (preserveAspect) { int ow = image.getWidth(); int oh = image.getHeight(); double oasp = (double) ow / oh; double tasp = (double) width / height; if (oasp > tasp) { w = width; h = (int) (w / oasp); } else { h = height; w = (int) (oasp * h); } } else { w = width; h = height; } Image resized = image.getScaledInstance(w, h, scaleType); progress.setValue(4 * i + 2); progress.setString("Painting" + tail); // create thumbnail BufferedImage thumb = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = thumb.createGraphics(); g2d.setColor(bg); g2d.fillRect(0, 0, width, height); g2d.drawImage(resized, (width - w) / 2, (height - h) / 2, this); g2d.dispose(); progress.setValue(4 * i + 3); progress.setString("Writing" + tail); // save thumbnail to disk File out = new File(outFile); File parent = out.getParentFile(); if (parent != null && !parent.exists()) parent.mkdirs(); try { ImageIO.write(thumb, suffix, out); } catch (IOException exc) { exc.printStackTrace(); } } list.setSelectedIndices(new int[0]); progress.setValue(4 * size); progress.setString("Complete"); }
public void run() { going = true; while (going) { String chose = null; synchronized (jobs) { chose = jobs.poll(); } if (chose != null) { cur = chose; updateStatus(); long time = System.currentTimeMillis(); String op = "export"; String targ = null; boolean success = false; if (chose.charAt(0) == IMPORT_FLAG) { String[] brk = chose.split(",", 4); // 4 parts to an import string File imp = new File(brk[1]); targ = imp.getName(); if (edtImport(imp, brk[2], brk[3])) { // import successful success = true; if (checkImports) op = "import & check"; else op = "import (fast)"; store.fireTableDataChanged(); } else { // no import } } else { String[] brk = chose.split(",", 3); // 3 parts to an export string File pla = new File(brk[2]); targ = pla.getName(); if (edtExport(new File(brk[1]), pla)) { // export succeeded success = true; // System.out.println(pla.getParentFile().getAbsolutePath() + ", " + // tempLoc.getAbsolutePath() + ", " + pla.getParentFile().equals(tempLoc)); try { if (pla.getParentFile().getCanonicalPath().equals(tempLoc.getCanonicalPath())) secureUse(pla); } catch (IOException exc) { System.err.println("Failed to retrieve canonical path?"); } } else { // export failed } } if (success) System.out.println( "Completed " + op + " in " + (System.currentTimeMillis() - time) + "ms - " + targ); cur = null; updateStatus(); } else { if (needsSave && idx == 0) { boolean alldone = true; for (int i = 0; i < numThreads; i++) { if (encryptDecryptThreads[i].getCur() != null) { alldone = false; break; } } if (alldone) { System.out.println("Automatically saving"); try { store.saveAll(tempLoc); } catch (IOException e) { System.err.println("Automatic save failed"); } needsSave = false; } } try { Thread.sleep(500); } catch (InterruptedException e) { // do nothing } } } }