protected int runEclipse(String message, File location, String[] args, File extensions) { File root = new File(Activator.getBundleContext().getProperty("java.home")); root = new File(root, "bin"); File exe = new File(root, "javaw.exe"); if (!exe.exists()) exe = new File(root, "java"); assertTrue("Java executable not found in: " + exe.getAbsolutePath(), exe.exists()); List<String> command = new ArrayList<String>(); Collections.addAll( command, new String[] { (new File(location == null ? output : location, getExeFolder() + "eclipse")) .getAbsolutePath(), "--launcher.suppressErrors", "-nosplash", "-vm", exe.getAbsolutePath() }); Collections.addAll(command, args); Collections.addAll(command, new String[] {"-vmArgs", "-Dosgi.checkConfiguration=true"}); // command-line if you want to run and allow a remote debugger to connect if (debug) Collections.addAll( command, new String[] { "-Xdebug", "-Xnoagent", "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8787" }); int result = run(message, command.toArray(new String[command.size()])); // 13 means that we wrote something out in the log file. // so try and parse it and fail via that message if we can. if (result == 13) parseExitdata(message); return result; }
/* * Set up the platform binary download and get it ready to run the tests. * This method is not intended to be called by clients, it will be called * automatically when the clients use a ReconcilerTestSuite. If the executable isn't * found on the file-system after the call, then we fail. */ public void initialize() throws Exception { initialized = false; File file = getPlatformZip(); output = getUniqueFolder(); toRemove.add(output); // for now we will exec to un-tar archives to keep the executable bits if (file.getName().toLowerCase().endsWith(".zip")) { try { FileUtils.unzipFile(file, output); } catch (IOException e) { fail("0.99", e); } } else { untar("1.0", file); } File exe = new File(output, getExeFolder() + "eclipse.exe"); if (!exe.exists()) { exe = new File(output, getExeFolder() + "eclipse"); if (!exe.exists()) fail( "Executable file: " + exe.getAbsolutePath() + "(or .exe) not found after extracting: " + file.getAbsolutePath() + " to: " + output); } initialized = true; }
public int runDirectorToInstall( String message, File installFolder, String sourceRepo, String iuToInstall) { String[] command = new String[] { // "-application", "org.eclipse.equinox.p2.director", // "-repository", sourceRepo, "-installIU", iuToInstall, // "-destination", installFolder.getAbsolutePath(), // "-bundlepool", installFolder.getAbsolutePath(), // "-roaming", "-profile", "PlatformProfile", "-profileProperties", "org.eclipse.update.install.features=true", // "-p2.os", Platform.getOS(), "-p2.ws", Platform.getWS(), "-p2.arch", Platform.getOSArch() }; return runEclipse(message, command); }
/** @param workTokDir Token directory (common for multiple nodes). */ private void cleanupResources(File workTokDir) { RandomAccessFile lockFile = null; FileLock lock = null; try { lockFile = new RandomAccessFile(new File(workTokDir, LOCK_FILE_NAME), "rw"); lock = lockFile.getChannel().lock(); if (lock != null) processTokenDirectory(workTokDir); else if (log.isDebugEnabled()) log.debug( "Token directory is being processed concurrently: " + workTokDir.getAbsolutePath()); } catch (OverlappingFileLockException ignored) { if (log.isDebugEnabled()) log.debug( "Token directory is being processed concurrently: " + workTokDir.getAbsolutePath()); } catch (FileLockInterruptionException ignored) { Thread.currentThread().interrupt(); } catch (IOException e) { U.error(log, "Failed to process directory: " + workTokDir.getAbsolutePath(), e); } finally { U.releaseQuiet(lock); U.closeQuiet(lockFile); } }
public int compare(Object o1, Object o2) { File f1 = (File) o1; File f2 = (File) o2; if (f1.isDirectory()) { if (f2.isDirectory()) { switch (mode) { // Filename or Type case 1: case 4: return sign * f1.getAbsolutePath() .toUpperCase() .compareTo(f2.getAbsolutePath().toUpperCase()); // Filesize case 2: return sign * (new Long(f1.length()).compareTo(new Long(f2.length()))); // Date case 3: return sign * (new Long(f1.lastModified()).compareTo(new Long(f2.lastModified()))); default: return 1; } } else return -1; } else if (f2.isDirectory()) return 1; else { switch (mode) { case 1: return sign * f1.getAbsolutePath().toUpperCase().compareTo(f2.getAbsolutePath().toUpperCase()); case 2: return sign * (new Long(f1.length()).compareTo(new Long(f2.length()))); case 3: return sign * (new Long(f1.lastModified()).compareTo(new Long(f2.lastModified()))); case 4: { // Sort by extension int tempIndexf1 = f1.getAbsolutePath().lastIndexOf('.'); int tempIndexf2 = f2.getAbsolutePath().lastIndexOf('.'); if ((tempIndexf1 == -1) && (tempIndexf2 == -1)) { // Neither have an extension return sign * f1.getAbsolutePath() .toUpperCase() .compareTo(f2.getAbsolutePath().toUpperCase()); } // f1 has no extension else if (tempIndexf1 == -1) return -sign; // f2 has no extension else if (tempIndexf2 == -1) return sign; // Both have an extension else { String tempEndf1 = f1.getAbsolutePath().toUpperCase().substring(tempIndexf1); String tempEndf2 = f2.getAbsolutePath().toUpperCase().substring(tempIndexf2); return sign * tempEndf1.compareTo(tempEndf2); } } default: return 1; } } }
/* * Untar the given file in the output directory. */ private void untar(String message, File file) { String name = file.getName(); File gzFile = new File(output, name); output.mkdirs(); run(message, new String[] {"cp", file.getAbsolutePath(), gzFile.getAbsolutePath()}); run(message, new String[] {"tar", "-zpxf", gzFile.getAbsolutePath()}); gzFile.delete(); }
// Derived from http://stackoverflow.com/a/3054692/250076 public static File getRelativeFile(File targetFile, File baseFile) { try { targetFile = targetFile.getCanonicalFile(); baseFile = baseFile.getCanonicalFile(); } catch (IOException ignored) { } String pathSeparator = File.separator; String basePath = baseFile.getAbsolutePath(); String normalizedTargetPath = normalize(targetFile.getAbsolutePath(), pathSeparator); String normalizedBasePath = normalize(basePath, pathSeparator); String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator)); String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator)); StringBuilder common = new StringBuilder(); int commonIndex = 0; while (commonIndex < target.length && commonIndex < base.length && target[commonIndex].equals(base[commonIndex])) { common.append(target[commonIndex]).append(pathSeparator); commonIndex++; } if (commonIndex == 0) { throw new Error( "No common path element found for '" + normalizedTargetPath + "' and '" + normalizedBasePath + '\''); } boolean baseIsFile = true; if (baseFile.exists()) { baseIsFile = baseFile.isFile(); } else if (basePath.endsWith(pathSeparator)) { baseIsFile = false; } StringBuilder relative = new StringBuilder(); if (base.length != commonIndex) { int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex; for (int i = 0; i < numDirsUp; i++) { relative.append("..").append(pathSeparator); } } relative.append(normalizedTargetPath.substring(common.length())); return new File(relative.toString()); }
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"); } }
private void loadObjects() throws ConfigurationException { if (!isExecutionMode()) { // Import objects from file system File objectsDirectory = new File(tangaraPath.getParentFile(), "objects"); System.out.println("using path " + objectsDirectory.getAbsolutePath()); // 1st Load libraries File libDirectory = new File(objectsDirectory, "lib"); File libraries[] = libDirectory.listFiles(); for (int i = 0; i < libraries.length; i++) { if (libraries[i].getName().endsWith(".jar")) { System.out.println("Loading library " + libraries[i].getName()); addClassPathToScriptEngine(libraries[i]); } } // 2nd load objects File objects[] = objectsDirectory.listFiles(); for (int i = 0; i < objects.length; i++) { if (objects[i].getName().endsWith(".jar")) { System.out.println("Loading object " + objects[i].getName()); addClassPathToScriptEngine(objects[i]); } } } // import the localized objects package importLocalizedObjectsPackage(); }
private boolean checkIfRequestedFileLegal(HtmlRequest htmlRequest) throws IOException { String requestedFileStr = htmlRequest.requestedFile; // Check if it is default if (requestedFileStr.equals("/")) { htmlRequest.requestedFile = "/" + defaultPage.toString(); requestedFileStr = htmlRequest.requestedFile; } String requestedFileFullPath = rootDirectory.getCanonicalPath() + requestedFileStr; File requestedFile = new File(requestedFileFullPath); // Checking that the requested file path is under the root directory if (!requestedFile.getAbsolutePath().startsWith(rootDirectory.getCanonicalPath())) { return false; } // Checking if it is a directory if (requestedFile.isDirectory()) { return false; } // Check if the file exists if (!requestedFile.exists()) { return false; } return true; }
public void loadProperty() { try { File file = new File(confFileName); log.debug("file=" + file.getAbsolutePath()); confProperties = new Properties(); confProperties.loadFromXML(new FileInputStream(file)); bonitaApiHost = confProperties.getProperty("bonita.api.host"); bonitaApiUsername = confProperties.getProperty("bonita.api.username"); bonitaApiPassword = confProperties.getProperty("bonita.api.password"); bonitaApiHttpUsername = confProperties.getProperty("bonita.api.http.username"); bonitaApiHttpPassword = confProperties.getProperty("bonita.api.http.password"); bonitaApiPath = confProperties.getProperty("bonita.api.path"); rallyApiHost = confProperties.getProperty("rally.api.host"); rallyApiHttpUsername = confProperties.getProperty("rally.api.http.username"); rallyApiHttpPassword = confProperties.getProperty("rally.api.http.password"); rallyProjectIds = confProperties.getProperty("rally.project.ids"); // bonitaProcessId=properties.getProperty("bonita.process.xp_code.id"); workflowServiceUrl = confProperties.getProperty("service.url"); } catch (Exception e) { log.error("", e); } }
public void setUp() throws Exception { super.setUp(); theDaemon = getMockLockssDaemon(); tempDir = getTempDir(); String tempDirPath = tempDir.getAbsolutePath(); System.setProperty("java.io.tmpdir", tempDirPath); Properties p = new Properties(); p.setProperty(IdentityManager.PARAM_IDDB_DIR, tempDirPath + "iddb"); p.setProperty(ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST, tempDirPath); p.setProperty(IdentityManager.PARAM_LOCAL_IP, "127.0.0.1"); p.setProperty(V3LcapMessage.PARAM_REPAIR_DATA_THRESHOLD, "4096"); ConfigurationUtil.setCurrentConfigFromProps(p); IdentityManager idmgr = theDaemon.getIdentityManager(); idmgr.startService(); mPollMgr = new MockPollManager(); theDaemon.setPollManager(mPollMgr); try { m_testID = idmgr.stringToPeerIdentity("127.0.0.1"); } catch (IOException ex) { fail("can't open test host 127.0.0.1: " + ex); } m_repairProps = new CIProperties(); m_repairProps.setProperty("key1", "val1"); m_repairProps.setProperty("key2", "val2"); m_repairProps.setProperty("key3", "val3"); m_testVoteBlocks = V3TestUtils.makeVoteBlockList(10); m_testMsg = this.makeTestVoteMessage(m_testVoteBlocks); }
String ls(String args[], boolean relative) { if (args.length < 2) throw new IllegalArgumentException( "the ${ls} macro must at least have a directory as parameter"); File dir = domain.getFile(args[1]); if (!dir.isAbsolute()) throw new IllegalArgumentException( "the ${ls} macro directory parameter is not absolute: " + dir); if (!dir.exists()) throw new IllegalArgumentException( "the ${ls} macro directory parameter does not exist: " + dir); if (!dir.isDirectory()) throw new IllegalArgumentException( "the ${ls} macro directory parameter points to a file instead of a directory: " + dir); Collection<File> files = new ArrayList<File>(new SortedList<File>(dir.listFiles())); for (int i = 2; i < args.length; i++) { Instructions filters = new Instructions(args[i]); files = filters.select(files, true); } List<String> result = new ArrayList<String>(); for (File file : files) result.add(relative ? file.getName() : file.getAbsolutePath()); return Processor.join(result, ","); }
void put(final URI uri, ArtifactData data) throws Exception { reporter.trace("put %s %s", uri, data); File tmp = createTempFile(repoDir, "mtp", ".whatever"); tmp.deleteOnExit(); try { copy(uri.toURL(), tmp); byte[] sha = SHA1.digest(tmp).digest(); reporter.trace("SHA %s %s", uri, Hex.toHexString(sha)); ArtifactData existing = get(sha); if (existing != null) { reporter.trace("existing"); xcopy(existing, data); return; } File meta = new File(repoDir, Hex.toHexString(sha) + ".json"); File file = new File(repoDir, Hex.toHexString(sha)); rename(tmp, file); reporter.trace("file %s", file); data.file = file.getAbsolutePath(); data.sha = sha; data.busy = false; CommandData cmddata = parseCommandData(data); if (cmddata.bsn != null) { data.name = cmddata.bsn + "-" + cmddata.version; } else data.name = Strings.display(cmddata.title, cmddata.bsn, cmddata.name, uri); codec.enc().to(meta).put(data); reporter.trace("TD = " + data); } finally { tmp.delete(); reporter.trace("puted %s %s", uri, data); } }
/** Related to issues [JACKSON-155], [#170]. */ public void testFile() throws Exception { // Not portable etc... has to do: File src = new File("/test").getAbsoluteFile(); String abs = src.getAbsolutePath(); // escape backslashes (for portability with windows) String json = MAPPER.writeValueAsString(abs); File result = MAPPER.readValue(json, File.class); assertEquals(abs, result.getAbsolutePath()); // Then #170 final ObjectMapper mapper2 = new ObjectMapper(); mapper2.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE); result = mapper2.readValue(json, File.class); assertEquals(abs, result.getAbsolutePath()); }
protected void addPathFile(final File pathComponent) throws IOException { if (!this.pathComponents.contains(pathComponent)) { this.pathComponents.addElement(pathComponent); } if (pathComponent.isDirectory()) { return; } final String absPathPlusTimeAndLength = pathComponent.getAbsolutePath() + pathComponent.lastModified() + "-" + pathComponent.length(); String classpath = AntClassLoader.pathMap.get(absPathPlusTimeAndLength); if (classpath == null) { JarFile jarFile = null; try { jarFile = new JarFile(pathComponent); final Manifest manifest = jarFile.getManifest(); if (manifest == null) { return; } classpath = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH); } finally { if (jarFile != null) { jarFile.close(); } } if (classpath == null) { classpath = ""; } AntClassLoader.pathMap.put(absPathPlusTimeAndLength, classpath); } if (!"".equals(classpath)) { final URL baseURL = AntClassLoader.FILE_UTILS.getFileURL(pathComponent); final StringTokenizer st = new StringTokenizer(classpath); while (st.hasMoreTokens()) { final String classpathElement = st.nextToken(); final URL libraryURL = new URL(baseURL, classpathElement); if (!libraryURL.getProtocol().equals("file")) { this.log( "Skipping jar library " + classpathElement + " since only relative URLs are supported by this" + " loader", 3); } else { final String decodedPath = Locator.decodeUri(libraryURL.getFile()); final File libraryFile = new File(decodedPath); if (!libraryFile.exists() || this.isInPath(libraryFile)) { continue; } this.addPathFile(libraryFile); } } } }
// function to do the compute use case public static void compute() throws Exception { HttpPost method = new HttpPost(url + "/compute"); method.setEntity(new StringEntity(username, "UTF-8")); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); connIp = client.execute(method, responseHandler); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } System.out.println("Give the file name which has to be put in the grid for computation"); // input of the file name to be computed BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String name = in.readLine(); // get the absolute path of the current working directory File directory = new File("."); String pwd = directory.getAbsolutePath(); // get present time date = new Date(); long start = date.getTime(); String cmd = "java -classpath " + pwd + "/vishwa/JVishwa.jar:. " + name + " " + connIp; System.out.println(cmd); // Execute the vishwa compute process Process p = Runtime.getRuntime().exec(cmd); // wait till the compute process is completed // check for the status code (0 for successful termination) int status = p.waitFor(); if (status == 0) { System.out.println("Compute operation successful. Check the directory for results"); } date = new Date(); long end = date.getTime(); long durationInt = end - start; String duration = String.valueOf(durationInt); method = new HttpPost(url + "/computeAck"); method.setEntity(new StringEntity(username + ";" + duration, "UTF-8")); try { client.execute(method); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } }
protected long getTotalFileSizeSupport(File file) throws TOTorrentException { String name = file.getName(); ///////////////////////////////////////// ///////////////////////////////////// if (name.equals(".") || name.equals("..")) { return (0); } if (!file.exists()) { throw (new TOTorrentException( "TOTorrentCreate: file '" + file.getName() + "' doesn't exist", TOTorrentException.RT_FILE_NOT_FOUND)); } if (file.isFile()) { if (!ignoreFile(name)) { total_file_count++; return (file.length()); } else { return (0); } } else { File[] dir_files = file.listFiles(); if (dir_files == null) { throw (new TOTorrentException( "TOTorrentCreate: directory '" + file.getAbsolutePath() + "' returned error when listing files in it", TOTorrentException.RT_FILE_NOT_FOUND)); } long length = 0; for (int i = 0; i < dir_files.length; i++) { length += getTotalFileSizeSupport(dir_files[i]); } return (length); } }
public void displayPage(JEditorPane pane, String text) { try { File helpFile = new File((String) locations.get(text)); String loc = "file:" + helpFile.getAbsolutePath(); URL page = new URL(loc); pane.setPage(page); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Help Topic Unavailable"); pane.getParent().repaint(); } }
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."); } }
/** Runs a Solaris installer */ public static boolean runSolarisInstaller(String installPath, File installFile) { /** Build temp. script file */ File script = null; boolean success = false; try { script = SolarisInstaller.createTempShellScript(); String[] args = new String[3]; args[0] = installPath; args[1] = script.getAbsolutePath(); args[2] = installFile.getAbsolutePath(); String execString = getExecuteString(args); success = SolarisInstaller.execute(execString); } catch (IOException ioe) { Config.trace("Got ioe: " + ioe); return false; } finally { if (script != null) script.delete(); } return success; }
private String createTemporaryPreinstallFile() { try { File tempFile = File.createTempFile("preinstall", null); tempFile.deleteOnExit(); InstallUtil.copyResourceToFile("/gnu/io/installer/resources/macosx/preinstall", tempFile); String absPath = tempFile.getAbsolutePath(); Process p = Runtime.getRuntime().exec(new String[] {"chmod", "a+x", absPath}); p.waitFor(); return absPath; } catch (Throwable t) { } return null; }
/** * Copies a file or directory * * @param src the file or directory to copy * @param dest where copy * @throws IOException */ public static void copyFile(File src, File dest) throws IOException { if (!src.exists()) throw new IOException("File not found '" + src.getAbsolutePath() + "'"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[4096]; int len; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); }
private static void deleteFileItem(FileItem fileItem, int scope) { if (logger.isDebugEnabled() && fileItem instanceof DiskFileItem) { final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation(); if (storeLocation != null) { final String temporaryFileName = storeLocation.getAbsolutePath(); final String scopeString = (scope == REQUEST_SCOPE) ? "request" : (scope == SESSION_SCOPE) ? "session" : "application"; logger.debug("Deleting temporary " + scopeString + "-scoped file: " + temporaryFileName); } } fileItem.delete(); }
private void addClassPathToScriptEngine(File jarFile) throws ConfigurationException { try { StringBuilder cmd = new StringBuilder(addClassPathCmd); int tagStartPos = cmd.indexOf(parameterTag); int tageEndPos = tagStartPos + parameterTag.length(); cmd.replace(tagStartPos, tageEndPos, jarFile.getAbsolutePath().replace("\\", "/")); // System.out.println("cmd " + cmd.toString()); engine.eval("add-classpath", 1, 1, cmd.toString()); // $NON-NLS-1$ } catch (Exception ex) { String msg = String.format("Failed to load class path %s", jarFile.getName()); // $NON-NLS-1$ System.err.println(msg + " " + ex); throw new ConfigurationException(msg, ex); } }
/** * Converts a dir string to a linked dir string * * @param dir the directory string (e.g. /usr/local/httpd) * @param browserLink web-path to Browser.jsp */ public static String dir2linkdir(String dir, String browserLink, int sortMode) { File f = new File(dir); StringBuffer buf = new StringBuffer(); while (f.getParentFile() != null) { if (f.canRead()) { String encPath = URLEncoder.encode(f.getAbsolutePath()); buf.insert( 0, "<a href=\"" + browserLink + "?sort=" + sortMode + "&dir=" + encPath + "\">" + conv2Html(f.getName()) + File.separator + "</a>"); } else buf.insert(0, conv2Html(f.getName()) + File.separator); f = f.getParentFile(); } if (f.canRead()) { String encPath = URLEncoder.encode(f.getAbsolutePath()); buf.insert( 0, "<a href=\"" + browserLink + "?sort=" + sortMode + "&dir=" + encPath + "\">" + conv2Html(f.getAbsolutePath()) + "</a>"); } else buf.insert(0, f.getAbsolutePath()); return buf.toString(); }
// Writes the program to a source file, compiles it, and runs it. private void compileAndRun(String fileName, String code) { // Exceptions here can pick and choose what font to use, as needed. // Exceptions thrown by the program, that cause the Playground to be unstable, should be in // blue. println("Deleting old temp files...", progErr); new File(fileName + ".java").delete(); new File(fileName + ".class").delete(); println("Creating source file...", progErr); file = new File(fileName + ".java"); println("Writing code to source file...", progErr); try { new FileWriter(file).append(code).close(); } catch (IOException i) { println("Had an IO Exception when trying to write the code. Stack trace:", error); i.printStackTrace(); return; // Exit on error } println("Compiling code...", progErr); // This should only ever be called if the JDK isn't installed. How you'd get here, I don't // know. if (compiler == null) { println("Fatal Error: JDK not installed. Go to java.sun.com and install.", error); return; } // Tries to compile. Success code is 0, so if something goes wrong, do stuff. int result = compiler.run( null, null, null, file .getAbsolutePath()); // Possibly add a new outputstream to parse through the // compiler errors if (result != 0) { displayLog(); println("Failed to compile.", error); return; // Return on error } println("Code compiled with 0 errors.", progErr); println("Attempting to run code...", progErr); run(fileName); }
/** * Jars up the run directory. * * @param run The run to jar up * @return The resulting jar file * @throws IOException Error creating the jar */ public static File jar(Run run) throws IOException { logger.info("Preparing run " + run.getRunId() + " for download."); String runId = run.getRunId(); String jarName = runId + ".jar"; File jar = new File(Config.TMP_DIR, jarName); String[] files = new File(Config.OUT_DIR, runId).list(); if (jar.exists()) jar.delete(); FileHelper.jar(Config.OUT_DIR + runId, files, jar.getAbsolutePath()); return jar; }
/** * @param data * @param target * @throws Exception * @throws IOException */ public String createService(ServiceData data) throws Exception, IOException { File sdir = new File(serviceDir, data.name); if (!sdir.exists() && !sdir.mkdirs()) { throw new IOException("Could not create directory " + data.sdir); } data.sdir = sdir.getAbsolutePath(); File lock = new File(data.sdir, LOCK); data.lock = lock.getAbsolutePath(); if (data.work == null) data.work = new File(data.sdir, "work").getAbsolutePath(); if (data.user == null) data.user = platform.user(); if (data.user == null) data.user = "******"; new File(data.work).mkdir(); if (data.log == null) data.log = new File(data.sdir, "log").getAbsolutePath(); // TODO // if (Data.validate(data) != null) // return "Invalid service data: " + Data.validate(data); if (service == null) throw new RuntimeException( "Missing biz.aQute.jpm.service in repo, should have been installed by init, try reiniting"); data.serviceLib = service.getAbsolutePath(); platform.chown(data.user, true, new File(data.sdir)); String s = platform.createService(data, null, false); if (s == null) storeData(new File(data.sdir, "data"), data); return s; }
@Nullable static IdeaPluginDescriptorImpl loadDescriptorFromDir(final File file, @NonNls String fileName) { IdeaPluginDescriptorImpl descriptor = null; File descriptorFile = new File(file, META_INF + File.separator + fileName); if (descriptorFile.exists()) { descriptor = new IdeaPluginDescriptorImpl(file); try { descriptor.readExternal(descriptorFile.toURI().toURL()); } catch (Exception e) { System.err.println("Cannot load: " + descriptorFile.getAbsolutePath()); e.printStackTrace(); } } return descriptor; }