protected void runScript(String[] cmd, JTextArea txaMsg) { String strg = ""; if (cmd == null) return; Process prcs = null; try { Messages.postDebug("Running script: " + cmd[2]); Runtime rt = Runtime.getRuntime(); prcs = rt.exec(cmd); if (prcs == null) return; InputStream istrm = prcs.getInputStream(); if (istrm == null) return; BufferedReader bfr = new BufferedReader(new InputStreamReader(istrm)); while ((strg = bfr.readLine()) != null) { // System.out.println(strg); strg = strg.trim(); // Messages.postDebug(strg); strg = strg.toLowerCase(); if (txaMsg != null) { txaMsg.append(strg); txaMsg.append("\n"); } } } catch (Exception e) { // e.printStackTrace(); Messages.writeStackTrace(e); Messages.postDebug(e.toString()); } finally { // It is my understanding that these streams are left // open sometimes depending on the garbage collector. // So, close them. try { if (prcs != null) { OutputStream os = prcs.getOutputStream(); if (os != null) os.close(); InputStream is = prcs.getInputStream(); if (is != null) is.close(); is = prcs.getErrorStream(); if (is != null) is.close(); } } catch (Exception ex) { Messages.writeStackTrace(ex); } } }
/** * System command. Execute a command and insert the result. * * @param args * @param help * @param patterns * @param low * @param high */ public String system_internal(boolean allowFail, String args[]) throws Exception { verifyCommand( args, "${" + (allowFail ? "system-allow-fail" : "system") + ";<command>[;<in>]}, execute a system command", null, 2, 3); String command = args[1]; String input = null; if (args.length > 2) { input = args[2]; } Process process = Runtime.getRuntime().exec(command, null, domain.getBase()); if (input != null) { process.getOutputStream().write(input.getBytes("UTF-8")); } process.getOutputStream().close(); String s = IO.collect(process.getInputStream(), "UTF-8"); int exitValue = process.waitFor(); if (exitValue != 0) return exitValue + ""; if (!allowFail && (exitValue != 0)) { domain.error("System command " + command + " failed with " + exitValue); } return s.trim(); }
/** * Executes the command through a system 'exec'. This method will be used only if the supporting * Java Native Interface library could not be loaded. */ private synchronized void pure_exec(String[] cmd) throws IOException { if (null != this.environ.getExecutable()) { cmd[0] = this.environ.getExecutable(); } p = rt.exec(cmd, this.environ.getEnvp()); InputStream is = p.getInputStream(); Debug.verbose("P4Process.exec().is: " + is); InputStreamReader isr = new InputStreamReader(is); Debug.verbose("P4Process.exec().isr: " + isr); in = new BufferedReader(isr); InputStream es = p.getErrorStream(); Debug.verbose("P4Process.exec().es: " + es); InputStreamReader esr = new InputStreamReader(es); Debug.verbose("P4Process.exec().esr: " + esr); err = new BufferedReader(esr); OutputStream os = p.getOutputStream(); Debug.verbose("P4Process.exec().os: " + os); OutputStreamWriter osw = new OutputStreamWriter(os); Debug.verbose("P4Process.exec().osw: " + osw); out = new FilterWriter(new BufferedWriter(osw)) { public void write(String str) throws IOException { super.write(str); System.out.print("P4DebugOutput: " + str); } }; }
String[] getMedkit( String[] availableResources, String[] requiredResources, String[] missions, double P, double C) { try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(exec); OutputStream os = proc.getOutputStream(); InputStream is = proc.getInputStream(); new ErrorReader(proc.getErrorStream()).start(); StringBuffer sb = new StringBuffer(); append(sb, availableResources); append(sb, requiredResources); append(sb, missions); sb.append(P).append('\n'); sb.append(C).append('\n'); os.write(sb.toString().getBytes()); BufferedReader br = new BufferedReader(new InputStreamReader(is)); int N = Integer.parseInt(br.readLine().trim()); String[] ret = new String[N]; for (int i = 0; i < N; i++) ret[i] = br.readLine().trim(); return ret; } catch (Exception e) { System.err.println("An error occurred while executing your program"); e.printStackTrace(); return null; } }
// To be called exactly twice by the parent process static <T> T rendezvousParent(Process p, Callable<T> callable) throws Throwable { p.getInputStream().read(); T result = callable.call(); OutputStream os = p.getOutputStream(); os.write((byte) '\n'); os.flush(); return result; }
/** * processes the input String and produces an output String. * * @param input the String to input to the underlying process * @throws java.lang.Exception exceptions from Runtime and Process that this class uses * @return the output from the underlying process */ public String process(String input) throws Exception { String returnValue = new String(); StringBuffer buffer = new StringBuffer(); if (socketServer == true) { returnValue = client.process(input); ServerThread current = getServer(); if (current != null) { if (!current.isDaemon()) { current.getProcess().destroy(); } current.interrupt(); } } else { // not a socket server Runtime rt = Runtime.getRuntime(); String output = ""; String errors = ""; try { p = rt.exec(getCodeCall() + " " + getParams()); PrintStream processInputStream = new PrintStream(p.getOutputStream(), true, "utf-8"); processInputStream.println(input + "\n\u0003"); // put in garbage to kill Bikel's loop StreamConsumer errorConsumer = new StreamConsumer(p.getErrorStream(), "error", 1); StreamConsumer outputConsumer = new StreamConsumer(p.getInputStream(), "output", 10); outputConsumer.start(); errorConsumer.start(); int countloops = 0; int time = 0; String message = ""; while (!outputConsumer.isComplete()) { // wait Thread.sleep(100); countloops++; time += 100; // one tenth of a second if (time > waittime) { // just wait 5 minutes message = "exceeded waittime of " + waittime + " milliseconds"; break; } } errors = errorConsumer.getOutput(); output = outputConsumer.getOutput(); if (!message.equals("")) { errors = message; } } catch (IOException ioe) { System.err.println("Module error: " + getModuleName()); ioe.printStackTrace(); System.exit(0); } p.destroy(); if (errors.equals("")) { returnValue = output; } else { returnValue = errors; } } return returnValue; }
public boolean continueShellProcess(Process proc) { if (progIndicator.isAborted()) { try { Writer stream; stream = new OutputStreamWriter((BufferedOutputStream) proc.getOutputStream()); stream.write((char) 3); stream.flush(); stream.close(); } catch (IOException e) { } return false; } return true; }
static void execPrivileged(final String[] cmd_array) throws Exception { try { Process process = AccessController.doPrivileged( new PrivilegedExceptionAction<Process>() { public Process run() throws Exception { return Runtime.getRuntime().exec(cmd_array); } }); // Close unused streams to make sure the child process won't hang process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); } catch (PrivilegedActionException e) { throw (Exception) e.getCause(); } }
/** ************************************************************* */ public static ArrayList<String> extractEntities(String infile) throws IOException { ArrayList<String> result = new ArrayList<String>(); Process _nlp; BufferedReader _reader; BufferedWriter _writer; BufferedReader _error; String stanfordCore = "/home/apease/Programs/stanford-ner-2014-10-26"; String newcore = KBmanager.getMgr().getPref("stanford-ner"); if (!StringUtil.emptyString(newcore)) stanfordCore = newcore; String execString = "/home/apease/Programs/java/jdk1.8.0_25/bin/java -mx700m " + "-classpath " + stanfordCore + "/stanford-ner.jar " + "edu.stanford.nlp.ie.crf.CRFClassifier " + // "-loadClassifier // /home/apease/Programs/stanford-ner-2014-10-26/classifiers/english.all.3class.distsim.crf.ser.gz " + // "-loadClassifier // /home/apease/Programs/stanford-ner-2014-10-26/classifiers/english.nowiki.3class.distsim.crf.ser.gz " + // "-loadClassifier // /home/apease/Programs/stanford-ner-2014-10-26/classifiers/english.conll.4class.distsim.crf.ser.gz " + "-loadClassifier " + stanfordCore + "/classifiers/english.muc.7class.distsim.crf.ser.gz " + "-textFile " + infile; System.out.println("INFO in NER.extractEntities(): executing: " + execString); _nlp = Runtime.getRuntime().exec(execString); _reader = new BufferedReader(new InputStreamReader(_nlp.getInputStream())); _error = new BufferedReader(new InputStreamReader(_nlp.getErrorStream())); // System.out.println("INFO in NER.extractEntities(): initializing process"); String line = null; while (true) { line = _reader.readLine(); System.out.println(line); if (line == null) break; result.add(line); } _writer = new BufferedWriter(new OutputStreamWriter(_nlp.getOutputStream())); return result; }
private void startProcess(List<String> command) { ProcessBuilder processBuilder = new ProcessBuilder(command); DarkMod darkMod = DarkMod.getInstance(); DarkModUI ui = darkMod.getUI(); try { if (ui != null) { ui.setVisible(false); ui.dispose(); } Process process = processBuilder.start(); StreamRedirectFactory.createInputToOutputRedirect(process.getInputStream(), System.out); StreamRedirectFactory.createInputToOutputRedirect(process.getErrorStream(), System.err); StreamRedirectFactory.createInputToOutputRedirect(System.in, process.getOutputStream()); System.exit(process.waitFor()); } catch (Exception exception) { exception.printStackTrace(); System.exit(-1); } }
private void startProcess() throws IOException, SrvrMgrException { ProcessBuilder builder = new ProcessBuilder(runTimeCommand); this.lastCommandDate = System.currentTimeMillis(); try { builder.redirectErrorStream(true); this.process = builder.start(); } catch (Exception ex) { throw new SrvrMgrException("Can't start process " + Arrays.toString(runTimeCommand)); } this.locked = false; this.processInput = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); this.processOutputStream = process.getInputStream(); this.PID = getProcessId(process); /*TODO: debug*/ processLog(runTimeCommand, "Input Command"); byte[] inputData = new byte[1024]; String result = ""; int numBytes; while ((numBytes = readInputStreamWithTimeout(processOutputStream, inputData, 1000)) > 0 || !result.contains("srvrmgr>")) { if (numBytes > 0) result += new String(inputData, StandardCharsets.UTF_8); else { try { Thread.sleep(500); } catch (InterruptedException ex) { } } if (result.contains(("Fatal error"))) { this.process.destroy(); throw new SrvrMgrException("Could not open connection to Siebel Gateway configuration"); } // System.out.println(result); inputData = new byte[1024]; } /*TODO: debug*/ processLog(result, "Output after process creation"); }
/** * Executes a command as {@code user}. Saves the stdout/stderr in the corresponding fields and * returns the return code of the child process. * * @param cmd The command to execute * @param data The data to send to the stdin of the process * @param timelimt How many seconds the command can run * @param memlimit How many megabytes the command can use */ private int exec(String cmdS, String data, int timelimit, int memlimit) throws Exception { ArrayList<String> cmd = new ArrayList<String>(cmdPrefix); cmd.add("-m"); cmd.add("" + memlimit); cmd.add("-c"); cmd.add("" + timelimit); cmd.add("-w"); cmd.add("" + (3 * timelimit + 1)); cmd.add("-x"); cmd.add(cmdS); String tmp = ""; for (String cs : cmd) tmp += " \"" + cs + "\""; log.fine("exec " + tmp); ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(workDir); Process p = pb.start(); OutputStreamWriter writer = new OutputStreamWriter(p.getOutputStream()); StreamReader rOut = new StreamReader(p.getInputStream()); StreamReader rErr = new StreamReader(p.getErrorStream()); rOut.start(); rErr.start(); // TODO I think this may block for big tests. Check and Fix. // send and receive data "in parallel" writer.write(data); writer.flush(); writer.close(); rOut.join(); rErr.join(); stdout = rOut.result; stderr = rErr.result; if (rOut.exception != null) throw rOut.exception; if (rErr.exception != null) throw rErr.exception; // log.finer("out: " + stdout); // log.finer("err: " + stderr); // log.finer("done exec"); return p.waitFor(); }
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed") private MyProcessHandler(@NotNull Process process) { super(process, null, null); // do not access EncodingManager here myWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); }