List of usage examples for java.lang ProcessBuilder directory
File directory
To view the source code for java.lang ProcessBuilder directory.
Click Source Link
From source file:org.pbccrc.zsls.utils.Shell.java
/** Run a command */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null;/*from w w w.j av a 2 s . c o m*/ ShellTimeoutTimerTask timeoutTimerTask = null; timedOut = new AtomicBoolean(false); completed = new AtomicBoolean(false); if (environment != null) { builder.environment().putAll(this.environment); } if (dir != null) { builder.directory(this.dir); } builder.redirectErrorStream(redirectErrorStream); if (Shell.WINDOWS) { synchronized (WindowsProcessLaunchLock) { // To workaround the race condition issue with child processes // inheriting unintended handles during process launch that can // lead to hangs on reading output and error streams, we // serialize process creation. More info available at: // http://support.microsoft.com/kb/315939 process = builder.start(); } } else { process = builder.start(); } if (timeOutInterval > 0) { timeOutTimer = new Timer("Shell command timeout"); timeoutTimerTask = new ShellTimeoutTimerTask(this); //One time scheduling. timeOutTimer.schedule(timeoutTimerTask, timeOutInterval); } 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() { boolean overErrMsg = false; try { String line = errReader.readLine(); while ((line != null) && !isInterrupted()) { if (!overErrMsg) { if (line.length() + errMsg.length() > ERR_MSG_BUFF_SIZE) overErrMsg = true; else { 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(); // make sure that the error thread exits joinThread(errThread); completed.set(true); //the timeout thread handling //taken care in finally block if (exitCode != 0) { throw new ExitCodeException(exitCode, errMsg.toString()); } } catch (InterruptedException ie) { throw new IOException(ie.toString()); } finally { if (timeOutTimer != null) { timeOutTimer.cancel(); } // close the input stream try { // JDK 7 tries to automatically drain the input streams for us // when the process exits, but since close is not synchronized, // it creates a race if we close the stream first and the same // fd is recycled. the stream draining thread will attempt to // drain that fd!! it may block, OOM, or cause bizarre behavior // see: https://bugs.openjdk.java.net/browse/JDK-8024521 // issue is fixed in build 7u60 InputStream stdout = process.getInputStream(); synchronized (stdout) { inReader.close(); } } catch (IOException ioe) { LOG.warn("Error while closing the input stream", ioe); } if (!completed.get()) { errThread.interrupt(); joinThread(errThread); } try { InputStream stderr = process.getErrorStream(); synchronized (stderr) { errReader.close(); } } catch (IOException ioe) { LOG.warn("Error while closing the error stream", ioe); } process.destroy(); lastTime = clock.getTime(); } }
From source file:com.devbury.mkremote.server.QuickLaunchServiceImpl.java
protected void runOnWindows(File f) throws Throwable { logger.debug("Windows launch failed. Trying work arounds"); String extention = f.getName().substring(f.getName().lastIndexOf(".")); ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "assoc", extention); Process proc = pb.start();/*from www. j av a 2s . c o m*/ Properties p = new Properties(); p.load(new BackslashFilterInputStream(proc.getInputStream())); String type = p.getProperty(extention); pb = new ProcessBuilder("cmd", "/C", "ftype", type); proc = pb.start(); p = new Properties(); p.load(new BackslashFilterInputStream(proc.getInputStream())); String exe = p.getProperty(type); logger.debug("exe is {}", exe); // see if windows media player is supposed to run this if (exe.toLowerCase().indexOf("wmplayer") != -1) { String program_files = System.getenv("ProgramFiles"); if (program_files == null) { program_files = "C:\\Program Files"; } logger.debug("Using custom windows media player launch"); pb = new ProcessBuilder(program_files + "\\Windows Media Player\\wmplayer.exe", f.getCanonicalPath()); pb.start(); } else { pb = new ProcessBuilder("cmd", "/C", f.getName()); pb.directory(f.getParentFile()); pb.start(); } }
From source file:com.cisco.dvbu.ps.common.util.ScriptExecutor.java
public int executeCommand(String errorFile) { int exitValue = -99; String prefix = "ScriptExecutor::"; String command = ""; try {//from w ww . ja va2 s . c o m // Print out the command and execution directory for (int i = 0; i < scriptArgsList.size(); i++) { command = command + scriptArgsList.get(i) + " "; } if (logger.isDebugEnabled()) { logger.debug(prefix + "-------------------------------------------------"); logger.debug(prefix + "Command: " + CommonUtils.maskCommand(command)); logger.debug(prefix + "Exec Dir: " + execFromDir.toString()); } // Build a new process to execute ProcessBuilder pb = new ProcessBuilder(scriptArgsList); // Setup the environment variables Map<String, String> env = pb.environment(); for (int i = 0; i < envList.size(); i++) { String envVar = envList.get(i).toString(); StringTokenizer st = new StringTokenizer(envVar, "="); if (st.hasMoreTokens()) { String property = st.nextToken(); String propertyVal = ""; try { propertyVal = st.nextToken(); } catch (Exception e) { } env.put(property, propertyVal); if (logger.isDebugEnabled()) { logger.debug(prefix + "Env Var: " + CommonUtils.maskCommand(envVar)); } } } if (logger.isDebugEnabled()) { logger.debug(prefix + "-------------------------------------------------"); } // Setup up the execute from directory File execDir = new File(execFromDir); pb.directory(execDir); if (logger.isDebugEnabled()) { logger.debug(""); logger.debug("ProcessBuilder::pb.command: " + CommonUtils.maskCommand(pb.command().toString())); logger.debug("ProcessBuilder::pb.directory: " + pb.directory().toString()); logger.debug("ProcessBuilder::pb.directory.getAbsolutePath: " + pb.directory().getAbsolutePath()); logger.debug("ProcessBuilder::pb.directory.getCanonicalPath: " + pb.directory().getCanonicalPath()); logger.debug(""); logger.debug("ProcessBuilder::pb.environment: " + CommonUtils.maskCommand(pb.environment().toString())); logger.debug(prefix + "-------------------------------------------------"); logger.debug(""); } // Execute the command Process process = pb.start(); OutputStream stdOutput = process.getOutputStream(); InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); inputStreamHandler = new ScriptStreamHandler(inputStream, stdOutput); errorStreamHandler = new ScriptStreamHandler(errorStream); inputStreamHandler.start(); errorStreamHandler.start(); exitValue = process.waitFor(); if (logger.isDebugEnabled()) { logger.debug(prefix + "exitValue for process.waitFor is: " + exitValue); } if (exitValue > 0) { logger.error("Error executing command=" + CommonUtils.maskCommand(command)); logger.error("Error=" + CommonUtils.maskCommand(getStandardErrorFromCommand().toString())); } else { if (logger.isInfoEnabled()) { logger.info("Successfully executed command:\n" + CommonUtils.maskCommand(command)); logger.info("Output:\n" + getStandardOutputFromCommand().toString()); } } } catch (IOException e) { CompositeLogger.logException(e, e.getMessage()); throw new CompositeException(e); } catch (InterruptedException e) { CompositeLogger.logException(e, e.getMessage()); throw new CompositeException(e); } return exitValue; }
From source file:it.drwolf.ridire.session.CrawlerManager.java
@Restrict("#{s:hasRole('Admin')}") public String startCrawlerEngine() throws HeritrixNotStartingException { String launchCommand = this.getHeritrixBinPath() + CrawlerManager.FILE_SEPARATOR + this.entityManager .find(CommandParameter.class, CommandParameter.HERITRIX_LAUNCH_KEY).getCommandValue(); // + " -a "/*from w w w . j av a 2 s . c o m*/ // + this.entityManager.find(CrawlerCommand.class, // CrawlerCommand.HERITRIX_ADMINPW_KEY).getCommandValue(); ProcessBuilder pb = new ProcessBuilder(); pb.directory(new File(this.getHeritrixBinPath())); pb.command(launchCommand, "-a", "admin:" + this.entityManager.find(CommandParameter.class, CommandParameter.HERITRIX_ADMINPW_KEY) .getCommandValue(), "-p", this.entityManager.find(Parameter.class, Parameter.ENGINE_PORT.getKey()).getValue()); try { pb.start(); // try CONN_ATTEMPTS times to get connection to heritrix for (int i = 0; i < CrawlerManager.CONN_ATTEMPTS; i++) { Thread.sleep(10000); if (this.getCrawlerEngineStatus().equals(CrawlerManager.RUNNING)) { break; } } } catch (IOException e) { throw new HeritrixNotStartingException(); } catch (InterruptedException e) { throw new HeritrixNotStartingException(); } return "OK"; }
From source file:org.apache.htrace.impl.HTracedProcess.java
private HTracedProcess(Builder builder) throws Exception { this.htracedPath = Paths.get("target", "..", "go", "build", "htraced").toFile(); if (!this.htracedPath.exists()) { throw new RuntimeException("No htraced binary exists at " + this.htracedPath); }/*from w ww . j a va 2 s . c om*/ this.dataDir = new DataDir(); // Create a notifier socket bound to a random port. ServerSocket listener = new ServerSocket(0); boolean success = false; Process process = null; HttpClient http = null; try { // Use a random port for the web address. No 'scheme' yet. String random = builder.host + ":0"; String logPath = new File(dataDir.get(), "log.txt").getAbsolutePath(); // Pass cmdline args to htraced to it uses our test dir for data. ProcessBuilder pb = new ProcessBuilder(htracedPath.getAbsolutePath(), "-Dlog.level=TRACE", "-Dlog.path=" + logPath, "-Dweb.address=" + random, "-Dhrpc.address=" + random, "-Ddata.store.clear=true", "-Dstartup.notification.address=localhost:" + listener.getLocalPort(), "-Ddata.store.directories=" + dataDir.get().getAbsolutePath()); // Set HTRACED_CONF_DIR to the temporary directory we just created, to // ensure that it doesn't pull in any other configuration file that might // be on this test machine. Map<String, String> env = pb.environment(); env.put("HTRACED_CONF_DIR", dataDir.get().getAbsolutePath()); // Remove any HTRACED_WEB_DIR variable that might be set, to ensure that // we use the default value (which finds the local web files by relative // path). env.remove("HTRACED_WEB_DIR"); pb.redirectErrorStream(true); // Inherit STDERR/STDOUT i/o; dumps on console for now. Can add logs later. pb.inheritIO(); pb.directory(dataDir.get()); //assert pb.redirectInput() == Redirect.PIPE; //assert pb.redirectOutput().file() == dataDir; process = pb.start(); assert process.getInputStream().read() == -1; StartupNotificationData data = readStartupNotification(listener); httpAddr = data.httpAddr; hrpcAddr = data.hrpcAddr; LOG.info("Started htraced process " + data.processId + " with http " + "address " + data.httpAddr + ", logging to " + logPath); http = RestBufferManager.createHttpClient(60000L, 60000L); http.start(); success = true; } finally { if (!success) { // Clean up after failure if (process != null) { process.destroy(); process = null; } if (http != null) { http.stop(); } } delegate = process; listener.close(); httpClient = http; } }
From source file:com.searchcode.app.jobs.IndexSvnRepoJob.java
public RepositoryChanged checkoutSvnRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, boolean useCredentials) { boolean successful = false; Singleton.getLogger().info("Attempting to checkout " + repoRemoteLocation); try {/*from w ww .jav a2 s . c o m*/ File f = new File(repoLocations); if (!f.exists()) { f.mkdir(); } ProcessBuilder processBuilder; // http://serverfault.com/questions/158349/how-to-stop-subversion-from-prompting-about-server-certificate-verification-fai // http://stackoverflow.com/questions/34687/subversion-ignoring-password-and-username-options#38386 if (useCredentials) { processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "checkout", "--no-auth-cache", "--non-interactive", repoRemoteLocation, repoName); } else { processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "checkout", "--no-auth-cache", "--non-interactive", "--username", repoUserName, "--password", repoPassword, repoRemoteLocation, repoName); } processBuilder.directory(new File(repoLocations)); Process process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { Singleton.getLogger().info(line); } successful = true; } catch (IOException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + "\n with message: " + ex.getMessage()); } RepositoryChanged repositoryChanged = new RepositoryChanged(successful); repositoryChanged.setClone(true); return repositoryChanged; }
From source file:org.pentaho.di.job.entries.shell.JobEntryShell.java
private void executeShell(Result result, List<RowMetaAndData> cmdRows, String[] args) { FileObject fileObject = null; String realScript = null;// ww w . j a v a 2 s .c om FileObject tempFile = null; try { // What's the exact command? String[] base = null; List<String> cmds = new ArrayList<String>(); if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "JobShell.RunningOn", Const.getOS())); } if (insertScript) { realScript = environmentSubstitute(script); } else { String realFilename = environmentSubstitute(getFilename()); fileObject = KettleVFS.getFileObject(realFilename, this); } if (Const.getOS().equals("Windows 95")) { base = new String[] { "command.com", "/C" }; if (insertScript) { tempFile = KettleVFS.createTempFile("kettle", "shell.bat", environmentSubstitute(workDirectory), this); fileObject = createTemporaryShellFile(tempFile, realScript); } } else if (Const.getOS().startsWith("Windows")) { base = new String[] { "cmd.exe", "/C" }; if (insertScript) { tempFile = KettleVFS.createTempFile("kettle", "shell.bat", environmentSubstitute(workDirectory), this); fileObject = createTemporaryShellFile(tempFile, realScript); } } else { if (insertScript) { tempFile = KettleVFS.createTempFile("kettle", "shell", environmentSubstitute(workDirectory), this); fileObject = createTemporaryShellFile(tempFile, realScript); } base = new String[] { KettleVFS.getFilename(fileObject) }; } // Construct the arguments... if (argFromPrevious && cmdRows != null) { // Add the base command... for (int i = 0; i < base.length; i++) { cmds.add(base[i]); } if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) { // for windows all arguments including the command itself // need to be // included in 1 argument to cmd/command. StringBuffer cmdline = new StringBuffer(300); cmdline.append('"'); cmdline.append(Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject))); // Add the arguments from previous results... for (int i = 0; i < cmdRows.size(); i++) { // Normally just one row, but once in a while to remain compatible we have multiple. RowMetaAndData r = cmdRows.get(i); for (int j = 0; j < r.size(); j++) { cmdline.append(' '); cmdline.append(Const.optionallyQuoteStringByOS(r.getString(j, null))); } } cmdline.append('"'); cmds.add(cmdline.toString()); } else { // Add the arguments from previous results... for (int i = 0; i < cmdRows.size(); i++) { // Normally just one row, but once in a while to remain compatible we have multiple. RowMetaAndData r = cmdRows.get(i); for (int j = 0; j < r.size(); j++) { cmds.add(Const.optionallyQuoteStringByOS(r.getString(j, null))); } } } } else if (args != null) { // Add the base command... for (int i = 0; i < base.length; i++) { cmds.add(base[i]); } if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) { // for windows all arguments including the command itself // need to be // included in 1 argument to cmd/command. StringBuffer cmdline = new StringBuffer(300); cmdline.append('"'); cmdline.append(Const.optionallyQuoteStringByOS(KettleVFS.getFilename(fileObject))); for (int i = 0; i < args.length; i++) { cmdline.append(' '); cmdline.append(Const.optionallyQuoteStringByOS(args[i])); } cmdline.append('"'); cmds.add(cmdline.toString()); } else { for (int i = 0; i < args.length; i++) { cmds.add(args[i]); } } } StringBuffer command = new StringBuffer(); Iterator<String> it = cmds.iterator(); boolean first = true; while (it.hasNext()) { if (!first) { command.append(' '); } else { first = false; } command.append(it.next()); } if (log.isBasic()) { logBasic(BaseMessages.getString(PKG, "JobShell.ExecCommand", command.toString())); } // Build the environment variable list... ProcessBuilder procBuilder = new ProcessBuilder(cmds); Map<String, String> env = procBuilder.environment(); String[] variables = listVariables(); for (int i = 0; i < variables.length; i++) { env.put(variables[i], getVariable(variables[i])); } if (getWorkDirectory() != null && !Const.isEmpty(Const.rtrim(getWorkDirectory()))) { String vfsFilename = environmentSubstitute(getWorkDirectory()); File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename, this))); procBuilder.directory(file); } Process proc = procBuilder.start(); // any error message? StreamLogger errorLogger = new StreamLogger(log, proc.getErrorStream(), "(stderr)", true); // any output? StreamLogger outputLogger = new StreamLogger(log, proc.getInputStream(), "(stdout)"); // kick them off Thread errorLoggerThread = new Thread(errorLogger); errorLoggerThread.start(); Thread outputLoggerThread = new Thread(outputLogger); outputLoggerThread.start(); proc.waitFor(); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobShell.CommandFinished", command.toString())); } // What's the exit status? result.setExitStatus(proc.exitValue()); if (result.getExitStatus() != 0) { if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobShell.ExitStatus", environmentSubstitute(getFilename()), "" + result.getExitStatus())); } result.setNrErrors(1); } // wait until loggers read all data from stdout and stderr errorLoggerThread.join(); outputLoggerThread.join(); // close the streams // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations proc.getErrorStream().close(); proc.getOutputStream().close(); } catch (IOException ioe) { logError(BaseMessages.getString(PKG, "JobShell.ErrorRunningShell", environmentSubstitute(getFilename()), ioe.toString()), ioe); result.setNrErrors(1); } catch (InterruptedException ie) { logError(BaseMessages.getString(PKG, "JobShell.Shellinterupted", environmentSubstitute(getFilename()), ie.toString()), ie); result.setNrErrors(1); } catch (Exception e) { logError(BaseMessages.getString(PKG, "JobShell.UnexpectedError", environmentSubstitute(getFilename()), e.toString()), e); result.setNrErrors(1); } finally { // If we created a temporary file, remove it... // if (tempFile != null) { try { tempFile.delete(); } catch (Exception e) { BaseMessages.getString(PKG, "JobShell.UnexpectedError", tempFile.toString(), e.toString()); } } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } }