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.ballerinalang.test.context.BMainInstance.java
/** * Executing the sh or bat file to start the server and returns the logs printed to stdout. * * @param command command to run/*from ww w . j a v a 2 s.c o m*/ * @param args command line arguments to pass when executing the sh or bat file * @param envProperties environmental properties to be appended to the environment * @param commandDir where to execute the command * @return logs printed to std out * @throws BallerinaTestException if starting services failed or if an error occurs when reading the stdout */ public String runMainAndReadStdOut(String command, String[] args, Map<String, String> envProperties, String commandDir) throws BallerinaTestException { String scriptName = Constant.BALLERINA_SERVER_SCRIPT_NAME; String[] cmdArray; try { if (Utils.getOSName().toLowerCase(Locale.ENGLISH).contains("windows")) { cmdArray = new String[] { "cmd.exe", "/c", balServer.getServerHome() + File.separator + "bin" + File.separator + scriptName + ".bat", command }; } else { cmdArray = new String[] { "bash", balServer.getServerHome() + File.separator + "bin/" + scriptName, command }; } String[] cmdArgs = Stream.concat(Arrays.stream(cmdArray), Arrays.stream(args)).toArray(String[]::new); ProcessBuilder processBuilder = new ProcessBuilder(cmdArgs).directory(new File(commandDir)); Map<String, String> env = processBuilder.environment(); env.putAll(envProperties); Process process = processBuilder.start(); // Give a small timeout so that the output is given. Thread.sleep(5000); String output = ""; try (InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream()); BufferedReader buffer = new BufferedReader(inputStreamReader)) { output = buffer.lines().collect(Collectors.joining("\n")); } catch (Exception e) { throw new BallerinaTestException("Error when reading from the stdout ", e); } process.waitFor(); return output; } catch (IOException e) { throw new BallerinaTestException("Error executing ballerina", e); } catch (InterruptedException e) { throw new BallerinaTestException("Error waiting for execution to finish", e); } }
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 av a2 s . 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:org.cloudata.core.common.ShellCommand.java
/** Run a command */ private void runCommand() throws IOException { if (onlyUnix() && WINDOWS) { return;// w w w . ja v a2s .c om } ProcessBuilder builder = new ProcessBuilder(getExecString()); boolean completed = false; if (environment != null) { builder.environment().putAll(this.environment); } if (dir != null) { builder.directory(this.dir); } process = builder.start(); final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream())); final StringBuffer errMsg = new StringBuffer(); // read error and input streams as this would free up the buffers // free the error stream buffer Thread errThread = new Thread() { @Override public void run() { try { String line = errReader.readLine(); while ((line != null) && !isInterrupted()) { errMsg.append(line); errMsg.append(System.getProperty("line.separator")); line = errReader.readLine(); } } catch (IOException ioe) { LOG.warn("Error reading the error stream", ioe); } } }; try { errThread.start(); } catch (IllegalStateException ise) { } try { parseExecResult(inReader); // parse the output // clear the input stream buffer String line = inReader.readLine(); while (line != null) { line = inReader.readLine(); } // wait for the process to finish and check the exit code exitCode = process.waitFor(); try { // make sure that the error thread exits errThread.join(); } catch (InterruptedException ie) { LOG.warn("Interrupted while reading the error stream", ie); } completed = true; if (exitCode != 0) { throw new ExitCodeException(exitCode, errMsg.toString()); } } catch (InterruptedException ie) { throw new IOException(ie.toString()); } finally { // close the input stream try { inReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing the input stream", ioe); } if (!completed) { errThread.interrupt(); } try { errReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing the error stream", ioe); } process.destroy(); lastTime = System.currentTimeMillis(); } }
From source file:cn.dockerfoundry.ide.eclipse.server.core.internal.ProcessLauncher.java
/** * Returns when the process has exited without errors. This will wait for * the process to exist, therefore will block the current thread in which it * is running. If any errors occur, throws CoreException CoreException * @throws CoreException if any errors occur while the process is being * launched//from w ww . jav a 2s. c o m */ public void run() throws CoreException { Exception error = null; Process p = null; try { List<String> processArguments = getProcessArguments(); if (processArguments == null || processArguments.isEmpty()) { throw new CoreException(getErrorStatus("No process arguments were found")); //$NON-NLS-1$ } else { ProcessBuilder processBuilder = new ProcessBuilder(processArguments); // Set any environment variables Map<String, String> envVars = getEnvironmentVariables(); if (envVars != null) { Map<String, String> actualVars = processBuilder.environment(); if (actualVars != null) { for (Entry<String, String> entry : envVars.entrySet()) { actualVars.put(entry.getKey(), entry.getValue()); } } } p = processBuilder.start(); if (p == null) { throw new CoreException(getErrorStatus("No process was created.")); //$NON-NLS-1$ } else { StringBuffer errorBuffer = new StringBuffer(); // Clear the input and error streams to prevent the // process // from blocking handleProcessIOAsynch(p, null, errorBuffer); p.waitFor(); if (errorBuffer.length() > 0) { throw new CoreException(getErrorStatus(errorBuffer.toString())); } else if (p.exitValue() != 0) { throw new CoreException(getErrorStatus("process exit value: " + p.exitValue())); //$NON-NLS-1$ } } } } catch (InterruptedException ex) { error = ex; } catch (IOException ioe) { error = ioe; } catch (SecurityException se) { error = se; } finally { if (p != null) { p.destroy(); } } if (error != null) { throw error instanceof CoreException ? (CoreException) error : CloudErrorUtil.toCoreException(error); } }
From source file:org.apache.slider.providers.agent.TestAgentClientProvider2.java
@Test public void testRunCommand() throws Exception { AgentClientProvider provider = new AgentClientProvider(null); File appPkgDir = new File("/tmp/pkg"); File agentPkgDir = new File("/tmp/agt"); File cmdDir = new File("/tmp/cmd"); String client_script = "scripts/abc.py"; List<String> commands = Arrays.asList("python", "-S", new File("/tmp/pkg").getAbsolutePath() + File.separator + "package" + File.separator + "scripts/abc.py", "INSTALL", new File("/tmp/cmd").getAbsolutePath() + File.separator + "command.json", new File("/tmp/pkg").getAbsolutePath() + File.separator + "package", new File("/tmp/cmd").getAbsolutePath() + File.separator + "command-out.json", "DEBUG"); ProcessBuilder pbMock = PowerMock.createMock(ProcessBuilder.class); Process procMock = PowerMock.createMock(Process.class); PowerMock.expectNew(ProcessBuilder.class, commands).andReturn(pbMock); expect(pbMock.environment()).andReturn(new HashMap<String, String>()).anyTimes(); expect(pbMock.start()).andReturn(procMock); expect(pbMock.command()).andReturn(new ArrayList<String>()); expect(procMock.waitFor()).andReturn(0); expect(procMock.exitValue()).andReturn(0); expect(procMock.getErrorStream()).andReturn(IOUtils.toInputStream("stderr", "UTF-8")); expect(procMock.getInputStream()).andReturn(IOUtils.toInputStream("stdout", "UTF-8")); PowerMock.replayAll();/* w w w .j av a2 s.com*/ provider.runCommand(appPkgDir, agentPkgDir, cmdDir, client_script); PowerMock.verifyAll(); }
From source file:org.sonar.application.process.ProcessLauncherImpl.java
private ProcessBuilder create(AbstractCommand<?> javaCommand, List<String> commands) { ProcessBuilder processBuilder = processBuilderSupplier.get(); processBuilder.command(commands);/*from www.j a va 2 s.c om*/ processBuilder.directory(javaCommand.getWorkDir()); Map<String, String> environment = processBuilder.environment(); environment.putAll(javaCommand.getEnvVariables()); javaCommand.getSuppressedEnvVariables().forEach(environment::remove); processBuilder.redirectErrorStream(true); return processBuilder; }
From source file:org.jajuk.services.players.WebRadioPlayerImpl.java
/** * (non-Javadoc)./*from w w w .j a v a2 s . c o m*/ * * @param radio * @param fVolume * * @throws IOException Signals that an I/O exception has occurred. * @throws JajukException the jajuk exception * * @see org.jajuk.players.IPlayerImpl#play(org.jajuk.base.File, float, long, * float) */ @Override public void play(WebRadio radio, float fVolume) throws IOException, JajukException { this.fVolume = fVolume; this.bOpening = true; this.bEOF = false; this.bitPerfect = Conf.getBoolean(Const.CONF_BIT_PERFECT); // Start ProcessBuilder pb = new ProcessBuilder(buildCommand(radio.getUrl(), 0)); Log.debug("Using this Mplayer command: {{" + pb.command() + "}}"); // Set all environment variables format: var1=xxx var2=yyy try { Map<String, String> env = pb.environment(); StringTokenizer st = new StringTokenizer(Conf.getString(Const.CONF_ENV_VARIABLES), " "); while (st.hasMoreTokens()) { StringTokenizer st2 = new StringTokenizer(st.nextToken(), "="); env.put(st2.nextToken(), st2.nextToken()); } // If needed, set proxy settings in format: // http_proxy=http://username:password@proxy.example.org:8080 if (Conf.getBoolean(Const.CONF_NETWORK_USE_PROXY)) { String sLogin = Conf.getString(Const.CONF_NETWORK_PROXY_LOGIN).trim(); String sHost = Conf.getString(Const.CONF_NETWORK_PROXY_HOSTNAME).trim(); int port = Conf.getInt(Const.CONF_NETWORK_PROXY_PORT); // Non anonymous proxy if (!StringUtils.isBlank(sLogin)) { String sPwd = UtilString.rot13(Conf.getString(Const.CONF_NETWORK_PROXY_PWD)); String sProxyConf = "http://" + sLogin + ':' + sPwd + '@' + sHost + ':' + port; env.put("http_proxy", sProxyConf); Log.debug("Using these proxy settings: " + sProxyConf); } // Anonymous proxy else { String sProxyConf = "http://" + sHost + ':' + port; env.put("http_proxy", sProxyConf); Log.debug("Using these proxy settings: " + sProxyConf); } } } catch (Exception e) { Log.error(e); } // Start mplayer proc = pb.start(); // start mplayer replies reader thread new ReaderThread().start(); // if opening, wait, 30 secs max int i = 0; while (bOpening && i < 30) { try { Thread.sleep(1000); i++; } catch (InterruptedException e) { Log.error(e); } } // If end of file already reached, it means that file cannot be read if (bEOF) { throw new JajukException(7); } // Get track length sendCommand("get_time_length"); }
From source file:org.apache.pulsar.functions.runtime.ProcessRuntime.java
private void startProcess() { deathException = null;// ww w . j a va 2s. com try { ProcessBuilder processBuilder = new ProcessBuilder(processArgs).inheritIO(); if (StringUtils.isNotEmpty(extraDependenciesDir)) { processBuilder.environment().put("PYTHONPATH", "${PYTHONPATH}:" + extraDependenciesDir); } secretsProviderConfigurator.configureProcessRuntimeSecretsProvider(processBuilder, instanceConfig.getFunctionDetails()); log.info("ProcessBuilder starting the process with args {}", String.join(" ", processBuilder.command())); process = processBuilder.start(); } catch (Exception ex) { log.error("Starting process failed", ex); deathException = ex; return; } try { int exitValue = process.exitValue(); log.error("Instance Process quit unexpectedly with return value " + exitValue); tryExtractingDeathException(); } catch (IllegalThreadStateException ex) { log.info("Started process successfully"); } }
From source file:org.apache.hadoop.hive.llap.cli.service.LlapServiceDriver.java
private int runPackagePy(Path tmpDir, Path scriptParent, String version, String outputDir) throws IOException, InterruptedException { Path scriptPath = new Path(new Path(scriptParent, "yarn"), "package.py"); List<String> scriptArgs = new ArrayList<>(cl.getArgs().length + 7); scriptArgs.addAll(Arrays.asList("python", scriptPath.toString(), "--input", tmpDir.toString(), "--output", outputDir, "--javaChild")); scriptArgs.addAll(Arrays.asList(cl.getArgs())); LOG.debug("Calling package.py via: " + scriptArgs); ProcessBuilder builder = new ProcessBuilder(scriptArgs); builder.redirectError(ProcessBuilder.Redirect.INHERIT); builder.redirectOutput(ProcessBuilder.Redirect.INHERIT); builder.environment().put("HIVE_VERSION", version); return builder.start().waitFor(); }