List of usage examples for java.lang ProcessBuilder environment
Map environment
To view the source code for java.lang ProcessBuilder environment.
Click Source Link
From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java
private void setEnv(TesseractOCRConfig config, ProcessBuilder pb) { String tessdataPrefix = "TESSDATA_PREFIX"; Map<String, String> env = pb.environment(); if (!config.getTessdataPath().isEmpty()) { env.put(tessdataPrefix, config.getTessdataPath()); } else if (!config.getTesseractPath().isEmpty()) { env.put(tessdataPrefix, config.getTesseractPath()); }/*from ww w. ja v a 2 s . com*/ }
From source file:com.android.ide.common.process.MtlProcessExecutor.java
public ListenableFuture<ProcessResult> submit(@NonNull ProcessInfo processInfo, @NonNull final ProcessOutputHandler processOutputHandler) { final List<String> command = buildCommand(processInfo); mLogger.info("command: " + Joiner.on(' ').join(command)); final SettableFuture<ProcessResult> result = SettableFuture.create(); try {/* w w w. j a v a2s .c o m*/ // Launch the command line process. ProcessBuilder processBuilder = new ProcessBuilder(buildCommand(processInfo)); Map<String, Object> envVariableMap = processInfo.getEnvironment(); if (!envVariableMap.isEmpty()) { Map<String, String> env = processBuilder.environment(); for (Map.Entry<String, Object> entry : envVariableMap.entrySet()) { env.put(entry.getKey(), entry.getValue().toString()); } } else { Map<String, String> env = processBuilder.environment(); env.putAll(System.getenv()); } if (processInfo instanceof MtlProcessInfo) { MtlProcessInfo mtlProcessInfo = (MtlProcessInfo) processInfo; if (StringUtils.isNotEmpty(mtlProcessInfo.getWorkspace())) { processBuilder.directory(new File(mtlProcessInfo.getWorkspace())); } } // Start the process. Process process = processBuilder.start(); // Grab the output, and the exit code. final ProcessOutput output = processOutputHandler.createOutput(); ListenableFuture<Integer> outputFuture = grabProcessOutput(process, output); Futures.addCallback(outputFuture, new FutureCallback<Integer>() { @Override public void onSuccess(Integer exit) { try { output.close(); processOutputHandler.handleOutput(output); result.set(new ProcessResultImpl(command, exit)); } catch (Exception e) { result.set(new ProcessResultImpl(command, e)); } } @Override public void onFailure(@Nullable Throwable t) { result.set(new ProcessResultImpl(command, t)); } }); } catch (Exception e) { result.set(new ProcessResultImpl(command, e)); } return result; }
From source file:com.thoughtworks.go.util.ProcessManager.java
public ProcessWrapper createProcess(String[] commandLine, String commandLineForDisplay, File workingDir, Map<String, String> envMap, EnvironmentVariableContext environmentVariableContext, ConsoleOutputStreamConsumer consumer, String processTag, String encoding, String errorPrefix) { ProcessBuilder processBuilder = new ProcessBuilder(commandLine); if (LOG.isDebugEnabled()) { LOG.debug("Executing: " + commandLineForDisplay); }//from w w w . j a v a 2s . co m if (workingDir != null) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("[Command Line] Using working directory %s to start the process.", workingDir.getAbsolutePath())); } processBuilder.directory(workingDir); } environmentVariableContext.setupRuntimeEnvironment(processBuilder.environment(), consumer); processBuilder.environment().putAll(envMap); Process process = startProcess(processBuilder, commandLineForDisplay); ProcessWrapper processWrapper = new ProcessWrapper(process, processTag, commandLineForDisplay, consumer, encoding, errorPrefix); processMap.putIfAbsent(process, processWrapper); return processWrapper; }
From source file:edu.isi.wings.execution.engine.api.impl.distributed.DistributedExecutionEngine.java
@Override public ProcessStatus call() throws Exception { File tempdir = File.createTempFile(planName + "-", "-" + exeName); if (!tempdir.delete() || !tempdir.mkdirs()) throw new Exception("Cannot create temp directory"); ProcessStatus status = new ProcessStatus(); try {//from w ww . j a v a 2 s. co m File codef = new File(this.codeBinary); codef.setExecutable(true); PrintWriter fout = null; if (outfilepath != null) { File f = new File(outfilepath); f.getParentFile().mkdirs(); fout = new PrintWriter(f); } ProcessBuilder pb = new ProcessBuilder(args); pb.directory(tempdir); pb.redirectErrorStream(true); // Set environment variables for (String var : this.environment.keySet()) pb.environment().put(var, this.environment.get(var)); this.process = pb.start(); // Read output stream StreamGobbler outputGobbler = new StreamGobbler(this.process.getInputStream(), fout); outputGobbler.start(); // Wait for the process to exit this.process.waitFor(); status.setExitValue(this.process.exitValue()); status.setLog(outputGobbler.getLog()); } catch (InterruptedException e) { if (this.process != null) { //System.out.println("Stopping remote process"); this.process.destroy(); } status.setLog("!! Stopping Remotely !! .. " + exeName); status.setExitValue(-1); } catch (Exception e) { status.setLog(e.getMessage()); status.setExitValue(-1); } // Delete temp directory FileUtils.deleteDirectory(tempdir); return status; }
From source file:com.axelor.studio.service.ModuleRecorderService.java
private String restartServer(boolean reset) throws AxelorException { String logFile = checkParams("studio.restart.log", AppSettings.get().get("studio.restart.log"), true); String warPath = getWarPath(); try {/*from w w w . j a va2 s .co m*/ String scriptPath = getRestartScriptPath(); ProcessBuilder processBuilder; if (reset) { processBuilder = new ProcessBuilder(scriptPath, warPath, "reset"); } else { processBuilder = new ProcessBuilder(scriptPath, warPath); } processBuilder.environment().putAll(ENV); processBuilder.redirectOutput(new File(logFile)); processBuilder.redirectError(new File(logFile)); processBuilder.start(); } catch (IOException e) { throw new AxelorException(e, 5); } if (reset) { return I18n.get("App reset sucessfully"); } return I18n.get("App updated successfully"); }
From source file:hoot.services.command.CommandRunner.java
public CommandResult exec(String[] pCmd, Map<String, String> pEnv, boolean useSysEnv, File dir, Writer pOut, Writer pErr) throws IOException, InterruptedException { int out = 0;/*from w w w. ja v a 2 s . co m*/ 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)); } builder.directory(dir); 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; }
From source file:hoot.services.command.CommandRunner.java
public CommandResult exec(String[] pCmd, Map<String, String> pEnv, boolean useSysEnv, Writer pOut, Writer pErr) throws IOException, InterruptedException { int out = 0;// w ww . j a va 2 s .c om 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; }
From source file:eu.udig.omsbox.core.OmsScriptExecutor.java
/** * Execute an OMS script./*from w ww .jav a2 s . c om*/ * * @param script the script file or the script string. * @param internalStream * @param errorStream * @param loggerLevelGui the log level as presented in the GUI, can be OFF|ON. This is not the OMS logger level, which * in stead has to be picked from the {@link OmsBoxConstants#LOGLEVELS_MAP}. * @param ramLevel the heap size to use in megabytes. * @return the process. * @throws Exception */ public Process exec(String script, final PrintStream internalStream, final PrintStream errorStream, String loggerLevelGui, String ramLevel) throws Exception { if (loggerLevelGui == null) loggerLevelGui = OmsBoxConstants.LOGLEVEL_GUI_OFF; File scriptFile = new File(script); if (!scriptFile.exists()) { // if the file doesn't exist, it is a script, let's put it into a file scriptFile = File.createTempFile("omsbox_script_", ".oms"); BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(scriptFile)); bw.write(script); } finally { bw.close(); } } else { // it is a script in a file, read it to log it BufferedReader br = null; StringBuilder sb = new StringBuilder(); try { br = new BufferedReader(new FileReader(scriptFile)); String line = null; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } } finally { br.close(); } script = sb.toString(); } // tmp folder String tempdir = System.getProperty("java.io.tmpdir"); File omsTmp = new File(tempdir + File.separator + "oms"); if (!omsTmp.exists()) omsTmp.mkdirs(); List<String> arguments = new ArrayList<String>(); arguments.add(javaFile); // ram usage String ramExpr = "-Xmx" + ramLevel + "m"; arguments.add(ramExpr); // modules jars List<String> modulesJars = OmsModulesManager.getInstance().getModulesJars(); StringBuilder sb = new StringBuilder(); for (String moduleJar : modulesJars) { sb.append(File.pathSeparator).append(moduleJar); } String modulesJarsString = sb.toString().replaceFirst(File.pathSeparator, ""); String resourcesFlag = "-Doms.sim.resources=\"" + modulesJarsString + "\""; arguments.add(resourcesFlag); // grass gisbase String grassGisbase = OmsBoxPlugin.getDefault().getGisbasePreference(); if (grassGisbase != null && grassGisbase.length() > 0) { arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_GISBASE_KEY + "=" + grassGisbase); } String grassShell = OmsBoxPlugin.getDefault().getShellPreference(); if (grassShell != null && grassShell.length() > 0) { arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_SHELL_KEY + "=" + grassShell); } // all the arguments arguments.add("-cp"); arguments.add(classPath); arguments.add(CLI.class.getCanonicalName()); arguments.add("-r "); arguments.add("\"" + scriptFile.getAbsolutePath() + "\""); String homeDir = System.getProperty("java.io.tmpdir"); File homeFile = new File(homeDir); StringBuilder runSb = new StringBuilder(); for (String arg : arguments) { runSb.append(arg).append(" "); } String[] args; if (Platform.getOS().equals(Platform.OS_WIN32)) { File tmpRunFile = new File(homeFile, "udig_spatialtoolbox.bat"); FileUtils.writeStringToFile(tmpRunFile, "@echo off\n" + runSb.toString()); args = new String[] { "cmd", "/c", tmpRunFile.getAbsolutePath() }; } else { File tmpRunFile = new File(homeFile, "udig_spatialtoolbox.sh"); FileUtils.writeStringToFile(tmpRunFile, runSb.toString()); args = new String[] { "sh", tmpRunFile.getAbsolutePath() }; } // {javaFile, ramExpr, resourcesFlag, "-cp", classPath, // CLI.class.getCanonicalName(), "-r", // scriptFile.getAbsolutePath()}; ProcessBuilder processBuilder = new ProcessBuilder(args); // work in home // processBuilder.directory(homeFile); // environment Map<String, String> environment = processBuilder.environment(); // environment.put("CLASSPATH", classPath); final Process process = processBuilder.start(); internalStream.println( "Process started: " + new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS)); internalStream.println(""); // command launched if (loggerLevelGui.equals(OmsBoxConstants.LOGLEVEL_GUI_ON)) { internalStream.println("------------------------------>8----------------------------"); internalStream.println("Launching command: "); internalStream.println("------------------"); List<String> command = processBuilder.command(); for (String arg : command) { internalStream.print(arg); internalStream.print(" "); } internalStream.println("\n"); internalStream.println("(you can run the above from command line, customizing the content)"); internalStream.println("----------------------------------->8---------------------------------"); internalStream.println(""); // script run internalStream.println("Script run: "); internalStream.println("-----------"); internalStream.println(script); internalStream.println(""); internalStream.println("------------------------------>8----------------------------"); internalStream.println(""); // environment used internalStream.println("Environment used: "); internalStream.println("-----------------"); Set<Entry<String, String>> entrySet = environment.entrySet(); for (Entry<String, String> entry : entrySet) { internalStream.print(entry.getKey()); internalStream.print(" =\t"); internalStream.println(entry.getValue()); } internalStream.println("------------------------------>8----------------------------"); internalStream.println(""); } internalStream.println(""); isRunning = true; new Thread() { public void run() { BufferedReader br = null; try { InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { internalStream.println(line); } } catch (Exception e) { e.printStackTrace(); errorStream.println(e.getLocalizedMessage()); } finally { if (br != null) try { br.close(); } catch (IOException e) { e.printStackTrace(); } isRunning = false; updateListeners(); } internalStream.println(""); internalStream.println(""); internalStream.println("Process finished: " + new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS)); }; }.start(); new Thread() { public void run() { BufferedReader br = null; try { InputStream is = process.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { /* * remove of ugly recurring geotools warnings. Not nice, but * at least users do not get confused. */ if (ConsoleMessageFilter.doRemove(line)) { continue; } errorStream.println(line); } } catch (Exception e) { e.printStackTrace(); errorStream.println(e.getLocalizedMessage()); } finally { if (br != null) try { br.close(); } catch (IOException e) { e.printStackTrace(); } } }; }.start(); return process; }
From source file:org.apache.accumulo.minicluster.MiniAccumuloCluster.java
private Process exec(Class<? extends Object> clazz, List<String> extraJvmOpts, String... args) throws IOException { String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; String classpath = getClasspath(); String className = clazz.getName(); ArrayList<String> argList = new ArrayList<String>(); argList.addAll(Arrays.asList(javaBin, "-Dproc=" + clazz.getSimpleName(), "-cp", classpath)); argList.add("-Djava.library.path=" + config.getLibDir()); argList.addAll(extraJvmOpts);/*from w w w . j a va2 s .c o m*/ argList.addAll(Arrays.asList("-XX:+UseConcMarkSweepGC", "-XX:CMSInitiatingOccupancyFraction=75", Main.class.getName(), className)); argList.addAll(Arrays.asList(args)); ProcessBuilder builder = new ProcessBuilder(argList); builder.environment().put("ACCUMULO_HOME", config.getDir().getAbsolutePath()); builder.environment().put("ACCUMULO_LOG_DIR", config.getLogDir().getAbsolutePath()); builder.environment().put("ACCUMULO_CONF_DIR", config.getConfDir().getAbsolutePath()); Process process = builder.start(); LogWriter lw; lw = new LogWriter(process.getErrorStream(), new File(config.getLogDir(), clazz.getSimpleName() + "_" + process.hashCode() + ".err")); logWriters.add(lw); lw.start(); lw = new LogWriter(process.getInputStream(), new File(config.getLogDir(), clazz.getSimpleName() + "_" + process.hashCode() + ".out")); logWriters.add(lw); lw.start(); return process; }
From source file:jp.co.tis.gsp.tools.dba.dialect.PostgresqlDialect.java
@Override public void exportSchema(ExportParams params) throws MojoExecutionException { BufferedInputStream in = null; FileOutputStream out = null;//from w ww. j a v a 2 s . co m try { File dumpFile = params.getDumpFile(); String user = params.getUser(); String password = params.getPassword(); String schema = params.getSchema(); ProcessBuilder pb = new ProcessBuilder("pg_dump", "--host=" + getHost(), "--port=" + getPort(), "--username=" + user, "--schema=" + schema, "-c", getDatabase()); pb.redirectErrorStream(true); if (StringUtils.isNotEmpty(password)) { // ?????????? pb.environment().put("PGPASSWORD", password); } Process process = pb.start(); in = new BufferedInputStream(process.getInputStream()); out = FileOutputStreamUtil.create(dumpFile); byte[] buf = new byte[4096]; while (true) { int res = in.read(buf); if (res <= 0) break; out.write(buf, 0, res); } } catch (IOException e) { throw new MojoExecutionException("??", e); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }