/** * Starts a native process on the server * * @param command the command to start the process * @param dir the dir in which the process starts */ static String startProcess(String command, String dir) throws IOException { StringBuffer ret = new StringBuffer(); String[] comm = new String[3]; comm[0] = COMMAND_INTERPRETER[0]; comm[1] = COMMAND_INTERPRETER[1]; comm[2] = command; long start = System.currentTimeMillis(); try { // Start process Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir)); // Get input and error streams BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream()); BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream()); boolean end = false; while (!end) { int c = 0; while ((ls_err.available() > 0) && (++c <= 1000)) { ret.append(conv2Html(ls_err.read())); } c = 0; while ((ls_in.available() > 0) && (++c <= 1000)) { ret.append(conv2Html(ls_in.read())); } try { ls_proc.exitValue(); // if the process has not finished, an exception is thrown // else while (ls_err.available() > 0) ret.append(conv2Html(ls_err.read())); while (ls_in.available() > 0) ret.append(conv2Html(ls_in.read())); end = true; } catch (IllegalThreadStateException ex) { // Process is running } // The process is not allowed to run longer than given time. if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) { ls_proc.destroy(); end = true; ret.append("!!!! Process has timed out, destroyed !!!!!"); } try { Thread.sleep(50); } catch (InterruptedException ie) { } } } catch (IOException e) { ret.append("Error: " + e); } return ret.toString(); }
/** * Take a process, record its standard error and standard out streams, wait for it to finish * * @param process process to watch * @throws SecurityException if a security manager exists and its checkExec method doesn't allow * creation of a sub process. * @throws IOException - if an I/O error occurs * @throws NullPointerException - if cmdarray is null * @throws IndexOutOfBoundsException - if cmdarray is an empty array (has length 0). * @since ostermillerutils 1.06.00 */ private ExecHelper(Process process, String charset) throws IOException { StringBuffer output = new StringBuffer(); StringBuffer error = new StringBuffer(); Reader stdout; Reader stderr; if (charset == null) { // This is one time that the system charset is appropriate, // don't specify a character set. stdout = new InputStreamReader(process.getInputStream()); stderr = new InputStreamReader(process.getErrorStream()); } else { stdout = new InputStreamReader(process.getInputStream(), charset); stderr = new InputStreamReader(process.getErrorStream(), charset); } char[] buffer = new char[1024]; boolean done = false; boolean stdoutclosed = false; boolean stderrclosed = false; while (!done) { boolean readSomething = false; // read from the process's standard output if (!stdoutclosed && stdout.ready()) { readSomething = true; int read = stdout.read(buffer, 0, buffer.length); if (read < 0) { readSomething = true; stdoutclosed = true; } else if (read > 0) { readSomething = true; output.append(buffer, 0, read); } } // read from the process's standard error if (!stderrclosed && stderr.ready()) { int read = stderr.read(buffer, 0, buffer.length); if (read < 0) { readSomething = true; stderrclosed = true; } else if (read > 0) { readSomething = true; error.append(buffer, 0, read); } } // Check the exit status only we haven't read anything, // if something has been read, the process is obviously not dead yet. if (!readSomething) { try { this.status = process.exitValue(); done = true; } catch (IllegalThreadStateException itx) { // Exit status not ready yet. // Give the process a little breathing room. try { Thread.sleep(100); } catch (InterruptedException ix) { process.destroy(); throw new IOException("Interrupted - processes killed"); } } } } this.output = output.toString(); this.error = error.toString(); }
public static String getArchName() throws Exception { if (archName == null) { archName = "lin"; // bits Process process = Runtime.getRuntime().exec("uname -m"); process.waitFor(); if (process.exitValue() != 0) throw new Exception("Error arch"); BufferedReader inStream = new BufferedReader(new InputStreamReader(process.getInputStream())); String arch = inStream.readLine(); if (arch.equals("i686")) archName += "32"; else archName += "64"; process.destroy(); // SSE process = Runtime.getRuntime().exec("cat /proc/cpuinfo"); process.waitFor(); if (process.exitValue() != 0) throw new Exception("Error /proc/cpuinfo"); inStream = new BufferedReader(new InputStreamReader(process.getInputStream())); String line, cpuinfo = ""; while ((line = inStream.readLine()) != null) cpuinfo += line; String bestSSE = "sse"; String[] sses = {"sse2", "sse3", "ssse3", "sse4", "avx"}; for (int i = 0; i < sses.length; i++) { if (cpuinfo.indexOf(sses[i]) >= 0) bestSSE = sses[i]; } archName += bestSSE; process.destroy(); } return archName; }
/** * Gives the same basic functionality of File.exists but can be used to look for removable media * without showing a system dialog if the media is not present. Workaround pulled from the <A * HREF="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4089199"> bug report</A> on * bugs.sun.com. This bug was fixed in Java 6, and we can remove the workaround when we start * requiring Java 6. */ protected static boolean fileExists(File file) { try { Process process = Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", "dir", file.getAbsolutePath()}); // We need to consume all available output or the process will block. boolean haveExitCode = false; int exitCode = -1; InputStream out = process.getInputStream(); InputStream err = process.getErrorStream(); while (!haveExitCode) { while (out.read() >= 0) {} while (err.read() >= 0) {} try { exitCode = process.exitValue(); haveExitCode = true; } catch (IllegalThreadStateException e) { // Not yet complete. Thread.sleep(100); } } // int exitCode = process.waitFor(); return exitCode == 0; } catch (IOException e) { System.out.println("Unable to check for file: " + file + " : " + e); return false; } catch (InterruptedException e) { System.out.println("Unable to check for file. Interrupted: " + file + " : " + e); return false; } }
public static void logFile(String file, boolean isWrite) { ArrayList<String> cmds = new ArrayList<String>(); cmds.add(Dependencies.getPythonLocation()); cmds.add(Dependencies.getCLILocation()); cmds.add("--file"); cmds.add(file); String project = WakaTime.getProjectName(); if (project != null) { cmds.add("--project"); cmds.add(project); } cmds.add("--plugin"); cmds.add(IDE_NAME + "/" + IDE_VERSION + " " + IDE_NAME + "-wakatime/" + VERSION); if (isWrite) cmds.add("--write"); try { log.debug("Executing CLI: " + Arrays.toString(cmds.toArray())); Process proc = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()])); if (WakaTime.DEBUG) { BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); proc.waitFor(); String s; while ((s = stdInput.readLine()) != null) { log.debug(s); } while ((s = stdError.readLine()) != null) { log.debug(s); } log.debug("Command finished with return value: " + proc.exitValue()); } } catch (Exception e) { log.error(e); } }
@Test public void testUnpack() { String type = "unpack"; String path = "P:\\Ruby22-x64\\bin"; String dir = "P:\\temp-workspace\\RPGTestProject1"; try { Process process = Runtime.getRuntime() .exec(path + "\\rvpacker.bat --verbose -f -d " + dir + " -t ace -a " + type); new Thread( () -> { String line = null; int i = 0; try { BufferedReader bR = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = bR.readLine()) != null) { if (line.isEmpty()) { System.out.print("{E}"); } System.out.println(++i + ": " + line); } System.out.println("NULL got | Closing"); } catch (Exception e) { e.printStackTrace(); fail("Exception"); } }) .start(); new Thread( () -> { String line = null; try { BufferedReader bR = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((line = bR.readLine()) != null) { System.out.println("Err " + line); } System.out.println("NULL got"); } catch (Exception e) { e.printStackTrace(); fail("Exception"); } }) .start(); ; process.waitFor(); assertEquals(0, process.exitValue()); } catch (IOException e) { e.printStackTrace(); fail("Exception"); } catch (InterruptedException e) { e.printStackTrace(); fail("Exception"); } }
protected boolean compile(String fileName) { String compiler = "javac"; String classpathOption = "-classpath"; if (jikes != null) { compiler = jikes; classpathOption = "-bootclasspath"; } String[] args = new String[] { compiler, "-d", tmpdir, classpathOption, tmpdir + pathSep + CLASSPATH, tmpdir + "/" + fileName }; String cmdLine = compiler + " -d " + tmpdir + " " + classpathOption + " " + tmpdir + pathSep + CLASSPATH + " " + fileName; // System.out.println("compile: "+cmdLine); File outputDir = new File(tmpdir); try { Process process = Runtime.getRuntime().exec(args, null, outputDir); StreamVacuum stdout = new StreamVacuum(process.getInputStream()); StreamVacuum stderr = new StreamVacuum(process.getErrorStream()); stdout.start(); stderr.start(); process.waitFor(); stdout.join(); stderr.join(); if (stdout.toString().length() > 0) { System.err.println("compile stdout from: " + cmdLine); System.err.println(stdout); } if (stderr.toString().length() > 0) { System.err.println("compile stderr from: " + cmdLine); System.err.println(stderr); } int ret = process.exitValue(); return ret == 0; } catch (Exception e) { System.err.println("can't exec compilation"); e.printStackTrace(System.err); return false; } }
/** @param directory Directory where we list tags */ @Override protected void buildTagList(File directory) { this.tagList = new TreeSet<TagEntry>(); ArrayList<String> argv = new ArrayList<String>(); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); argv.add(cmd); argv.add("tags"); ProcessBuilder pb = new ProcessBuilder(argv); pb.directory(directory); Process process = null; BufferedReader in = null; try { process = pb.start(); in = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = in.readLine()) != null) { String parts[] = line.split(" *"); if (parts.length < 2) { throw new HistoryException("Tag line contains more than 2 columns: " + line); } // Grrr, how to parse tags with spaces inside? // This solution will loose multiple spaces;-/ String tag = parts[0]; for (int i = 1; i < parts.length - 1; ++i) { tag += " " + parts[i]; } TagEntry tagEntry = new BazaarTagEntry(Integer.parseInt(parts[parts.length - 1]), tag); // Bazaar lists multiple tags on more lines. We need to merge those into single TagEntry TagEntry higher = this.tagList.ceiling(tagEntry); if (higher != null && higher.equals(tagEntry)) { // Found in the tree, merge tags this.tagList.remove(higher); tagEntry.setTags(higher.getTags() + ", " + tag); } this.tagList.add(tagEntry); } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to read tag list: {0}", e.getMessage()); this.tagList = null; } catch (HistoryException e) { OpenGrokLogger.getLogger() .log(Level.WARNING, "Failed to parse tag list: {0}", e.getMessage()); this.tagList = null; } IOUtils.close(in); if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException e) { // the process is still running??? just kill it.. process.destroy(); } } }
public static String getCCName() throws Exception { if (ccName == null) { Process process = Runtime.getRuntime().exec("gcc -dumpversion"); process.waitFor(); if (process.exitValue() != 0) throw new Exception("Error gcc -dumpversion"); BufferedReader inStream = new BufferedReader(new InputStreamReader(process.getInputStream())); String[] list = inStream.readLine().split("\\."); ccName = "gcc" + list[0] + list[1] + "-mt"; process.destroy(); } return ccName; }
static int exec(String line, boolean showOutput, File dir) throws Exception { Process process = null; if (showOutput) { System.out.println("exec: " + line); } process = Runtime.getRuntime().exec("cmd /c " + line, null, dir); InputStream stdin = process.getInputStream(); InputStream stderr = process.getErrorStream(); StreamGobbler stdinGobbler = new StreamGobbler(stdin, "stdin: "); StreamGobbler stderrGobbler = new StreamGobbler(stderr, "stderr: "); stdinGobbler.start(); stderrGobbler.start(); process.waitFor(); if (showOutput) { System.out.println("exec \"" + line + "\" returned " + process.exitValue()); } return process.exitValue(); }
public static int ensureNTServiceIsRunning(String serviceName, String service) throws Exception { ArrayList<String> serviceList = getRunningNTServices(); if (serviceList == null) return -1; // not NT kernel? for (String svc : serviceList) { if (serviceName.equals(svc.trim())) return 0; // service already running } Process process = RUNTIME.exec(comSpec + "net start \"" + service + "\""); process.waitFor(); // wait for the process to complete int rc = process.exitValue(); // pick up its return code boolean success = (rc == 0); if (success) System.out.println("Successfully started service '" + serviceName + "'."); return (success ? 1 : -1); }
/* * Run the given command. */ protected static int run(String message, String[] commandArray) { try { Process process = Runtime.getRuntime().exec(commandArray, null, output); StreamProcessor.start(process.getErrorStream(), StreamProcessor.STDERR, true); StreamProcessor.start(process.getInputStream(), StreamProcessor.STDOUT, true); process.waitFor(); return process.exitValue(); } catch (IOException e) { fail(message, e); } catch (InterruptedException e) { fail(message, e); } return -1; }
@Override public boolean isAlive() { if (currentProcess == null) { return false; } // FIXME: Usage of exceptions isn't good approach try { int exitValue = currentProcess.exitValue(); return false; } catch (IllegalThreadStateException ex) { return false; } }
/** * Copies sourceFile into targetDir. * * @param sourceFile the full path name of the source file to be copied * @param targetDir the full path name of the target directory * @return the full path of the file in the new location, if the "copy" operation is successfull. * Otherwise, it returns null. */ public static String copyFile(String sourceFile, String targetDir) { String[] cmdArray = new String[3]; cmdArray[0] = "cp"; cmdArray[1] = sourceFile; cmdArray[2] = targetDir; Process p = OCSSWRunner.executeLocal(cmdArray, new File(targetDir)); if (p.exitValue() == 0) { return targetDir + sourceFile.substring(sourceFile.lastIndexOf(System.getProperty("file.separator"))); } else { System.out.println("This should not happen!"); return null; } }
/** * This method invokes wmic outside of the normal environment collection routines. * * <p>An initial call to wmic can be costly in terms of time. <code> * Details of why the first call is costly can be found at: * * http://support.microsoft.com/kb/290216/en-us * * "When you run the Wmic.exe utility for the first time, the utility * compiles its .mof files into the repository. To save time during * Windows installation, this operation takes place as necessary." * </code> */ private String getWmicResult(String alias, String verb, String property) { String res = ""; BufferedReader in = null; BufferedWriter bw = null; try { ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "WMIC", alias, verb, property); Process p = pb.start(); // need this for executing windows commands (at least // needed for executing wmic command) bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); bw.write(13); p.waitFor(); if (p.exitValue() == 0) { in = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = in.readLine()) != null) { line = line.trim(); if (line.length() == 0) { continue; } res = line; } // return the *last* line read return res; } } catch (Exception e) { // ignore the exception } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (bw != null) { try { bw.flush(); } catch (Exception ex) { // ignore... } try { bw.close(); } catch (Exception ex) { // ignore... } } } return res.trim(); }
private String getFullWmicResult(String alias, String verb, String property) { StringBuilder res = new StringBuilder(); BufferedReader in = null; BufferedWriter bw = null; try { ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "WMIC", alias, verb, property); Process p = pb.start(); // need this for executing windows commands (at least // needed for executing wmic command) bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); bw.write(13); bw.flush(); p.waitFor(); if (p.exitValue() == 0) { in = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = in.readLine()) != null) { line = line.trim(); if (line.length() == 0) { continue; } if (line.toLowerCase(Locale.US).indexOf(property.toLowerCase(Locale.US)) != -1) { continue; } res.append(line).append("\n"); } } } catch (Exception e) { // ignore the exception } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (bw != null) { try { bw.close(); } catch (IOException e) { // ignore } } } return res.toString(); }
static void realMain(String[] args) throws Throwable { // jmap doesn't work on Windows if (System.getProperty("os.name").startsWith("Windows")) return; final String childClassName = Job.class.getName(); final String classToCheckForLeaks = Job.classToCheckForLeaks(); final String uniqueID = String.valueOf(new Random().nextInt(Integer.MAX_VALUE)); final String[] jobCmd = { java, "-Xmx8m", "-classpath", System.getProperty("test.classes", "."), childClassName, uniqueID }; final Process p = new ProcessBuilder(jobCmd).start(); final String childPid = match( commandOutputOf(jps, "-m"), "(?m)^ *([0-9]+) +\\Q" + childClassName + "\\E *" + uniqueID + "$", 1); final int n0 = objectsInUse(p, childPid, classToCheckForLeaks); final int n1 = objectsInUse(p, childPid, classToCheckForLeaks); equal(p.waitFor(), 0); equal(p.exitValue(), 0); failed += p.exitValue(); // Check that no objects were leaked. System.out.printf("%d -> %d%n", n0, n1); check(Math.abs(n1 - n0) < 2); // Almost always n0 == n1 check(n1 < 20); drainers.shutdown(); }
static String outputOf(final Process p) { try { Future<String> outputFuture = futureOutputOf(p.getInputStream()); Future<String> errorFuture = futureOutputOf(p.getErrorStream()); final String output = outputFuture.get(); final String error = errorFuture.get(); // Check for successful process completion equal(error, ""); equal(p.waitFor(), 0); equal(p.exitValue(), 0); return output; } catch (Throwable t) { unexpected(t); throw new Error(t); } }
/** Execute the process and return when the process is complete. */ public void exec() throws IOException { Runtime rt = Runtime.getRuntime(); try { Process proc = rt.exec(commandLine); OutputStream os = rt.getLocalizedOutputStream(proc.getOutputStream()); if (this.observer instanceof RefEnv) { os.write("quit();\n".getBytes()); } os.flush(); os.close(); InputStreamReader is; is = new InputStreamReader(proc.getErrorStream()); (new Thread(new StreamReader(error, is))).start(); is = new InputStreamReader(proc.getInputStream()); (new Thread(new StreamReader(input, is))).start(); proc.waitFor(); exitValue = proc.exitValue(); // unfortunately the following pause seems to // need to be here otherwise we get a crash // On AIX, Process.waitFor() doesn't seem to wait for // the process to complete before continuing. Bad. // Need to find a workaround. if (System.getProperty("os.name").startsWith("AIX") || System.getProperty("os.name").startsWith("HP")) { pause(20000); } else { pause(10000); } } catch (Exception e) { java.lang.System.out.println(e); e.printStackTrace(); } }
@Override public InputStream getHistoryGet(String parent, String basename, String rev) { InputStream ret = null; File directory = new File(directoryName); Process process = null; try { String filename = (new File(parent, basename)).getCanonicalPath().substring(directoryName.length() + 1); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); String argv[] = {cmd, "cat", "-r", rev, filename}; process = Runtime.getRuntime().exec(argv, null, directory); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[32 * 1024]; InputStream in = process.getInputStream(); int len; while ((len = in.read(buffer)) != -1) { if (len > 0) { out.write(buffer, 0, len); } } ret = new ByteArrayInputStream(out.toByteArray()); } catch (Exception exp) { OpenGrokLogger.getLogger() .log(Level.SEVERE, "Failed to get history: " + exp.getClass().toString(), exp); } finally { // Clean up zombie-processes... if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException exp) { // the process is still running??? just kill it.. process.destroy(); } } } return ret; }
/** * Checks if address can be reached using one argument InetAddress.isReachable() version or ping * command if failed. * * @param addr Address to check. * @param reachTimeout Timeout for the check. * @return {@code True} if address is reachable. */ public static boolean reachableByPing(InetAddress addr, int reachTimeout) { try { if (addr.isReachable(reachTimeout)) return true; String cmd = String.format("ping -%s 1 %s", U.isWindows() ? "n" : "c", addr.getHostAddress()); Process myProc = Runtime.getRuntime().exec(cmd); myProc.waitFor(); return myProc.exitValue() == 0; } catch (IOException ignore) { return false; } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); return false; } }
private static String retrieveOFileNameLocal(String[] cmdArray, String ifileDir) { Process process = OCSSWRunner.execute(cmdArray, new File(ifileDir)); if (process == null) { return "output"; } int exitCode = process.exitValue(); InputStream is; if (exitCode == 0) { is = process.getInputStream(); } else { is = process.getErrorStream(); } InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); try { if (exitCode == 0) { String line; while ((line = br.readLine()) != null) { if (line.startsWith(NEXT_LEVEL_FILE_NAME_TOKEN)) { return (line.substring(NEXT_LEVEL_FILE_NAME_TOKEN.length())).trim(); } } } else { debug("Failed exit code on program '" + NEXT_LEVEL_NAME_FINDER_PROGRAM_NAME + "'"); } } catch (IOException ioe) { VisatApp.getApp().showErrorDialog(ioe.getMessage()); } // int choice = VisatApp.getApp().showQuestionDialog("ofile computation", "ofile name is // not found", true, "continue"); // // return String.valueOf(choice); return "output"; }
public int compileJavaProgram(JavaProgram jp, String writeDirectory, String classpath) throws Exception { if (!jp.isTypeResolved()) { System.out.println( "Compilation will not take place since there were type resolution errors."); return -1; } String fileList = jp.getFilesAsString(); String command = "javac -d " + writeDirectory + " -classpath " + classpath + " " + fileList; // System.out.println(command); System.out.print("Compiling..."); Process p = Runtime.getRuntime().exec(command); // need to squirt the output into the InputStream is = p.getErrorStream(); Util.read(is, "compiler"); // blocks here int exitValue = p.exitValue(); return exitValue; }
private static String getNextLevelFileName(String ifileName, String[] cmdArray) { String ifileDir = ifileName.substring(0, ifileName.lastIndexOf(System.getProperty("file.separator"))); Process process = OCSSWRunner.execute(cmdArray, new File(ifileDir)); if (process == null) { return null; } int exitCode = process.exitValue(); InputStream is; if (exitCode == 0) { is = process.getInputStream(); } else { is = process.getErrorStream(); } InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); try { if (exitCode == 0) { String line; while ((line = br.readLine()) != null) { if (line.startsWith(NEXT_LEVEL_FILE_NAME_TOKEN)) { return (line.substring(NEXT_LEVEL_FILE_NAME_TOKEN.length())).trim(); } } } else { debug("Failed exit code on program '" + cmdArray[5] + "'"); } } catch (IOException ioe) { VisatApp.getApp().showErrorDialog(ioe.getMessage()); } return null; }
public static int executeCommand(String completeCommand, PrintWriter out) { try { Process p = Runtime.getRuntime().exec(completeCommand); if (out != null) { BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = in.readLine(); while (line != null) { out.println(line); line = in.readLine(); } in.close(); out.flush(); } p.waitFor(); int status = p.exitValue(); p.destroy(); return status; } catch (Exception e) { e.printStackTrace(); System.exit(1); return -1; } }
public static void main(String args[]) { int PC, SP, IR, AC, X, Y; int[] memory = new int[1000]; SP = IR = AC = X = Y = 0; PC = -1; // Gets "MainMemory" class from working directory. String directory = System.getProperty("user.dir") + "\\bin\\ MainMemory"; Scanner in = new Scanner(System.in); try { int x, y, index = 0; String z = ""; Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("java -cp " + directory); // Process proc = rt.exec("cat Hello.java"); InputStream os = proc.getInputStream(); IR = 0; // GRABS INSTRUCTION OUT OF STREAM while ((x = os.read()) != -1) { try { if (x > 47 && x < 58) { y = Character.getNumericValue(x); z += y; } else if (x == 10 && z != "") { x = Integer.parseInt(z); y = 0; z = ""; // System.out.println(x); memory[index] = x; index++; } else if (x == 13) { break; } } catch (Exception e) { System.out.println("ERROR: Error while reading instructions."); System.exit(1); } } // PERFORMS INSTRUCTIONS for (int k = 0; k < index; k++) { // System.out.println(k + " == " + memory[k]); IR = memory[k]; switch (IR) { case 1: // System.out.println("LOAD VALUE"); //READS IN THE VALUE PC++; k++; AC = memory[k]; PC++; break; case 2: // System.out.println("LOAD ADDR"); //READS VALUE FROM AN ADDRESS PC++; AC = memory[memory[k + 1]]; k++; break; case 3: // System.out.println("STORE ADDR"); //WRITES THE VALUE OF AC TO THE ADDRESS PC++; memory[memory[k + 1]] = AC; k++; try { File file = new File(System.getProperty("user.dir") + "\\src\\program.txt"); FileWriter fw = new FileWriter(file); BufferedWriter out = new BufferedWriter(fw); for (int i = 0; i < index; i++) { out.write("" + memory[i]); out.newLine(); } out.flush(); out.close(); } catch (IOException e) { System.out.println("ERROR: Could not rewrite program"); } break; case 4: // System.out.println("ADD X"); //ADDS X TO AC PC++; AC += X; break; case 5: // System.out.println("ADD Y"); //ADDS Y TO AC PC++; AC += Y; break; case 6: // System.out.println("SUB X"); //SUBSTRACTS X FROM AC PC++; AC -= X; break; case 7: // System.out.println("SUB Y"); //SUBTRACTS Y FROM AC PC++; AC -= Y; break; case 8: // System.out.println("GET PORT"); //RECEIVES EITHER INTEGER OR CHARACTER DEPENDING ON // PORT NUMBER, 1 OR 2 PC++; k++; if (memory[k] == 1) { PC++; // System.out.println("PORT = READ INT"); //RECEIVES INTEGER FROM USER AND PLACES IT // INTO AC AC = in.nextInt(); } else if (memory[k] == 2) // RECEIVES CHARACTER FROM USER AND PLACES IT INTO AC { PC++; // System.out.println("PORT = READ CHAR"); AC = (int) in.next(".{1}").charAt(0); } break; case 9: // System.out.println("PUT PORT"); //PRINTS EITHER INTEGER OR CHARACTER DEPENDING ON // PORT NUMBER, 1 OR 2 PC++; k++; if (memory[k] == 1) { // System.out.println("PORT = WRITE INT"); PRINTS OUT INTEGER VALUE FROM AC PC++; System.out.print(AC); } else if (memory[k] == 2) { // System.out.println("PORT = WRITE CHAR"); //PRINTS OUT CHARACTER VALUE FROM AC PC++; System.out.print((char) AC); } break; case 10: // System.out.println("COPYTO X"); //COPIES VALUE FROM X INTO AC PC++; X = AC; break; case 11: // System.out.println("COPYTO Y"); //COPIES VALUE FROM Y INTO AC PC++; Y = AC; break; case 12: // System.out.println("COPYFROM X"); //COPIES VALUE FROM X INTO AC PC++; AC = X; break; case 13: // System.out.println("COPYFROM Y"); //COPIES VALUE FROM Y INTO AC PC++; AC = Y; break; case 14: // System.out.println("JUMP ADDR"); //JUMPS TO AN ADDRESS PC++; k = memory[k + 1] - 1; break; case 15: // System.out.println("JUMPIFEQUAL ADDR"); //JUMPS TO AN ADDRESS IF AC IS EQUAL TO ZERO PC++; if (AC == 0) { PC++; k = memory[k + 1] - 1; } else { PC++; k++; } break; case 16: // System.out.println("JUMPIFNOTEQUAL ADDR"); //JUMPS TO AN ADDRESS IF AC IS NOT EQUAL // TO ZERO PC++; if (AC != 0) { PC++; k = memory[k + 1] - 1; } else { PC++; k++; } break; case 17: // System.out.println("CALL ADDR"); // PUSH RETURN ADDRESS INTO STACK, AND JUMPS AN // ADDRESS PC++; SP = PC; k = memory[k + 1] - 1; PC++; break; case 18: // System.out.println("RETURN"); //POPS RETURN ADDRESS FROM STACK, AND JUMPS TO IT PC++; k = SP + 1; break; case 19: // System.out.println("INC X"); //INCREMENTS VALUE IN X BY ONE PC++; X++; break; case 20: // System.out.println("DEC X"); //DECREMENTS VALUE IN X BY ONE PC++; X--; break; case 30: // System.out.println("END"); //ENDS PROCESS PC++; X = 0; Y = 0; AC = 0; k = index; try { os.close(); } catch (Exception e) { } break; } // System.out.println("\nProgram Counter: " + PC); } // PROCESS ENDS proc.waitFor(); in.close(); int exitVal = proc.exitValue(); System.out.println("\nProcess exited: " + exitVal); } catch (Throwable t) { t.printStackTrace(); } System.exit(1); }
/** * Reads the next line from the process. This method will be used only if the supporting Java * Native Interface library could not be loaded. */ private synchronized String pure_readLine() { String line; long current, timeout = ((new Date()).getTime()) + threshold; if (null == p || null == in || null == err) return null; // Debug.verbose("P4Process.readLine()"); try { for (; ; ) { if (null == p || null == in || null == err) { Debug.error("P4Process.readLine(): Something went null"); return null; } current = (new Date()).getTime(); if (current >= timeout) { Debug.error("P4Process.readLine(): Timeout"); // If this was generating a new object from stdin, return an // empty string. Otherwise, return null. for (int i = 0; i < new_cmd.length; i++) { if (new_cmd[i].equals("-i")) return ""; } return null; } // Debug.verbose("P4Process.readLine().in: "+in); try { /** * If there's something coming in from stdin, return it. We assume that the p4 command was * called with -s which sends all messages to standard out pre-pended with a string that * indicates what kind of messsage it is error warning text info exit */ // Some errors still come in on Standard error while (err.ready()) { line = err.readLine(); if (null != line) { addP4Error(line + "\n"); } } if (in.ready()) { line = in.readLine(); Debug.verbose("From P4:" + line); if (line.startsWith("error")) { if (!line.trim().equals("") && (-1 == line.indexOf("up-to-date")) && (-1 == line.indexOf("no file(s) to resolve"))) { addP4Error(line); } } else if (line.startsWith("warning")) { } else if (line.startsWith("text")) { } else if (line.startsWith("info")) { } else if (line.startsWith("exit")) { int exit_code = new Integer(line.substring(line.indexOf(" ") + 1, line.length())).intValue(); if (0 == exit_code) { Debug.verbose("P4 Exec Complete."); } else { Debug.error("P4 exited with an Error!"); } return null; } if (!raw) line = line.substring(line.indexOf(":") + 1).trim(); Debug.verbose("P4Process.readLine(): " + line); return line; } } catch (NullPointerException ne) { } // If there's nothing on stdin or stderr, check to see if the // process has exited. If it has, return null. try { exit_code = p.exitValue(); return null; } catch (IllegalThreadStateException ie) { Debug.verbose("P4Process: Thread is not done yet."); } // Sleep for a second, so this thread can't become a CPU hog. try { Debug.verbose("P4Process: Sleeping..."); Thread.sleep(100); // Sleep for 1/10th of a second. } catch (InterruptedException ie) { } } } catch (IOException ex) { return null; } }
public synchronized RenderedImage runDCRaw(dcrawMode mode, boolean secondaryPixels) throws IOException, UnknownImageTypeException, BadImageFileException { if (!m_decodable || (mode == dcrawMode.full && m_rawColors != 3)) throw new UnknownImageTypeException("Unsuported Camera"); RenderedImage result = null; File of = null; try { if (mode == dcrawMode.preview) { if (m_thumbWidth >= 1024 && m_thumbHeight >= 768) { mode = dcrawMode.thumb; } } long t1 = System.currentTimeMillis(); of = File.createTempFile("LZRAWTMP", ".ppm"); boolean four_colors = false; final String makeModel = m_make + ' ' + m_model; for (String s : four_color_cameras) if (s.equalsIgnoreCase(makeModel)) { four_colors = true; break; } if (secondaryPixels) runDCRawInfo(true); String cmd[]; switch (mode) { case full: if (four_colors) cmd = new String[] { DCRAW_PATH, "-F", of.getAbsolutePath(), "-v", "-f", "-H", "1", "-t", "0", "-o", "0", "-4", m_fileName }; else if (m_filters == -1 || (m_make != null && m_make.equalsIgnoreCase("SIGMA"))) cmd = new String[] { DCRAW_PATH, "-F", of.getAbsolutePath(), "-v", "-H", "1", "-t", "0", "-o", "0", "-4", m_fileName }; else if (secondaryPixels) cmd = new String[] { DCRAW_PATH, "-F", of.getAbsolutePath(), "-v", "-j", "-H", "1", "-t", "0", "-s", "1", "-d", "-4", m_fileName }; else cmd = new String[] { DCRAW_PATH, "-F", of.getAbsolutePath(), "-v", "-j", "-H", "1", "-t", "0", "-d", "-4", m_fileName }; break; case preview: cmd = new String[] { DCRAW_PATH, "-F", of.getAbsolutePath(), "-v", "-t", "0", "-o", "1", "-w", "-h", m_fileName }; break; case thumb: cmd = new String[] {DCRAW_PATH, "-F", of.getAbsolutePath(), "-v", "-e", m_fileName}; break; default: throw new IllegalArgumentException("Unknown mode " + mode); } String ofName = null; synchronized (DCRaw.class) { Process p = null; InputStream dcrawStdErr; InputStream dcrawStdOut; if (ForkDaemon.INSTANCE != null) { ForkDaemon.INSTANCE.invoke(cmd); dcrawStdErr = ForkDaemon.INSTANCE.getStdErr(); dcrawStdOut = ForkDaemon.INSTANCE.getStdOut(); } else { p = Runtime.getRuntime().exec(cmd); dcrawStdErr = new BufferedInputStream(p.getErrorStream()); dcrawStdOut = p.getInputStream(); } String line, args; // output expected on stderr while ((line = readln(dcrawStdErr)) != null) { // System.out.println(line); if ((args = match(line, DCRAW_OUTPUT)) != null) ofName = args.substring(0, args.indexOf(" ...")); } // Flush stdout just in case... while ((line = readln(dcrawStdOut)) != null) ; // System.out.println(line); if (p != null) { dcrawStdErr.close(); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } m_error = p.exitValue(); p.destroy(); } else m_error = 0; } System.out.println("dcraw value: " + m_error); if (m_error > 0) { of.delete(); throw new BadImageFileException(of); } if (!ofName.equals(of.getPath())) { of.delete(); of = new File(ofName); } if (of.getName().endsWith(".jpg") || of.getName().endsWith(".tiff")) { if (of.getName().endsWith(".jpg")) { try { LCJPEGReader jpegReader = new LCJPEGReader(of.getPath()); result = jpegReader.getImage(); } catch (Exception e) { e.printStackTrace(); } } else { try { LCTIFFReader tiffReader = new LCTIFFReader(of.getPath()); result = tiffReader.getImage(null); } catch (Exception e) { e.printStackTrace(); } } long t2 = System.currentTimeMillis(); int totalData = result.getWidth() * result.getHeight() * result.getColorModel().getNumColorComponents() * (result.getColorModel().getTransferType() == DataBuffer.TYPE_BYTE ? 1 : 2); System.out.println("Read " + totalData + " bytes in " + (t2 - t1) + "ms"); } else { ImageData imageData; try { imageData = readPPM(of); } catch (Exception e) { e.printStackTrace(); throw new BadImageFileException(of, e); } // do not change the initial image geometry // m_width = Math.min(m_width, imageData.width); // m_height = Math.min(m_height, imageData.height); long t2 = System.currentTimeMillis(); int totalData = imageData.width * imageData.height * imageData.bands * (imageData.dataType == DataBuffer.TYPE_BYTE ? 1 : 2); System.out.println("Read " + totalData + " bytes in " + (t2 - t1) + "ms"); final ColorModel cm; if (mode == dcrawMode.full) { if (imageData.bands == 1) { cm = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), false, false, Transparency.OPAQUE, DataBuffer.TYPE_USHORT); } else { cm = JAIContext.colorModel_linear16; } } else { if (imageData.bands == 3) cm = new ComponentColorModel( JAIContext.sRGBColorSpace, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); else if (imageData.bands == 4) cm = new ComponentColorModel( JAIContext.CMYKColorSpace, false, false, Transparency.OPAQUE, imageData.dataType); else throw new UnknownImageTypeException("Weird number of bands: " + imageData.bands); } final DataBuffer buf = imageData.dataType == DataBuffer.TYPE_BYTE ? new DataBufferByte( (byte[]) imageData.data, imageData.bands * imageData.width * imageData.height) : new DataBufferUShort( (short[]) imageData.data, imageData.bands * imageData.width * imageData.height); final WritableRaster raster = Raster.createInterleavedRaster( buf, imageData.width, imageData.height, imageData.bands * imageData.width, imageData.bands, imageData.bands == 3 ? new int[] {0, 1, 2} : new int[] {0}, null); result = new BufferedImage(cm, raster, false, null); } } catch (IOException e) { if (of != null) of.delete(); throw e; } finally { if (of != null) of.delete(); } return result; }
/** * The first invocation of this test starts a loop which exhaustively tests the object tree with * all of its different settings. There are 7 test objects in a tree that has 7 different places * to set assertions untouched/on/off so this tests 3^7 or 2187 different configurations. * * <p>This test spawns a new VM for each run because assertions are set on or off at class load * time. Once the class is loaded its assertion status does not change. */ public static void main(String[] args) throws Exception { // Switch values: 0=don't touch, 1=off, 2 = on int[] switches = new int[7]; int switchSource = 0; if (args.length == 0) { // This is master version // This code is for an exhaustive test // while(switchSource < 2187) { // int temp = switchSource++; // This code is for a weaker but faster test for (int x = 0; x < 100; x++) { int temp = generator.nextInt(2187); for (int i = 0; i < 7; i++) { switches[i] = temp % 3; temp = temp / 3; } // Spawn new VM and load classes String command = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java Assert"; StringBuffer commandString = new StringBuffer(command); for (int j = 0; j < 7; j++) commandString.append(" " + switches[j]); Process p = null; p = Runtime.getRuntime().exec(commandString.toString()); if (debug) { // See output of test VMs BufferedReader blah = new BufferedReader(new InputStreamReader(p.getInputStream())); String outString = blah.readLine(); while (outString != null) { System.out.println("from slave:" + outString); outString = blah.readLine(); } } p.waitFor(); int result = p.exitValue(); if (debug) { // See which switch configs failed if (result == 0) { for (int k = 6; k >= 0; k--) System.out.print(switches[k]); System.out.println(); } else { System.out.print("Nonzero Exit: "); for (int k = 6; k >= 0; k--) System.out.print(switches[k]); System.out.println(); } } else { if (result != 0) { System.err.print("Nonzero Exit: "); for (int k = 6; k >= 0; k--) System.err.print(switches[k]); System.err.println(); throw new RuntimeException("Assertion test failure."); } } } } else { // This is a test spawn for (int i = 0; i < 7; i++) switches[i] = Integer.parseInt(args[i]); SetAssertionSwitches(switches); ConstructClassTree(); TestClassTree(switches); } }
private void runDCRawInfo(boolean secondary) throws IOException { String info[] = {DCRAW_PATH, "-v", "-i", "-t", "0", m_fileName}; String secondaryInfo[] = {DCRAW_PATH, "-v", "-i", "-s", "1", "-t", "0", m_fileName}; synchronized (DCRaw.class) { Process p = null; InputStream dcrawStdOut; InputStream dcrawStdErr; if (ForkDaemon.INSTANCE != null) { ForkDaemon.INSTANCE.invoke(secondary ? secondaryInfo : info); dcrawStdOut = ForkDaemon.INSTANCE.getStdOut(); dcrawStdErr = ForkDaemon.INSTANCE.getStdErr(); } else { p = Runtime.getRuntime().exec(secondary ? secondaryInfo : info); dcrawStdOut = p.getInputStream(); dcrawStdErr = new BufferedInputStream(p.getErrorStream()); } // output expected on stdout String line, args; while ((line = readln(dcrawStdOut)) != null) { // System.out.println(line); String search; if (secondary) { if (line.startsWith(search = CAMERA_MULTIPLIERS)) { String multipliers[] = line.substring(search.length()).split("\\s"); m_secondary_cam_mul[0] = Float.parseFloat(multipliers[0]); m_secondary_cam_mul[1] = Float.parseFloat(multipliers[1]); m_secondary_cam_mul[2] = Float.parseFloat(multipliers[2]); m_secondary_cam_mul[3] = Float.parseFloat(multipliers[3]); } } else { // if (line.startsWith(search = FILENAME)) { // String filename = line.substring(search.length()); // } else if (line.startsWith(search = TIMESTAMP)) { String timestamp = line.substring(search.length()); try { m_captureDateTime = new SimpleDateFormat().parse(timestamp).getTime(); } catch (ParseException e) { m_captureDateTime = 0; } } else if (line.startsWith(search = CAMERA)) { String camera = line.substring(search.length()); m_make = camera.substring(0, camera.indexOf(' ')); m_model = camera.substring(m_make.length() + 1); } else if (line.startsWith(search = ISO)) { String iso = line.substring(search.length()); m_iso = Integer.decode(iso); } else if (line.startsWith(search = SHUTTER)) { String shutterSpeed = line.substring(search.length() + 2); float exposureTime = 0; try { exposureTime = Float.valueOf(shutterSpeed.substring(0, shutterSpeed.indexOf(" sec"))); if (exposureTime != 0) m_shutterSpeed = 1 / exposureTime; } catch (NumberFormatException e) { } } else if (line.startsWith(search = APERTURE)) { String aperture = line.substring(search.length() + 2); try { m_aperture = Float.valueOf(aperture); } catch (NumberFormatException e) { } } else if (line.startsWith(search = FOCAL_LENGTH)) { String focalLenght = line.substring(search.length()); try { m_focalLength = Float.valueOf(focalLenght.substring(0, focalLenght.indexOf(" mm"))); } catch (NumberFormatException e) { } // } else if (line.startsWith(search = NUM_RAW_IMAGES)) { // String numRawImages = line.substring(search.length()); // } else if (line.startsWith(search = EMBEDDED_ICC_PROFILE)) { // String embeddedICCProfile = line.substring(search.length()); } else if (line.startsWith(CANNOT_DECODE)) { m_decodable = false; } else if ((args = match(line, THUMB_SIZE)) != null) { String sizes[] = args.split(" x "); m_thumbWidth = Integer.decode(sizes[0]); m_thumbHeight = Integer.decode(sizes[1]); } else if ((args = match(line, FULL_SIZE)) != null) { String sizes[] = args.split(" x "); m_fullWidth = Integer.decode(sizes[0]); m_fullHeight = Integer.decode(sizes[1]); } else if ((args = match(line, IMAGE_SIZE)) != null) { String sizes[] = args.split(" x "); m_rawWidth = Integer.decode(sizes[0]); m_rawHeight = Integer.decode(sizes[1]); } else if ((args = match(line, OUTPUT_SIZE)) != null) { String sizes[] = args.split(" x "); m_width = Integer.decode(sizes[0]); m_height = Integer.decode(sizes[1]); } else if (line.startsWith(search = RAW_COLORS)) { String rawColors = line.substring(search.length()); m_rawColors = Integer.decode(rawColors); } else if (line.startsWith(search = FILTER_PATTERN)) { String pattern = line.substring(search.length()); if (pattern.length() >= 8 && !pattern.substring(0, 4).equals(pattern.substring(4, 8))) m_filters = -1; else if (pattern.startsWith("BGGR")) m_filters = 0x16161616; else if (pattern.startsWith("GRBG")) m_filters = 0x61616161; else if (pattern.startsWith("GBRG")) m_filters = 0x49494949; else if (pattern.startsWith("RGGB")) m_filters = 0x94949494; else m_filters = -1; } else if (line.startsWith(search = DAYLIGHT_MULTIPLIERS)) { String multipliers[] = line.substring(search.length()).split("\\s"); m_pre_mul[0] = Float.parseFloat(multipliers[0]); m_pre_mul[1] = Float.parseFloat(multipliers[1]); m_pre_mul[2] = Float.parseFloat(multipliers[2]); m_pre_mul[3] = m_pre_mul[1]; } else if (line.startsWith(search = CAMERA_MULTIPLIERS)) { String multipliers[] = line.substring(search.length()).split("\\s"); m_cam_mul[0] = Float.parseFloat(multipliers[0]); m_cam_mul[1] = Float.parseFloat(multipliers[1]); m_cam_mul[2] = Float.parseFloat(multipliers[2]); m_cam_mul[3] = Float.parseFloat(multipliers[3]); } else if (line.startsWith(CAMERA_RGB_PROFILE)) { String rgb_cam[] = line.substring(CAMERA_RGB_PROFILE.length()).split("\\s"); m_rgb_cam = new float[9]; for (int i = 0; i < 9; i++) { m_rgb_cam[i] = Float.parseFloat(rgb_cam[i]); } } else if (line.startsWith(CAMERA_XYZ_PROFILE)) { String xyz_cam[] = line.substring(CAMERA_XYZ_PROFILE.length()).split("\\s"); m_xyz_cam = new float[9]; for (int i = 0; i < 9; i++) { m_xyz_cam[i] = Float.parseFloat(xyz_cam[i]); } } } } // Flush stderr just in case... while ((line = readln(dcrawStdErr)) != null) ; // System.out.println(line); if (p != null) { dcrawStdOut.close(); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } m_error = p.exitValue(); p.destroy(); } else m_error = 0; } }