static int getHerokuAssignedPort() { ProcessBuilder processBuilder = new ProcessBuilder(); if (processBuilder.environment().get("PORT") != null) { return Integer.parseInt(processBuilder.environment().get("PORT")); } return 4567; // return default port if heroku-port isn't set (i.e. on localhost) }
public ProcessManager(String[] c, String[] env) throws IOException { String[] cx = c; String pnam = "this is a test"; String tcmd = Utils.join(cx, " "); if (isWindows) { cx = new String[] {"cmd", "/c", tcmd}; } else { cx = new String[] {"/usr/bin/ruby", "-e", rbProg.replaceAll("@@@", Utils.join(c, " "))}; } this.cmd = cx; ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectErrorStream(true); pb.environment().put("the_command", tcmd); pb.environment().put("the_title", pnam); if (env != null) { for (String e : env) { int ee = e.indexOf("="); if (ee > 0) pb.environment().put(e.substring(0, ee), e.substring(ee + 1)); else pb.environment().put(e, ""); } } proc = pb.start(); lk = new Semaphore(0); scribe = new Scribe(); scribe_thread = new Thread(scribe); scribe_thread.start(); new Thread( new Runnable() { public void run() { try { proc.waitFor(); processes.remove(ProcessManager.this.keyHandle()); System.err.println("process " + proc.toString() + " died"); ProcessManager.this.processDied(); } catch (InterruptedException ignore) { } } }) .start(); /* if (isWindows) { proc.getOutputStream().write("title this is a test\n%the_command%\n".getBytes()); proc.getOutputStream().flush(); proc.getOutputStream().close(); } */ try { scribe_thread.join(333); } catch (InterruptedException ignore) { } // wait for one third of a second processes.put(keyHandle(), this); }
private static File detectHadoopConfigurationDirectory( File command, File temporary, Map<String, String> envp) throws IOException { assert command != null; assert temporary != null; assert envp != null; prepareClasspath(temporary, ConfigurationDetecter.class); File resultOutput = new File(temporary, PATH_SUBPROC_OUTPUT); List<String> arguments = new ArrayList<String>(); arguments.add(command.getAbsolutePath()); arguments.add(ConfigurationDetecter.class.getName()); arguments.add(resultOutput.getAbsolutePath()); ProcessBuilder processBuilder = new ProcessBuilder(arguments); processBuilder.environment().clear(); processBuilder.environment().putAll(envp); processBuilder.environment().put(ENV_HADOOP_CLASSPATH, temporary.getPath()); Process process = processBuilder.start(); try { Thread redirectOut = redirect(process.getInputStream(), System.out); Thread redirectErr = redirect(process.getErrorStream(), System.err); try { int exit = process.waitFor(); redirectOut.join(); redirectErr.join(); if (exit != 0) { throw new IOException( MessageFormat.format( "Failed to execute Hadoop command (exitcode={1}): {0}", arguments, String.valueOf(exit))); } } catch (InterruptedException e) { throw (IOException) new InterruptedIOException( MessageFormat.format( "Failed to execute Hadoop command (interrupted): {0}", arguments)) .initCause(e); } } finally { process.destroy(); } if (resultOutput.isFile() == false) { throw new IOException( MessageFormat.format("Failed to restore Hadoop configuration path: {0}", resultOutput)); } File path = ConfigurationDetecter.read(resultOutput); return path; }
// If workingDirectory is null, then it is not set protected final void launchCommand(List<String> cmd, File workingDirectory) throws InterruptedException { retVal = -1000; output = new LinkedList<String>(); errors = new LinkedList<String>(); ProcessBuilder pb = new ProcessBuilder(cmd); // Redirect stderr to stdout pb.redirectErrorStream(true); // Update PATH variable to include external tools used by // the plug-in pb.environment() .put( "PATH", PreferencesValues.getGCC_PATH() + File.pathSeparator + pb.environment().get("PATH")); pb.environment() .put( "PATH", PreferencesValues.getCHEDDAR_PATH() + File.pathSeparator + pb.environment().get("PATH")); // Set working directory if (workingDirectory != null) { pb.directory(workingDirectory); } // Print the arguments used to execute the command out.println(StringUtils.join(cmd, ' ')); try { Process process = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); for (String line = reader.readLine(); line != null; line = reader.readLine()) { output.add(line); Utils.ocarinaDebug("command output: " + line); } retVal = process.waitFor(); } catch (IOException ex) { throw new RuntimeException(ex); } onAfterLaunchCommand(); }
public CommandResult exec( String[] pCmd, Map<String, String> pEnv, boolean useSysEnv, Writer pOut, Writer pErr) throws IOException, InterruptedException { int out = 0; String pCmdString = ArrayUtils.toString(pCmd); ProcessBuilder builder = new ProcessBuilder(); builder.command(pCmd); Map<String, String> env = builder.environment(); if (!useSysEnv) env.clear(); for (String name : pEnv.keySet()) { env.put(name, pEnv.get(name)); } logExec(pCmdString, env); StopWatch clock = new StopWatch(); clock.start(); try { process = builder.start(); out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt); } finally { this.cleanUpProcess(); clock.stop(); if (_log.isInfoEnabled()) _log.info("'" + pCmdString + "' completed in " + clock.getTime() + " ms"); } if (sig_interrupt.getValue() == true) { out = -9999; } CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString()); return result; }
private static void makeProcessSystemProperties( final ProcessBuilder pb, final Map<String, String> additional) { final StringBuilder sb = new StringBuilder(); for (final Map.Entry<Object, Object> entry : System.getProperties().entrySet()) { if (entry.getKey() == null || entry.getValue() == null) { continue; } final String key = entry.getKey().toString(); final String value = entry.getValue().toString(); if (key.startsWith("org.osgi.") || key.startsWith("drone.")) { if (sb.length() > 0) { sb.append(' '); } sb.append("-D").append(key).append('=').append(value); } } for (final Map.Entry<String, String> entry : additional.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); if (sb.length() > 0) { sb.append(' '); } sb.append("-D").append(key).append('=').append(value); } pb.environment().put("JAVA_OPTS", sb.toString()); }
protected Process startProcess(@NotNull List<String> commands) throws IOException { ProcessBuilder builder = new ProcessBuilder(commands); setupEnvironment(builder.environment()); builder.directory(myWorkDirectory); builder.redirectErrorStream(myRedirectErrorStream); return builder.start(); }
public void runCommand(String envName, String envValue, String... command) { try { ProcessBuilder pb = new ProcessBuilder(command); Map<String, String> env = pb.environment(); env.put(envName, envValue); // env.put(/*"BIRT_HOME"*/envName, // envValue/*"/home/alexander/myItemsLast/birt-runtime-4_4_1/"*/); pb.redirectErrorStream(true); Process p = pb.start(); InputStream is = p.getInputStream(); String pbMessage = "\nCommand " + Arrays.asList(command) + " reported"; System.out.println(pbMessage); log.write(pbMessage); int b; while ((b = is.read()) >= 0) System.out.write(b); is.close(); p.destroy(); } catch (IOException e) { String pbMessage = "\nCommand " + Arrays.asList(command) + " reported " + e; System.err.println(pbMessage); log.write(pbMessage); } }
public CommandResult exec(String[] pCmd, File dir, Writer pOut, Writer pErr) throws IOException, InterruptedException { ProcessBuilder builder = new ProcessBuilder(); Map<String, String> env = builder.environment(); int out = 0; String pCmdString = ArrayUtils.toString(pCmd); logExec(pCmdString, env); StopWatch clock = new StopWatch(); clock.start(); try { process = Runtime.getRuntime().exec(pCmd, null, dir); out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt); } finally { this.cleanUpProcess(); clock.stop(); if (_log.isInfoEnabled()) _log.info("'" + pCmd + "' completed in " + clock.getTime() + " ms"); } if (sig_interrupt.getValue() == true) { out = -9999; } CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString()); return result; }
/** Start a dedicated Cassandra process for this node. */ public void start() { getLog() .info( String.format( "Starting node #%s: %s:%s", mNodeId, mMyAddress, mCassandraConfiguration.getPortNativeTransport())); try { ProcessBuilder pb = new ProcessBuilder(); // Build a Java command line for running Cassandra. String javaExec = getJavaExecutable(); // Set the classpath to include all of the dependencies for this plugin (i.e., Cassandra). String classpath = getClasspath(); // Set CASSANDRA_CONF appropriately. Map<String, String> environmentVariables = pb.environment(); updateEnvironmentVariables(environmentVariables); pb.command(javaExec, "-cp", classpath, CassandraDaemon.class.getCanonicalName()); pb.directory(mRootDir); mCassandraProcess = pb.start(); // getLog().info("Successfully started node " + mNodeId); } catch (IOException ioe) { getLog().warn("Could not start Cassandra node " + mNodeId); } }
Path genPythonToolkit(String module) throws IOException, InterruptedException { Path pubsub = Paths.get(getTestRoot().getAbsolutePath(), "python", "pubsub"); System.err.println("Pubsub:" + pubsub); Path pyTk = Files.createTempDirectory("pytk").toAbsolutePath(); System.err.println("PKTK:" + pyTk); Path pyPackages = Paths.get(System.getProperty("topology.toolkit.release"), "opt", "python", "packages") .toAbsolutePath(); String pythonversion = System.getProperty("topology.test.python"); ProcessBuilder pb = new ProcessBuilder(pythonversion, module, pyTk.toAbsolutePath().toString()); pb.redirectOutput(Redirect.INHERIT); pb.redirectError(Redirect.INHERIT); Map<String, String> env = pb.environment(); env.put("PYTHONPATH", pyPackages.toString()); pb.directory(pubsub.toFile()); Process proc = pb.start(); assertEquals(0, proc.waitFor()); return pyTk; }
/** * Method description * * @return * @throws IOException */ protected Process createProcess() throws IOException { if (logger.isDebugEnabled()) { StringBuilder cmd = new StringBuilder(); for (String c : command) { cmd.append(c).append(" "); } logger.debug("start external process '{}'", cmd.toString()); } ProcessBuilder processBuilder = new ProcessBuilder(command); if (workDirectory != null) { processBuilder = processBuilder.directory(workDirectory); } Map<String, String> env = processBuilder.environment(); if (useSystemEnvironment) { env.putAll(System.getenv()); } if (environment != null) { env.putAll(environment); } return processBuilder.redirectErrorStream(true).start(); }
private void addBasisAndUrePaths(ProcessBuilder processBuilder) throws IOException { // see http://wiki.services.openoffice.org/wiki/ODF_Toolkit/Efforts/Three-Layer_OOo File basisLink = new File(officeHome, "basis-link"); if (!basisLink.isFile()) { logger.fine( "no %OFFICE_HOME%/basis-link found; assuming it's OOo 2.x and we don't need to append URE and Basic paths"); return; } String basisLinkText = FileUtils.readFileToString(basisLink).trim(); File basisHome = new File(officeHome, basisLinkText); File basisProgram = new File(basisHome, "program"); File ureLink = new File(basisHome, "ure-link"); String ureLinkText = FileUtils.readFileToString(ureLink).trim(); File ureHome = new File(basisHome, ureLinkText); File ureBin = new File(ureHome, "bin"); Map<String, String> environment = processBuilder.environment(); // Windows environment variables are case insensitive but Java maps are not :-/ // so let's make sure we modify the existing key String pathKey = "PATH"; for (String key : environment.keySet()) { if ("PATH".equalsIgnoreCase(key)) { pathKey = key; } } String path = environment.get(pathKey) + ";" + ureBin.getAbsolutePath() + ";" + basisProgram.getAbsolutePath(); logger.fine(String.format("setting %s to \"%s\"", pathKey, path)); environment.put(pathKey, path); }
private WorkerJvm startWorkerJvm() throws IOException { int workerIndex = workerJvmSettings.getWorkerIndex(); WorkerType type = workerJvmSettings.getWorkerType(); SimulatorAddress workerAddress = new SimulatorAddress(AddressLevel.WORKER, agent.getAddressIndex(), workerIndex, 0); String workerId = "worker-" + agent.getPublicAddress() + '-' + workerIndex + '-' + type.toLowerCase(); File workerHome = new File(testSuiteDir, workerId); ensureExistingDirectory(workerHome); WorkerJvm workerJvm = new WorkerJvm(workerAddress, workerId, workerHome); generateWorkerStartScript(type, workerJvm); ProcessBuilder processBuilder = new ProcessBuilder(new String[] {"bash", "worker.sh"}) .directory(workerHome) .redirectErrorStream(true); Map<String, String> environment = processBuilder.environment(); String javaHome = getJavaHome(); String path = javaHome + File.pathSeparator + "bin:" + environment.get("PATH"); environment.put("PATH", path); environment.put("JAVA_HOME", javaHome); Process process = processBuilder.start(); workerJvm.setProcess(process); copyResourcesToWorkerId(workerId); workerJvmManager.add(workerAddress, workerJvm); return workerJvm; }
public static Process executeLocal(String[] cmdArray, File ifileDir) { // System.out.println("local execution!" + " " + Arrays.toString(cmdArray) ); ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); Map<String, String> env = processBuilder.environment(); if (!env.containsKey(OCSSW_ROOT_VAR) && OCSSW.isOCSSWExist()) { env.put(OCSSW_ROOT_VAR, OCSSW.getOcsswEnv()); } if (ifileDir != null) { processBuilder.directory(ifileDir); } else { processBuilder.directory(getDefaultDir()); } Process process = null; try { process = processBuilder.start(); int exitValue = process.waitFor(); } catch (Exception e) { VisatApp.getApp() .showErrorDialog( "OCSSW execution error from SeaDAS application! \n" + cmdArray[0] + " program is not executed correctly."); e.printStackTrace(); } return process; }
public Process createProcess() throws ExecutionException { if (LOG.isDebugEnabled()) { LOG.debug("Executing [" + getCommandLineString() + "]"); } List<String> commands; try { checkWorkingDirectory(); if (StringUtil.isEmptyOrSpaces(myExePath)) { throw new ExecutionException( IdeBundle.message("run.configuration.error.executable.not.specified")); } commands = CommandLineUtil.toCommandLine(myExePath, myProgramParams.getList()); } catch (ExecutionException e) { LOG.warn(e); throw e; } try { ProcessBuilder builder = new ProcessBuilder(commands); setupEnvironment(builder.environment()); builder.directory(myWorkDirectory); builder.redirectErrorStream(myRedirectErrorStream); return builder.start(); } catch (IOException e) { LOG.warn(e); throw new ProcessNotCreatedException(e.getMessage(), e, this); } }
private void execute(List<String> command2) { try { ProcessBuilder builder = new ProcessBuilder(command2); if (env.size() > 0) builder.environment().putAll(env); if (StringUtils.hasLength(workingDir)) builder.directory(new File(workingDir)); builder.redirectErrorStream(true); process = builder.start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); try { String line; while ((line = stdInput.readLine()) != null) { System.out.println(line); } process.waitFor(); } finally { stdInput.close(); } } catch (IOException e) { throw new AssertionError(e); } catch (InterruptedException e) { throw new AssertionError(e); } }
public static Process executeRemote(String[] cmdArray, File ifileDir) { Gson gson = new Gson(); String json = gson.toJson(cmdArray); JsonParser parser = new JsonParser(); JsonArray array = parser.parse(json).getAsJsonArray(); ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); Map<String, String> env = processBuilder.environment(); if (environment != null) env.putAll(environment); if (ifileDir != null) { processBuilder.directory(ifileDir); } else { // processBuilder.directory(getDefaultDir()); } Process process = null; try { process = processBuilder.start(); } catch (IOException ioe) { } return process; }
public StreamSink createStreamSink(ServiceContext context, Flow flow) { List<String> commandList = new ArrayList<String>(); String cmd = command.evaluateString(context, flow); commandList.add(cmd); for (int i = 0; i < commandArgs.length; ++i) { String arg = commandArgs[i].evaluateString(context, flow); commandList.add(arg); } ProcessBuilder processBuilder = new ProcessBuilder(commandList); Map<String, String> environment = processBuilder.environment(); for (int i = 0; i < envVariableFactories.length; ++i) { EnvVariable envVariable = envVariableFactories[i].createEnvVariable(context, flow); environment.put(envVariable.getName(), envVariable.getValue()); } String directory = dirResolver.evaluateAsString(flow.getParameters(), flow.getRecord()); if (directory.length() > 0) { File file = new File(directory); processBuilder.directory(file); } StreamSink streamSink = new CommandSink(processBuilder, charset); return streamSink; }
public void startProfile(FirefoxProfile profile, File profileDir, String... commandLineFlags) throws IOException { String profileAbsPath = profileDir.getAbsolutePath(); setEnvironmentProperty("XRE_PROFILE_PATH", profileAbsPath); setEnvironmentProperty("MOZ_NO_REMOTE", "1"); setEnvironmentProperty("MOZ_CRASHREPORTER_DISABLE", "1"); // Disable Breakpad setEnvironmentProperty( "NO_EM_RESTART", "1"); // Prevent the binary from detaching from the console if (isOnLinux() && (profile.enableNativeEvents() || profile.alwaysLoadNoFocusLib())) { modifyLinkLibraryPath(profileDir); } List<String> commands = new ArrayList<String>(); commands.add(getExecutable().getPath()); commands.addAll(Arrays.asList(commandLineFlags)); ProcessBuilder builder = new ProcessBuilder(commands); builder.redirectErrorStream(true); builder.environment().putAll(getExtraEnv()); getExecutable().setLibraryPath(builder, getExtraEnv()); if (stream == null) { stream = getExecutable().getDefaultOutputStream(); } startFirefoxProcess(builder); copeWithTheStrangenessOfTheMac(builder); startOutputWatcher(); }
private static ProcessBuilder setPassword( ProcessBuilder builder, ConnectionProperties properties) { if (!PASSWORD_FILE.exists()) { builder.environment().put("MYSQL_PWD", properties.getPassword()); } return builder; }
/** * Run a given command in a subprocess, including threads to copy its stdout and stderr to our * stdout and stderr. * * @param command the command and its arguments * @param env the environment to run the process in * @return a handle on the process * @throws IOException */ static Process runClient(List<String> command, Map<String, String> env) throws IOException { ProcessBuilder builder = new ProcessBuilder(command); if (env != null) { builder.environment().putAll(env); } Process result = builder.start(); return result; }
public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir, Map<String,String> envVars) throws IOException { printCommandLine(cmd, workDir); ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(toFile(workDir)); if (envVars!=null) pb.environment().putAll(envVars); return launchChannel(out, pb); }
private static ProcessBuilder buildProcess(String[] args) { ProcessBuilder pb = new ProcessBuilder(args[0]); Map<String, String> env = pb.environment(); for (int i = 3; i < args.length; i = i + 2) { env.put(args[i], args[i + 1]); } pb.directory(new File(args[1])); return pb; }
/** * Start a process Start a process and merge its error and output streams * * @see ExecHelper#exec() */ public static ExecHelper execMerge( IExecEvents handler, String command[], Map<String, String> envp, File dir) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(dir); processBuilder.redirectErrorStream(true); if (envp != null) processBuilder.environment().putAll(envp); return new ExecHelper(handler, processBuilder.start()); }
private void dumpEnv(StringBuilder buffer) { buffer.append("\nEnvironment\n-----------"); Map<String, String> env = builder.environment(); Set<String> keys = env.keySet(); List<String> sortedKeys = new ArrayList<String>(keys); Collections.sort(sortedKeys); for (String key : sortedKeys) { buffer.append(key).append("=").append(env.get(key)).append('\n'); } }
private void setEnvironment(final RuntimeData data, final ProcessBuilder builder) { final Map<String, String> env = builder.environment(); if (!SystemConfiguration.getInstance().isOnWindows() && SystemConfiguration.getInstance().hasSpecialTclLib()) { env.put("TCL_LIBRARY", "/usr/share/tcl/tcl8.4/"); } if (data.getEnv() != null) { env.putAll(data.getEnv()); } }
/** * Calls the Unix sort command with the options <code>$filesNames -o * $outputfile -T WaybackSettings#WAYBACK_AGGREGATOR_TEMP_DIR. * * Sets the LC_ALL environment variable before making the call. * * @param files The files to merge and sort * @param outputFile The resulting sorted file * @param additionalArgs A list af extra arguments, which (if different from * null) are added to the sort call.<p> Note: If any * of the args contain a whitespace the call will * fail. */ private void processFiles(File[] files, File outputFile, List<String> additionalArgs) { if (files.length == 0) { // Empty file list will cause sort to wait for further input, // and the call will therefore never return return; } Process p = null; try { List<String> inputFileList = new LinkedList<String>(); for (int i = 0; i < files.length; i++) { if (files[i].exists() && files[i].isFile()) { inputFileList.add(files[i].getCanonicalPath()); } else { log.warn( "File " + files[i] + " doesn't exist or isn't a regular file, " + "dropping from list of files to " + "sort and merge"); } } List<String> cmd = new LinkedList<String>(); // Prepare to run the unix sort command, see sort manual page for // details cmd.add("sort"); cmd.addAll(inputFileList); cmd.add("-o"); cmd.add(outputFile.getCanonicalPath()); cmd.add("-T"); cmd.add(Settings.get(WaybackSettings.WAYBACK_AGGREGATOR_TEMP_DIR)); if (additionalArgs != null && !additionalArgs.isEmpty()) { for (String argument : additionalArgs) { ArgumentNotValid.checkTrue( argument.indexOf(' ') == -1, "The argument '" + argument + "' contains spaces, this isn't allowed "); } cmd.addAll(additionalArgs); } ProcessBuilder pb = new ProcessBuilder(cmd); // Reset all locale definitions pb.environment().put("LC_ALL", "C"); // Run the command in the user.dir directory pb.directory(new File(System.getProperty("user.dir"))); p = pb.start(); p.waitFor(); if (p.exitValue() != 0) { log.error("Failed to sort index files, sort exited with " + "return code " + p.exitValue()); } } catch (Exception e) { log.error("Failed to aggregate indexes ", e); } }
/** * Requires a map of environment variables (P4USER, P4CLIENT, P4PORT, etc) * * @param environment */ public CmdLineExecutor(Map<String, String> environment) { args = new ArrayList<String>(); builder = new ProcessBuilder(args); Map<String, String> env = builder.environment(); for (Map.Entry<String, String> entry : environment.entrySet()) { // if(key.equals("P4PASSWD")) // continue; // logger.warn("Settin env: " + key + " = " + environment.get(key)); env.put(entry.getKey(), entry.getValue()); } }
public static void call(String command, ZarkovTask parent, String sdk) { _task = parent; try { ZarkovMonitor.addMessage("\n\n----------- COMMAND -----------"); ZarkovMonitor.addMessage(command + "\n\n"); ZarkovMonitor.addMessage("----------- OUTPUT -----------"); ArrayList<String> calls = new ArrayList<String>(); String osName = System.getProperty("os.name"); if (osName.contains("Windows")) { calls.add(sdk + "\\bin\\adl.exe"); } if (osName.contains("Mac") || osName.contains("Linux")) { calls.add(sdk + "/bin/adl"); } String[] commandlist = command.split(" "); for (int i = 1; i < commandlist.length; i++) { calls.add(commandlist[i]); } _pb = new ProcessBuilder(calls); Map<String, String> env = _pb.environment(); env.put("-Xms32m", ""); env.put("-Xmx256m", ""); _p = _pb.start(); InputReader errReader = new InputReader(_p.getErrorStream(), _task); Thread errThread = new Thread(errReader); errThread.start(); InputReader inReader = new InputReader(_p.getInputStream(), _task); Thread inThread = new Thread(inReader); inThread.start(); int exitval = _p.waitFor(); if (exitval != 0) { _task.callException(); } _task.quit(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }