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.taverna.server.master.localworker.ForkRunFactory.java
/** * Makes the subprocess that manufactures runs. * //from w ww . j a v a 2 s . c o m * @throws Exception * If anything goes wrong. */ public void initFactory() throws Exception { if (factory != null) return; // Generate the arguments to use when spawning the subprocess factoryProcessName = state.getFactoryProcessNamePrefix() + randomUUID(); ProcessBuilder p = new ProcessBuilder(getJavaBinary()); p.command().addAll(asList(getExtraArguments())); p.command().add("-jar"); p.command().add(getServerWorkerJar()); p.command().add(getExecuteWorkflowScript()); p.command().add(factoryProcessName); p.redirectErrorStream(true); p.directory(new File(getProperty("javax.servlet.context.tempdir", getProperty("java.io.tmpdir")))); // Spawn the subprocess log.info("about to create subprocess: " + p.command()); factoryProcess = p.start(); Thread logger = new Thread(new OutputLogger(factoryProcessName, factoryProcess), factoryProcessName + ".Logger"); logger.setDaemon(true); logger.start(); // Wait for the subprocess to register itself in the RMI registry Calendar deadline = Calendar.getInstance(); deadline.add(SECOND, state.getWaitSeconds()); Exception lastException = null; lastStartupCheckCount = 0; while (deadline.after(Calendar.getInstance())) { try { sleep(state.getSleepMS()); lastStartupCheckCount++; log.info("about to look up resource called " + factoryProcessName); try { // Validate registry connection first getTheRegistry().list(); } catch (ConnectException ce) { log.warn("connection problems with registry", ce); } catch (ConnectIOException e) { log.warn("connection problems with registry", e); } factory = (RemoteRunFactory) getTheRegistry().lookup(factoryProcessName); log.info("successfully connected to factory subprocess " + factoryProcessName); if (interhost != null) factory.setInteractionServiceDetails(interhost, interport, interwebdav, interfeed); return; } catch (InterruptedException ie) { continue; } catch (NotBoundException nbe) { lastException = nbe; log.info("resource \"" + factoryProcessName + "\" not yet registered..."); continue; } catch (RemoteException re) { // Unpack a remote exception if we can lastException = re; try { if (re.getCause() != null) lastException = (Exception) re.getCause(); } catch (Throwable t) { // Ignore! } } catch (Exception e) { lastException = e; } } throw lastException; }
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;/* ww w . j ava 2 s. c o 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:com.thoughtworks.cruise.util.command.CommandLine.java
private Process createProcess(EnvironmentVariableContext environmentVariableContext, ConsoleOutputStreamConsumer consumer) { final String msgCommandInfo = "Executing: " + toString(getCommandLineForDisplay(), true); ProcessBuilder processBuilder = new ProcessBuilder(getCommandLine()); LOG.debug(msgCommandInfo);//from w w w . ja va 2 s . com if (workingDir != null) { LOG.debug("Using working directory " + workingDir.getAbsolutePath()); processBuilder.directory(workingDir); } setEnvironmentVariables(processBuilder, environmentVariableContext, consumer); processBuilder.environment().putAll(env); Process process; try { LOG.debug("START command " + msgCommandInfo); process = processBuilder.start(); LOG.debug("END command " + msgCommandInfo); } catch (IOException e) { throw new CommandLineException( "Error happens when " + msgCommandInfo + "\n Make sure this command can execute manually.", e); } return process; }
From source file:com.searchcode.app.jobs.IndexSvnRepoJob.java
public RepositoryChanged getDiffBetweenRevisions(String repoLocations, String repoName, String startRevision) { // svn diff -r 4000:HEAD --summarize --xml List<String> changedFiles = new ArrayList<>(); List<String> deletedFiles = new ArrayList<>(); try {/*from ww w. j a v a 2 s.c o m*/ ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "diff", "-r", startRevision + ":HEAD", "--summarize", "--xml"); processBuilder.directory(new File(repoLocations + repoName)); Process process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { Singleton.getLogger().info("svn diff: " + line); sb.append(Helpers.removeUTF8BOM(line)); } Singleton.getLogger().info("Before XML parsing: " + sb.toString()); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes())); doc.getDocumentElement().normalize(); Element node = (Element) doc.getElementsByTagName("diff").item(0); node = (Element) node.getElementsByTagName("paths").item(0); NodeList nList = node.getElementsByTagName("path"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String type = eElement.getAttribute("item"); String path = eElement.getTextContent(); if ("modified".equals(type) || "added".equals(type)) { changedFiles.add(path); } else { deletedFiles.add(path); } } } } catch (IOException | ParserConfigurationException | SAXException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + "\n with message: " + ex.getMessage()); } return new RepositoryChanged(true, changedFiles, deletedFiles); }
From source file:com.gochinatv.datasync.util.Shell.java
/** * Run a command//from w w w . j a va2 s .c om */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null; ShellTimeoutTimerTask timeoutTimerTask; timedOut = new AtomicBoolean(false); completed = new AtomicBoolean(false); if (environment != null) { builder.environment().putAll(this.environment); } if (dir != null) { builder.directory(this.dir); } process = builder.start(); if (timeOutInterval > 0) { timeOutTimer = new Timer(); 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() { 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 ignored) { } 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.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) && !timedOut.get()) { timeOutTimer.cancel(); } // close the input stream try { inReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing the input stream", ioe); } if (!completed.get()) { 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:com.searchcode.app.jobs.IndexGitRepoJob.java
/** * Only works if we have path to GIT/* ww w . j ava 2s. c o m*/ */ private List<CodeOwner> getBlameInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) { List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize); try { // -w is to ignore whitespace bug ProcessBuilder processBuilder = new ProcessBuilder(this.GITBINARYPATH, "blame", "-c", "-w", fileName); // The / part is required due to centos bug for version 1.1.1 processBuilder.directory(new File(repoLocations + "/" + repoName)); Process process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; DateFormat df = new SimpleDateFormat("yyyy-mm-dd kk:mm:ss"); HashMap<String, CodeOwner> owners = new HashMap<>(); boolean foundSomething = false; while ((line = br.readLine()) != null) { Singleton.getLogger().info("Blame line " + repoName + fileName + ": " + line); String[] split = line.split("\t"); if (split.length > 2 && split[1].length() != 0) { foundSomething = true; String author = split[1].substring(1); int commitTime = (int) (System.currentTimeMillis() / 1000); try { commitTime = (int) (df.parse(split[2]).getTime() / 1000); } catch (ParseException ex) { Singleton.getLogger().info("time parse expection for " + repoName + fileName); } if (owners.containsKey(author)) { CodeOwner codeOwner = owners.get(author); codeOwner.incrementLines(); int timestamp = codeOwner.getMostRecentUnixCommitTimestamp(); if (commitTime > timestamp) { codeOwner.setMostRecentUnixCommitTimestamp(commitTime); } owners.put(author, codeOwner); } else { owners.put(author, new CodeOwner(author, 1, commitTime)); } } } if (foundSomething == false) { // External call for CentOS issue String[] split = fileName.split("/"); if (split.length != 1) { codeOwners = getBlameInfoExternal(codeLinesSize, repoName, repoLocations, String.join("/", Arrays.asList(split).subList(1, split.length))); } } else { codeOwners = new ArrayList<>(owners.values()); } } catch (IOException | StringIndexOutOfBoundsException ex) { Singleton.getLogger().info("getBlameInfoExternal repoloc: " + repoLocations + "/" + repoName); Singleton.getLogger().info("getBlameInfoExternal fileName: " + fileName); Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + "\n with message: " + ex.getMessage()); } return codeOwners; }
From source file:org.apache.hadoop.mapred.util.Shell.java
/** Run a command */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null;/* w ww . j a va2s . co 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); } process = builder.start(); if (timeOutInterval > 0) { timeOutTimer = new Timer(); 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() { 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.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) && !timedOut.get()) { timeOutTimer.cancel(); } // close the input stream try { inReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing the input stream", ioe); } if (!completed.get()) { 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:gov.pnnl.goss.gridappsd.app.AppManagerImpl.java
@Override public String startAppForSimultion(String appId, String runtimeOptions, Map simulationContext) { String simulationId = simulationContext.get("simulationId").toString(); appId = appId.trim();//from w w w.j ava2 s.c o m String instanceId = appId + "-" + new Date().getTime(); // get execution path AppInfo appInfo = apps.get(appId); if (appInfo == null) { throw new RuntimeException("App not found: " + appId); } // are multiple allowed? if not check to see if it is already running, // if it is then fail if (!appInfo.isMultiple_instances() && listRunningApps(appId).size() > 0) { throw new RuntimeException("App is already running and multiple instances are not allowed: " + appId); } // build options // might need a standard method for replacing things like SIMULATION_ID // in the input/output options /*String optionsString = appInfo.getOptions(); if (simulationId != null) { if (optionsString.contains("SIMULATION_ID")) { optionsString = optionsString.replace("SIMULATION_ID", simulationId); } if (runtimeOptions.contains("SIMULATION_ID")) { runtimeOptions = runtimeOptions.replace("SIMULATION_ID", simulationId); } }*/ File appDirectory = new File(getAppConfigDirectory().getAbsolutePath() + File.separator + appId); Process process = null; // something like if (AppType.PYTHON.equals(appInfo.getType())) { List<String> commands = new ArrayList<String>(); commands.add("python"); commands.add(appInfo.getExecution_path()); //Check if static args contain any replacement values List<String> staticArgsList = appInfo.getOptions(); for (String staticArg : staticArgsList) { if (staticArg != null) { if (staticArg.contains("(")) { String[] replaceArgs = StringUtils.substringsBetween(staticArg, "(", ")"); for (String args : replaceArgs) { staticArg = staticArg.replace("(" + args + ")", simulationContext.get(args).toString()); } } commands.add(staticArg); } } if (runtimeOptions != null && !runtimeOptions.isEmpty()) { String runTimeString = runtimeOptions.replace(" ", "").replace("\n", ""); commands.add(runTimeString); } ProcessBuilder processAppBuilder = new ProcessBuilder(commands); processAppBuilder.redirectErrorStream(true); processAppBuilder.redirectOutput(); processAppBuilder.directory(appDirectory); logManager.log(new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting app with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); try { process = processAppBuilder.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python", // getPath(GridAppsDConstants.FNCS_BRIDGE_PATH), // simulationConfig.getSimulation_name()); // fncsBridgeBuilder.redirectErrorStream(true); // fncsBridgeBuilder.redirectOutput(new // File(defaultLogDir.getAbsolutePath()+File.separator+"fncs_goss_bridge.log")); // fncsBridgeProcess = fncsBridgeBuilder.start(); // // Watch the process // watch(fncsBridgeProcess, "FNCS GOSS Bridge"); // during watch, send stderr/out to logmanager } else if (AppType.JAVA.equals(appInfo.getType())) { // ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python", // getPath(GridAppsDConstants.FNCS_BRIDGE_PATH), // simulationConfig.getSimulation_name()); // fncsBridgeBuilder.redirectErrorStream(true); // fncsBridgeBuilder.redirectOutput(new // File(defaultLogDir.getAbsolutePath()+File.separator+"fncs_goss_bridge.log")); // fncsBridgeProcess = fncsBridgeBuilder.start(); // // Watch the process // watch(fncsBridgeProcess, "FNCS GOSS Bridge"); // during watch, send stderr/out to logmanager } else if (AppType.WEB.equals(appInfo.getType())) { // ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python", // getPath(GridAppsDConstants.FNCS_BRIDGE_PATH), // simulationConfig.getSimulation_name()); // fncsBridgeBuilder.redirectErrorStream(true); // fncsBridgeBuilder.redirectOutput(new // File(defaultLogDir.getAbsolutePath()+File.separator+"fncs_goss_bridge.log")); // fncsBridgeProcess = fncsBridgeBuilder.start(); // // Watch the process // watch(fncsBridgeProcess, "FNCS GOSS Bridge"); // during watch, send stderr/out to logmanager } else { throw new RuntimeException("Type not recognized " + appInfo.getType()); } // create appinstance object AppInstance appInstance = new AppInstance(instanceId, appInfo, runtimeOptions, simulationId, simulationId, process); appInstance.setApp_info(appInfo); watch(appInstance); // add to app instances map appInstances.put(instanceId, appInstance); return instanceId; }
From source file:com.alu.e3.logger.LogCollector.java
private static String execTailOnFile(File file, int numLines) throws IOException { String numLinesArg = String.valueOf(numLines); if ((numLines < 0) || (numLinesArg == null) || (numLinesArg.length() == 0) || (file == null) || !file.exists()) {// ww w . j a va 2s. c o m return null; } else if (numLines == 0) { return ""; } ProcessBuilder processBuilder = new ProcessBuilder("/usr/bin/tail", "-n " + numLinesArg, file.getAbsolutePath()); File workingDirectory = file.getParentFile(); if (workingDirectory != null) { processBuilder.directory(workingDirectory); } Process p = processBuilder.start(); // Get tail's output: its InputStream InputStream is = p.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; if (reader != null) { try { while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } } finally { try { if (reader != null) { reader.close(); } if (is != null) { is.close(); } } catch (IOException ioe) { // Nothing to do on close exception } } } /* // We only need to wait for p to finish if we want the exit value try { p.waitFor(); } catch (InterruptedException ex) { logger.warn("Tail on logfile {} interrupted!", file.getAbsoluteFile()); } logger.debug("Tail process exited with code {} ", String.valueOf(p.exitValue())); */ return sb.toString(); }
From source file:sorcer.launcher.JavaProcessBuilder.java
public Process2 startProcess() throws IOException { ProcessBuilder procBld = new ProcessBuilder().command(command); if (debugger) { procBld.command().addAll(/*from w w w .ja v a 2 s .c om*/ Arrays.asList("-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,address=" + debugPort)); } procBld.command().addAll(_D(properties)); String classPath = StringUtils.join(classPathList, File.pathSeparator); procBld.command().addAll(asList("-classpath", classPath, mainClass)); if (parameters != null) { procBld.command().addAll(parameters); } if (workingDir == null) { // the default // make explicit for logging purpose workingDir = new File(System.getProperty("user.dir")); } procBld.directory(workingDir); Map<String, String> env = procBld.environment(); updateEnvironment(env); StringBuilder cmdStr = new StringBuilder("[").append(workingDir.getPath()).append("] ") .append(StringUtils.join(procBld.command(), " ")); if (output != null) { cmdStr.append(" > ").append(output.getPath()); } log.info(cmdStr.toString()); redirectIO(procBld); Process proc = null; try { proc = procBld.start(); try { // give it a moment to exit on error Thread.sleep(100); } catch (InterruptedException ignored) { //ignore } // if the next call throws exception, then we're probably good - // process hasn't finished yet. int x = proc.exitValue(); throw new IllegalStateException("Process exited with value " + x); } catch (IllegalThreadStateException x) { return new Process2(proc); } }