List of usage examples for java.lang Process getOutputStream
public abstract OutputStream getOutputStream();
From source file:com.esminis.server.mariadb.server.MariaDbServerLauncher.java
void initializeDataDirectory(Context context, File binary, File root) throws IOException { File[] files = root.listFiles(); if (files != null && files.length > 0) { return;//w w w.j a v a 2 s.c om } synchronized (lock) { final List<String> environment = getEnvironment(); final List<String> command = createCommandInternal(context, binary, root); Collections.addAll(command, "--bootstrap", "--log-warnings=0", "--max_allowed_packet=8M", "--net_buffer_length=16K"); final File dataMysqlDirectory = new File(root, "mysql"); if (dataMysqlDirectory.isDirectory()) { return; } if (!dataMysqlDirectory.mkdirs()) { throw new IOException("Cannot create directory: " + dataMysqlDirectory.getAbsolutePath()); } final Process process = Runtime.getRuntime().exec(command.toArray(new String[command.size()]), environment.toArray(new String[environment.size()]), root); final Object[] finishedWithError = { null }; try { final OutputStream stream = process.getOutputStream(); Observable.create(new Observable.OnSubscribe<Void>() { @Override public void call(Subscriber<? super Void> subscriber) { final InputStream inputStream = process.getErrorStream(); String data = ""; for (;;) { synchronized (finishedWithError) { if (finishedWithError[0] != null) { break; } } try { int available = inputStream.available(); if (available > 0) { for (int i = 0; i < available; i++) { data += (char) inputStream.read(); } if (getFreeSpace(dataMysqlDirectory) < 1024L * 1024L || data.contains("No space left on device")) { synchronized (finishedWithError) { finishedWithError[0] = new IOException("No space left on device"); } process.destroy(); break; } } } catch (Throwable ignored) { } Thread.yield(); } subscriber.onCompleted(); } }).subscribeOn(Schedulers.newThread()).subscribe(); writeToStream(stream, "use mysql;\n"); writeToStream(stream, context, "sql/mysql_system_tables.sql"); writeToStream(stream, context, "sql/mysql_performance_tables.sql"); writeToStream(stream, context, "sql/mysql_system_tables_data.sql"); writeToStream(stream, context, "sql/add_root_from_any_host.sql"); writeToStream(stream, context, "sql/fill_help_tables.sql"); writeToStream(stream, "exit;\n"); process.waitFor(); } catch (Throwable e) { FileUtils.deleteDirectory(root); //noinspection ResultOfMethodCallIgnored root.mkdirs(); synchronized (finishedWithError) { if (finishedWithError[0] != null && finishedWithError[0] instanceof IOException) { throw (IOException) finishedWithError[0]; } else { throw new IOException( e.toString() + "\n\nLog:\n" + IOUtils.toString(process.getErrorStream())); } } } finally { synchronized (finishedWithError) { if (finishedWithError[0] == null) { finishedWithError[0] = true; } } } } }
From source file:org.applause.applausedsl.ui.generator.formatter.UncrustifyFormatter.java
/** * Formats the given string with Uncrustify. * //from w ww. j a v a 2 s .c o m * @param unformatted * Unformatted code * @param args * @return Formatted code */ public CharSequence format(CharSequence unformatted, List<String> args) { if (unformatted == null) { return null; } if (args == null) { throw new IllegalArgumentException("args is null"); } Process proc = null; // Store original code as fallback CharSequence result = unformatted; try { int rc; ProcessBuilder pb = new ProcessBuilder(); pb.command(args); proc = pb.start(); Writer stdinWriter = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())); IOUtils.copy(new StringReader(unformatted.toString()), stdinWriter); stdinWriter.close(); rc = proc.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream())); String lineRead; while ((lineRead = br.readLine()) != null) { if (lineRead.startsWith("Parsing:")) { LOG.debug(lineRead); } else { LOG.warn(lineRead); } } if (rc != 0) { LOG.warn("Execution of uncrustify failed with error."); } else { StringWriter sw = new StringWriter(unformatted.length()); IOUtils.copy(proc.getInputStream(), sw); result = sw.getBuffer(); rc = proc.exitValue(); if (rc != 0) { LOG.warn("Execution of uncrustify failed with error."); } else { if (LOG.isDebugEnabled()) LOG.debug("Execution of uncrustify was successful."); } } } catch (Exception re) { LOG.warn(re.getClass().getSimpleName() + ": " + re.getMessage()); } finally { if (proc != null) { IOUtils.closeQuietly(proc.getErrorStream()); IOUtils.closeQuietly(proc.getInputStream()); IOUtils.closeQuietly(proc.getOutputStream()); } } return result; }
From source file:io.appium.java_client.service.local.AppiumServiceBuilder.java
@Override protected File findDefaultExecutable() { validateNodeJSVersion();/*from ww w .j av a 2s .c om*/ Runtime rt = Runtime.getRuntime(); Process p; try { p = rt.exec(NODE_COMMAND_PREFIX + " node"); } catch (IOException e) { throw new RuntimeException(e); } try { OutputStream outputStream = p.getOutputStream(); PrintStream out = new PrintStream(outputStream); out.println("console.log(process.execPath);"); out.close(); return new File(getProcessOutput(p.getInputStream())); } catch (Throwable t) { throw new RuntimeException(t); } finally { p.destroy(); } }
From source file:org.wso2.carbon.identity.authenticator.krb5.Krb5Authenticator.java
private boolean loginWithKrb5(String username, String password, String remoteAddress) throws AuthenticationException { //Proceed with Kerberos TGT request String uuid = UUID.randomUUID().toString(); ProcessBuilder procBldr = new ProcessBuilder("/usr/bin/kinit", "-l", "10d", "-r", "5d", "-c", tgtCachePrefix + uuid, username); procBldr.directory(new File(CARBON_HOME)); Map<String, String> env = procBldr.environment(); if (KRB5_CONFIG == null) KRB5_CONFIG = "/etc/krb5.conf"; env.put("KRB5_CONFIG", KRB5_CONFIG); log.info(env.get("KRB5_CONFIG")); HttpSession session = getHttpSession(); try {/* w w w . j a va 2s.co m*/ Process proc = procBldr.start(); InputStream procErr = proc.getErrorStream(); InputStream procOut = proc.getInputStream(); //Read the output from the program byte[] buffer = new byte[256]; BufferedWriter out = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())); BufferedReader err = new BufferedReader(new InputStreamReader(procErr)); boolean isError = (procErr.available() > 0) ? true : false; if (!isError) { out.write(password); out.newLine(); out.close(); if (proc.waitFor() != 0) { log.warn("Kinit Failed"); if (procErr.available() > 0) { String line = null; String msg = ""; while (err.ready() && (line = err.readLine()) != null) msg += line; if (!msg.equals("")) throw new AuthenticationException(msg); } } //Looks like all went well and we got the TGT, lets renew the TGT... procBldr = new ProcessBuilder("/usr/bin/kinit", "-R", "-c", tgtCachePrefix + uuid); proc = procBldr.start(); if (proc.waitFor() != 0) { log.warn("TGT Renewal Failed"); File tgt = new File(tgtCachePrefix + uuid); tgt.delete(); throw new AuthenticationException("TGT Renewal Failed"); } AuthenticationAdmin authAdmin = new AuthenticationAdmin(); boolean loggedIn = authAdmin.login(username, password, remoteAddress); if (loggedIn) { nameToUuidMap.put(username, uuid); session.setAttribute(Krb5AuthenticatorConstants.USER_TICKET_CACHE, tgtCachePrefix + uuid); } return loggedIn; } else { log.error("Incorrect kinit command: " + err.readLine()); throw new AuthenticationException("Incorrect kinit command"); } } catch (IOException ioe) { log.warn(ioe.getMessage()); ioe.printStackTrace(); throw new AuthenticationException(ioe.getMessage()); } catch (InterruptedException e) { e.printStackTrace(); throw new AuthenticationException(e.getMessage()); } }
From source file:com.googlecode.jmxtrans.model.output.RRDToolWriter.java
/** * Calls out to the rrdtool binary with the 'create' command. *//*from www .j ava2s .com*/ protected void rrdToolCreateDatabase(RrdDef def) throws Exception { List<String> commands = new ArrayList<>(); commands.add(this.binaryPath + "/rrdtool"); commands.add("create"); commands.add(this.outputFile.getCanonicalPath()); commands.add("-s"); commands.add(String.valueOf(def.getStep())); for (DsDef dsdef : def.getDsDefs()) { commands.add(getDsDefStr(dsdef)); } for (ArcDef adef : def.getArcDefs()) { commands.add(getRraStr(adef)); } ProcessBuilder pb = new ProcessBuilder(commands); Process process = pb.start(); try { checkErrorStream(process); } finally { IOUtils.closeQuietly(process.getInputStream()); IOUtils.closeQuietly(process.getOutputStream()); IOUtils.closeQuietly(process.getErrorStream()); } }
From source file:org.apache.taverna.commandline.TavernaCommandLineTest.java
private synchronized void runWorkflow(String command, String workflow, File outputsDirectory, boolean inputValues, boolean secure, boolean database) throws Exception { ProcessBuilder processBuilder = new ProcessBuilder("sh", command); processBuilder.redirectErrorStream(true); processBuilder.directory(buildDirectory); List<String> args = processBuilder.command(); for (File input : inputs) { if (inputValues) { args.add("-inputvalue"); args.add(input.getName());//from ww w . ja va 2 s . c o m args.add(IOUtils.toString(new FileReader(input))); } else { args.add("-inputfile"); args.add(input.getName()); args.add(input.getAbsolutePath()); } } args.add("-outputdir"); args.add(outputsDirectory.getPath()); if (secure) { args.add("-cmdir"); args.add(getClass().getResource("/security").getFile()); args.add("-cmpassword"); } if (database) { args.add("-embedded"); } args.add(workflow); Process process = processBuilder.start(); if (secure) { PrintStream outputStream = new PrintStream(process.getOutputStream()); outputStream.println("test"); outputStream.flush(); } waitFor(process); }
From source file:er.extensions.ERXExtensions.java
/** * Frees all of the resources associated with a given * process and then destroys the process. * @param p process to destroy//from w ww.j av a 2 s. c o m */ public static void freeProcessResources(Process p) { if (p != null) { try { if (p.getInputStream() != null) p.getInputStream().close(); if (p.getOutputStream() != null) p.getOutputStream().close(); if (p.getErrorStream() != null) p.getErrorStream().close(); p.destroy(); } catch (IOException e) { } } }
From source file:org.ballerinalang.test.context.BMainInstance.java
/** * Write client clientArgs to process.// www .j a v a 2s .co m * * @param clientArgs client clientArgs * @param process process executed * @throws IOException if something goes wrong */ private void writeClientArgsToProcess(String[] clientArgs, Process process) throws IOException { try { // Wait until the options are prompted TODO find a better way Thread.sleep(3000); } catch (InterruptedException e) { //Ignore } OutputStream stdin = process.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin)); for (String arguments : clientArgs) { writer.write(arguments); } writer.flush(); writer.close(); }
From source file:Exec.java
/** * Description of the Method//from ww w .j a v a2s.c o m * * @param command * Description of the Parameter * @param input * Description of the Parameter * @param successCode * Description of the Parameter * @param timeout * Description of the Parameter * @param lazy * Description of the Parameter * @return Description of the Return Value */ public static ExecResults execOptions(String command, String input, int successCode, int timeout, boolean lazy) { Process child = null; ByteArrayOutputStream output = new ByteArrayOutputStream(); ByteArrayOutputStream errors = new ByteArrayOutputStream(); ExecResults results = new ExecResults(command, input, successCode, timeout); BitSet interrupted = new BitSet(1); boolean lazyQuit = false; ThreadWatcher watcher; try { // start the command child = Runtime.getRuntime().exec(command); // get the streams in and out of the command InputStream processIn = child.getInputStream(); InputStream processError = child.getErrorStream(); OutputStream processOut = child.getOutputStream(); // start the clock running if (timeout > 0) { watcher = new ThreadWatcher(child, interrupted, timeout); new Thread(watcher).start(); } // Write to the child process' input stream if ((input != null) && !input.equals("")) { try { processOut.write(input.getBytes()); processOut.flush(); processOut.close(); } catch (IOException e1) { results.setThrowable(e1); } } // Read from the child process' output stream // The process may get killed by the watcher at any time int c = 0; try { while (true) { if (interrupted.get(0) || lazyQuit) { break; } // interrupted c = processIn.read(); if (c == -1) { break; } // end of stream output.write(c); if (lazy && (processIn.available() < 1)) { lazyQuit = true; } // if lazy and nothing then quit (after at least one read) } processIn.close(); } catch (IOException e2) { results.setThrowable(e2); } finally { if (interrupted.get(0)) { results.setInterrupted(); } results.setOutput(output.toString()); } // Read from the child process' error stream // The process may get killed by the watcher at any time try { while (true) { if (interrupted.get(0) || lazyQuit) { break; } // interrupted c = processError.read(); if (c == -1) { break; } // end of stream output.write(c); if (lazy && (processError.available() < 1)) { lazyQuit = true; } // if lazy and nothing then quit (after at least one read) } processError.close(); } catch (IOException e3) { results.setThrowable(e3); } finally { if (interrupted.get(0)) { results.setInterrupted(); } results.setErrors(errors.toString()); } // wait for the return value of the child process. if (!interrupted.get(0) && !lazyQuit) { int returnCode = child.waitFor(); results.setReturnCode(returnCode); if (returnCode != successCode) { results.setError(ExecResults.BADRETURNCODE); } } } catch (InterruptedException i) { results.setInterrupted(); } catch (Throwable t) { results.setThrowable(t); } finally { if (child != null) { child.destroy(); } } return (results); }
From source file:Exec.java
/** * Description of the Method// w w w. ja v a 2 s .c o m * * @param command * Description of the Parameter * @param input * Description of the Parameter * @param successCode * Description of the Parameter * @param timeout * Description of the Parameter * @param lazy * Description of the Parameter * @return Description of the Return Value */ public static ExecResults execOptions(String[] command, String input, int successCode, int timeout, boolean lazy) { Process child = null; ByteArrayOutputStream output = new ByteArrayOutputStream(); ByteArrayOutputStream errors = new ByteArrayOutputStream(); ExecResults results = new ExecResults(command[0], input, successCode, timeout); BitSet interrupted = new BitSet(1); boolean lazyQuit = false; ThreadWatcher watcher; try { // start the command child = Runtime.getRuntime().exec(command); // get the streams in and out of the command InputStream processIn = child.getInputStream(); InputStream processError = child.getErrorStream(); OutputStream processOut = child.getOutputStream(); // start the clock running if (timeout > 0) { watcher = new ThreadWatcher(child, interrupted, timeout); new Thread(watcher).start(); } // Write to the child process' input stream if ((input != null) && !input.equals("")) { try { processOut.write(input.getBytes()); processOut.flush(); processOut.close(); } catch (IOException e1) { results.setThrowable(e1); } } // Read from the child process' output stream // The process may get killed by the watcher at any time int c = 0; try { while (true) { if (interrupted.get(0) || lazyQuit) { break; } // interrupted c = processIn.read(); if (c == -1) { break; } // end of stream output.write(c); if (lazy && (processIn.available() < 1)) { lazyQuit = true; } // if lazy and nothing then quit (after at least one read) } processIn.close(); } catch (IOException e2) { results.setThrowable(e2); } finally { if (interrupted.get(0)) { results.setInterrupted(); } results.setOutput(output.toString()); } // Read from the child process' error stream // The process may get killed by the watcher at any time try { while (true) { if (interrupted.get(0) || lazyQuit) { break; } // interrupted c = processError.read(); if (c == -1) { break; } // end of stream output.write(c); if (lazy && (processError.available() < 1)) { lazyQuit = true; } // if lazy and nothing then quit (after at least one read) } processError.close(); } catch (IOException e3) { results.setThrowable(e3); } finally { if (interrupted.get(0)) { results.setInterrupted(); } results.setErrors(errors.toString()); } // wait for the return value of the child process. if (!interrupted.get(0) && !lazyQuit) { int returnCode = child.waitFor(); results.setReturnCode(returnCode); if (returnCode != successCode) { results.setError(ExecResults.BADRETURNCODE); } } } catch (InterruptedException i) { results.setInterrupted(); } catch (Throwable t) { results.setThrowable(t); } finally { if (child != null) { child.destroy(); } } return (results); }