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:com.moviejukebox.scanner.MediaInfoScanner.java
@SuppressWarnings("resource") protected MediaInfoStream createStream(String movieFilePath) throws IOException { if (MI_READ_FROM_FILE) { // check file String filename = FilenameUtils.removeExtension(movieFilePath) + ".mediainfo"; Collection<File> files = FileTools.fileCache.searchFilename(filename, Boolean.FALSE); if (files != null && !files.isEmpty()) { // create new input stream for reading LOG.debug("Reading from file {}", filename); return new MediaInfoStream(new FileInputStream(files.iterator().next())); }/*from ww w . j av a 2s .c om*/ } // Create the command line List<String> commandMedia = new ArrayList<>(MI_EXE); commandMedia.add(movieFilePath); ProcessBuilder pb = new ProcessBuilder(commandMedia); // set up the working directory. pb.directory(MI_PATH); return new MediaInfoStream(pb.start()); }
From source file:cz.cuni.amis.planning4j.external.impl.itsimple.ItSimplePlanningProcess.java
/** * Runs the planner and returns the console output *//* w ww . java2 s . c o m*/ protected UnprocessedPlanningResult runPlanner(File domain, File problem) { //1.Get main planner's parameters and arguments ItSimplePlannerSettings settings = chosenPlanner.getSettings(); String plannerRelativeFile = settings.getExecutableFilePath(); plannerExecutableFile = new File(plannerBinariesDirectory, plannerRelativeFile); if (!plannerExecutableFile.exists()) { String toolMessage = "Could not find selected planner '" + plannerRelativeFile + "' in directory " + plannerBinariesDirectory.getAbsolutePath(); throw new PlanningException(toolMessage); } List<String> commandArguments = new ArrayList<String>(); //1.0 Get planner execution file commandArguments.add(plannerExecutableFile.getAbsolutePath()); //1.1 Get domain arguments if (!settings.getDomainArgumentName().trim().isEmpty()) { commandArguments.add(settings.getDomainArgumentName()); } commandArguments.add(domain.getAbsolutePath()); //domain path //1.2 Get problem arguments if (!settings.getProblemArgumentName().trim().isEmpty()) { commandArguments.add(settings.getProblemArgumentName()); } commandArguments.add(problem.getAbsolutePath()); //problem path //1.3 Get additional arguments for (PlannerArgument argument : settings.getAdditionalArguments()) { //System.out.println(argument.getChildText("name")); if (!argument.getName().trim().equals("")) { commandArguments.add(argument.getName()); } //if there is a value for the argument then add to the command if (!argument.getValue().trim().equals("")) { commandArguments.add(argument.getValue()); } } //1.4 Get output arguments if (settings.isHasOutputFile() && settings.isOutputFileNeedsArgument()) { commandArguments.add(settings.getOutputFileArgumentName()); commandArguments.add(settings.getOutputFile()); //problem path } synchronized (this) { if (cancelled) { return null; } logger.info("\n>> Calling planner " + chosenPlanner.getName() + " in directory: " + workingDirectory.getAbsolutePath()); logger.debug("Planner arguments:" + commandArguments); //Call the planner try { ProcessBuilder builder = new ProcessBuilder(commandArguments); builder.directory(workingDirectory); process = spawnPlanner(builder, plannerRelativeFile); } catch (Exception e) { String message = "Error while running the planner " + chosenPlanner.getName() + ". "; throw new PlanningException(message, e); } } try { boolean plannerFoundNoSolution = false; Scanner sc = new Scanner(process.getInputStream()); //Get the planner answer exposed in the console if (logger.isDebugEnabled()) { logger.debug("Planner console output:"); } StringBuilder consoleOutputBuilder = new StringBuilder(); List<String> unprocessedPlan = new ArrayList<String>(); List<String> unprocessedStatistics = new ArrayList<String>(); //Needed only when parsing plan from console, but need to be initialized here EConsoleParseState consoleParseState; int numLinesBeforePlan = settings.getConsoleOutputStartsAfterNLines(); if (settings.getConsoleOutputPlanStartIdentifier() == null || settings.getConsoleOutputPlanStartIdentifier().isEmpty()) { consoleParseState = EConsoleParseState.COUNTING_TO_PLAN_START; } else { consoleParseState = EConsoleParseState.BEGIN; } while (sc.hasNextLine()) { String line = sc.nextLine(); consoleOutputBuilder.append(line).append("\n"); for (INoPlanFoundChecker checker : settings.getNoPlanFoundCheckers()) { if (checker.processOutputLine(line)) { plannerFoundNoSolution = true; } } if (logger.isDebugEnabled()) { logger.debug(line); } if (!settings.isHasOutputFile()) { if (!line.trim().isEmpty()) { if (logger.isDebugEnabled()) { logger.debug(consoleParseState + ":" + line); } //the plan is part of console output switch (consoleParseState) { case BEGIN: { if (line.contains(settings.getConsoleOutputPlanStartIdentifier())) { if (numLinesBeforePlan > 0) { consoleParseState = EConsoleParseState.COUNTING_TO_PLAN_START; numLinesBeforePlan--; } else { //the plan starts on the same line int indexPlanStart = line .indexOf(settings.getConsoleOutputPlanStartIdentifier()); String firstLine = line.substring(indexPlanStart + settings.getConsoleOutputPlanStartIdentifier().length()); if (!isLineAction(firstLine)) { unprocessedStatistics.add(firstLine); } else { unprocessedPlan.add(firstLine); } consoleParseState = EConsoleParseState.READING_PLAN; } } break; } case COUNTING_TO_PLAN_START: { if (numLinesBeforePlan > 0) { numLinesBeforePlan--; break; } else { consoleParseState = EConsoleParseState.READING_PLAN; } //intentional fallthrough!!! } case READING_PLAN: { if (!settings.getConsoleOutputPlanEndIdentifier().isEmpty() && line.contains(settings.getConsoleOutputPlanEndIdentifier())) { consoleParseState = EConsoleParseState.END; } else { if (!isLineAction(line)) { unprocessedStatistics.add(line); } else { unprocessedPlan.add(line); } } break; } case END: { if (isLineStatistics(line)) { unprocessedStatistics.add(line); } break; } } } } } sc.close(); if (cancelled) { return null; } //Need to clean the stream, otherwise, it would block the process from terminating String errorOuput; try { errorOuput = IOUtils.toString(process.getErrorStream()); } catch (IOException ex) { errorOuput = "Could not get error stream: " + ex.getMessage(); } try { if (cancelled) { return null; } process.waitFor(); logger.info("\n>> Planner " + chosenPlanner.getName() + " finished execution\n "); } catch (InterruptedException ex) { if (cancelled) { return null; } logger.info("Waiting for planner execution interrupted", ex); destroyProcess(); return null; } process.destroy(); if (logger.isDebugEnabled()) { logger.debug("Planner console output end."); } if (cancelled) { return null; } int exitCode = process.exitValue(); for (INoPlanFoundChecker checker : settings.getNoPlanFoundCheckers()) { if (checker.processExitCode(exitCode)) { plannerFoundNoSolution = true; } } if (exitCode != 0 && !plannerFoundNoSolution) { throw new PlanningException( "Planner terminated with an error - exit code: " + exitCode + ". Planner output:\n " + consoleOutputBuilder.toString() + "\nError output:\n" + errorOuput); } if (settings.isHasOutputFile()) { //The planner does provide an output file String solutionFile = "solution.soln"; if (!settings.getOutputFile().trim().isEmpty()) { solutionFile = settings.getOutputFile(); } if (settings.getOutputFileAutomaticIncrementSuffix() != null) { //Find the existing file with the highest increment index int i = 1; while (true) { String candidateSolutionFileName = solutionFile + settings .getOutputFileAutomaticIncrementSuffix().replace("#", Integer.toString(i)); File candidateSolutionFile = new File(workingDirectory, candidateSolutionFileName); if (candidateSolutionFile.exists()) { solutionFile = candidateSolutionFileName; i++; } else { break; } } } //Get the planner answer exposed in the solution Output File File outputFile = new File(workingDirectory, solutionFile); if (outputFile.exists()) { //Get output try { for (String line : FileUtils.readLines(outputFile)) { if (line.trim().isEmpty()) { continue; } if (!isLineAction(line)) { unprocessedStatistics.add(line); } else { unprocessedPlan.add(line); } } } catch (IOException ex) { throw new PlanningException("Could not read planner output", ex); } //remove output solution file (only if the plan create it) outputFile.delete(); //TODO check permission } else { //if the planner signalled before that it found nothing, the file may not exits and it's OK if (!plannerFoundNoSolution) { throw new PlanningException("Could not find the planner output solution file! \n"); } //System.out.println(toolMessage); } } if (cancelled) { return null; } for (INoPlanFoundChecker checker : settings.getNoPlanFoundCheckers()) { if (checker.processUnprocessedPlan(unprocessedPlan)) { plannerFoundNoSolution = true; } } return new UnprocessedPlanningResult(unprocessedPlan, unprocessedStatistics, consoleOutputBuilder.toString(), !plannerFoundNoSolution); } finally { // delete additional generated files for (String generatedFileName : settings.getAdditionalGeneratedFiles()) { File file = new File(workingDirectory, generatedFileName); if (file.exists()) { // delete the file file.delete(); } } } }
From source file:net.doubledoordev.backend.server.Server.java
/** * Downloads and uses specific forge installer *//*from w ww. j av a2 s. c o m*/ public void installForge(final IMethodCaller methodCaller, final String name) { if (getOnline()) throw new ServerOnlineException(); final String version = Helper.getForgeVersionForName(name); if (version == null) throw new IllegalArgumentException("Forge with ID " + name + " not found."); if (downloading) throw new IllegalStateException("Already downloading something."); if (!isCoOwner(methodCaller.getUser())) throw new AuthenticationException(); final Server instance = this; new Thread(new Runnable() { @Override public void run() { downloading = true; try { // delete old files for (File file : folder.listFiles(ACCEPT_MINECRAFT_SERVER_FILTER)) file.delete(); for (File file : folder.listFiles(ACCEPT_FORGE_FILTER)) file.delete(); // download new files String url = Constants.FORGE_INSTALLER_URL.replace("%ID%", version); String forgeName = url.substring(url.lastIndexOf('/')); File forge = new File(folder, forgeName); FileUtils.copyURLToFile(new URL(url), forge); // run installer List<String> arguments = new ArrayList<>(); arguments.add(Constants.getJavaPath()); arguments.add("-Xmx1G"); arguments.add("-jar"); arguments.add(forge.getName()); arguments.add("--installServer"); ProcessBuilder builder = new ProcessBuilder(arguments); builder.directory(folder); builder.redirectErrorStream(true); final Process process = builder.start(); printLine(arguments.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { methodCaller.sendMessage(line); printLine(line); } try { process.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } for (String name : folder.list(ACCEPT_FORGE_FILTER)) getJvmData().jarName = name; forge.delete(); methodCaller.sendDone(); printLine("Forge installer done."); instance.update(); } catch (IOException e) { printLine("##################################################################"); printLine("Error installing a new forge version (version " + version + ")"); printLine(e.toString()); printLine("##################################################################"); e.printStackTrace(); } downloading = false; } }, getID() + "-forge-installer").start(); }
From source file:com.tencent.gaia.portal.util.Shell.java
/** * Run a command/*from ww w.j a v a2s . c o m*/ */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null; 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() { 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) { 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); } try { if (!completed.get()) { errThread.interrupt(); errThread.join(); } } catch (InterruptedException ie) { LOG.warn("Interrupted while joining 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 = System.currentTimeMillis(); } }
From source file:com.moviejukebox.scanner.MediaInfoScanner.java
public String archiveScan(String movieFilePath) { if (!IS_ACTIVATED) { return null; }/*from www . java 2s. com*/ LOG.debug("Mini-scan on {}", movieFilePath); try { // Create the command line List<String> commandMedia = new ArrayList<>(MI_EXE); // Technically, mediaInfoExe has "-f" in it from above, but "-s" will override it anyway. // "-s" will dump just "$size $path" inside RAR/ISO. commandMedia.add("-s"); commandMedia.add(movieFilePath); ProcessBuilder pb = new ProcessBuilder(commandMedia); // set up the working directory. pb.directory(MI_PATH); Process p = pb.start(); String mediaArchive; try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; mediaArchive = null; while ((line = localInputReadLine(input)) != null) { Pattern patternArchive = Pattern.compile("^\\s*\\d+\\s(.*)$"); Matcher m = patternArchive.matcher(line); if (m.find() && (m.groupCount() == 1)) { mediaArchive = m.group(1); } } } LOG.debug("Returning with archivename {}", mediaArchive); return mediaArchive; } catch (IOException error) { LOG.error(SystemTools.getStackTrace(error)); } return null; }
From source file:com.twinsoft.convertigo.engine.localbuild.BuildLocally.java
private String runCommand(File launchDir, String command, List<String> parameters, boolean mergeError) throws Throwable { if (is(OS.win32)) { // Works for cordova and npm command += ".cmd"; }//from w w w . jav a 2 s. c o m String shellFullpath = command; String paths = getLocalBuildAdditionalPath(); paths = (paths.length() > 0 ? paths + File.pathSeparator : "") + System.getenv("PATH"); String defaultPaths = null; if (is(OS.mac) || is(OS.linux)) { defaultPaths = "/usr/local/bin"; } else if (is(OS.win32)) { String programFiles = System.getenv("ProgramW6432"); if (programFiles != null && programFiles.length() > 0) { defaultPaths = programFiles + File.separator + "nodejs"; } programFiles = System.getenv("ProgramFiles"); if (programFiles != null && programFiles.length() > 0) { defaultPaths = (defaultPaths == null ? "" : defaultPaths + File.pathSeparator) + programFiles + File.separator + "nodejs"; } String appData = System.getenv("APPDATA"); if (appData != null && appData.length() > 0) { defaultPaths = (defaultPaths == null ? "" : defaultPaths + File.pathSeparator) + appData + File.separator + "npm"; } } paths += File.pathSeparator + defaultPaths; // Checks if the command is already full path if (!(new File(shellFullpath).exists())) { // Else search where the "exec" is and build the absolute path for this "exec" shellFullpath = getFullPath(paths, command); // If the "exec" is not found then it search it elsewhere if (shellFullpath == null) { shellFullpath = command; } } // Prepares the command parameters.add(0, shellFullpath); ProcessBuilder pb = new ProcessBuilder(parameters); // Set the directory from where the command will be executed pb.directory(launchDir.getCanonicalFile()); Map<String, String> pbEnv = pb.environment(); // must set "Path" for Windows 8.1 64 pbEnv.put(pbEnv.get("PATH") == null ? "Path" : "PATH", paths); // Specific to npm command if (shellFullpath.endsWith("npm") || shellFullpath.endsWith("npm.cmd")) { // Set the proxy for npm String proxyMode = EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_MODE); if (proxyMode.equals(ProxyMode.manual.getValue())) { String proxyAuthMethod = EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_METHOD); if (proxyAuthMethod.equals(ProxyMethod.anonymous.getValue()) || proxyAuthMethod.equals(ProxyMethod.basic.getValue())) { String proxyHost = EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_HOST); String proxyPort = EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_PORT); String npmProxy = proxyHost + ":" + proxyPort; if (proxyAuthMethod.equals(ProxyMethod.basic.getValue())) { String proxyUser = EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_USER); String proxyPassword = EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_PASSWORD); npmProxy = proxyUser + ":" + proxyPassword + "@" + npmProxy; } pbEnv.put("http-proxy", "http://" + npmProxy); pbEnv.put("https-proxy", "http://" + npmProxy); } } } pb.redirectErrorStream(mergeError); Engine.logEngine.info("Executing command : " + parameters); process = pb.start(); cmdOutput = ""; // Logs the output new Thread(new Runnable() { @Override public void run() { try { String line; processCanceled = false; BufferedReader bis = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = bis.readLine()) != null) { Engine.logEngine.info(line); BuildLocally.this.cmdOutput += line; } } catch (IOException e) { Engine.logEngine.error("Error while executing command", e); } } }).start(); if (!mergeError) { // Logs the error output new Thread(new Runnable() { @Override public void run() { try { String line; processCanceled = false; BufferedReader bis = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((line = bis.readLine()) != null) { Engine.logEngine.error(line); errorLines += line; } } catch (IOException e) { Engine.logEngine.error("Error while executing command", e); } } }).start(); } int exitCode = process.waitFor(); if (exitCode != 0 && exitCode != 127) { throw new Exception( "Exit code " + exitCode + " when running the command '" + command + "' with parameters : '" + parameters + "'. The output of the command is : '" + cmdOutput + "'"); } return cmdOutput; }
From source file:net.doubledoordev.backend.server.Server.java
/** * Start the server in a process controlled by us. * Threaded to avoid haning.//from w ww . j ava 2 s . c o m * * @throws ServerOnlineException */ public void startServer() throws Exception { if (getOnline() || starting) throw new ServerOnlineException(); if (downloading) throw new Exception("Still downloading something. You can see the progress in the server console."); if (new File(folder, getJvmData().jarName + ".tmp").exists()) throw new Exception("Minecraft server jar still downloading..."); if (!new File(folder, getJvmData().jarName).exists()) throw new FileNotFoundException(getJvmData().jarName + " not found."); User user = Settings.getUserByName(getOwner()); if (user == null) throw new Exception("No owner set??"); if (user.getMaxRamLeft() != -1 && getJvmData().ramMax > user.getMaxRamLeft()) throw new Exception("Out of usable RAM. Lower your max RAM."); saveProperties(); starting = true; final Server instance = this; for (String blocked : SERVER_START_ARGS_BLACKLIST_PATTERNS) if (getJvmData().extraJavaParameters.contains(blocked)) throw new Exception("JVM options contain a blocked option: " + blocked); File eula = new File(getFolder(), "eula.txt"); if (!eula.exists()) { try { FileUtils.writeStringToFile(eula, "#The server owner indicated to agree with the EULA when submitting the from that produced this server instance.\n" + "#That means that there is no need for extra halting of the server startup sequence with this stupid file.\n" + "#" + new Date().toString() + "\n" + "eula=true\n"); } catch (IOException e) { printLine("Error making the eula file...."); e.printStackTrace(); } } new Thread(new Runnable() { @Override public void run() { printLine("Starting server ................"); try { /** * Build arguments list. */ List<String> arguments = new ArrayList<>(); arguments.add(Constants.getJavaPath()); arguments.add("-server"); { int amount = getJvmData().ramMin; if (amount > 0) arguments.add(String.format("-Xms%dM", amount)); amount = getJvmData().ramMax; if (amount > 0) arguments.add(String.format("-Xmx%dM", amount)); amount = getJvmData().permGen; if (amount > 0) arguments.add(String.format("-XX:MaxPermSize=%dm", amount)); } if (getJvmData().extraJavaParameters.trim().length() != 0) arguments.add(getJvmData().extraJavaParameters.trim()); arguments.add("-jar"); arguments.add(getJvmData().jarName); arguments.add("nogui"); if (getJvmData().extraMCParameters.trim().length() != 0) arguments.add(getJvmData().extraMCParameters.trim()); // Debug printout printLine("Arguments: " + arguments.toString()); /** * Make ProcessBuilder, set rundir, and make sure the io gets redirected */ ProcessBuilder pb = new ProcessBuilder(arguments); pb.directory(folder); pb.redirectErrorStream(true); if (!new File(folder, getJvmData().jarName).exists()) return; // for reasons of WTF? process = pb.start(); new Thread(new Runnable() { @Override public void run() { try { printLine("----=====##### STARTING SERVER #####=====-----"); BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { printLine(line); } printLine("----=====##### SERVER PROCESS HAS ENDED #####=====-----"); instance.update(); } catch (IOException e) { error(e); } } }, ID.concat("-streamEater")).start(); instance.update(); } catch (IOException e) { error(e); } starting = false; } }, "ServerStarter-" + getID()).start(); // <-- Very important call. }
From source file:org.apache.bookkeeper.util.Shell.java
/** Run a command */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null;//from w ww.jav a 2s . 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); } 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(), Charsets.UTF_8)); BufferedReader inReader = new BufferedReader( new InputStreamReader(process.getInputStream(), Charsets.UTF_8)); 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) { 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 = MathUtils.now(); } }
From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToLaTeXConverter.java
/** * * @param workDir//ww w .j a v a 2s. c o m * @param latexFile */ protected int runPdflatex(File workDir, File latexFile, int nrOfRuns) { if (latexCmd == null) { return -99; } int exitValue = 0; try { String[] cmd = new String[] { latexCmd, "--halt-on-error", "-output-directory=" + workDir, latexFile.getAbsolutePath() }; String texpath = new File((new File(latexCmd)).getParent()).getAbsolutePath(); ProcessBuilder latexProcessBuilder = new ProcessBuilder(cmd); latexProcessBuilder.directory(workDir); Map<String, String> env = latexProcessBuilder.environment(); String path = env.get("PATH"); if (path != null) { path = texpath + ":" + path; env.put("PATH", path); } File stdoutlog = new File(workDir + File.separator + "stdout.log"); latexProcessBuilder.redirectOutput(Redirect.appendTo(stdoutlog)); File stderrlog = new File(workDir + File.separator + "stderr.log"); latexProcessBuilder.redirectError(Redirect.appendTo(stderrlog)); ProcessExecutor latexProcessExecutor = new ProcessExecutor(latexProcessBuilder); Thread executionThread = new Thread(latexProcessExecutor); long timeout = 20000; LOGGER.debug("Run xelatex thread started!"); long startTime = System.currentTimeMillis(); executionThread.start(); int imod = 0; while (executionThread.isAlive()) { ++imod; if (imod % 5 == 0) { LOGGER.debug("Run xelatex thread is alive"); } if (((System.currentTimeMillis() - startTime) > timeout) && executionThread.isAlive()) { executionThread.interrupt(); LOGGER.debug("Run xelatex thread interrupted!"); latexProcessExecutor.killProcess(); } Thread.sleep(100); } LOGGER.debug("Run xelatex done!"); exitValue = latexProcessExecutor.getExitValue(); try { Thread.sleep(1000); } catch (Exception ex) { LOGGER.error(ExceptionUtils.getStackTrace(ex), ex); } } catch (Exception ex) { LOGGER.error(ExceptionUtils.getStackTrace(ex), ex); } return exitValue; }
From source file:org.springframework.yarn.test.Shell.java
/** Run a command */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null;// ww w . j a v a 2 s. 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); } 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() { 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) { 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 = Time.now(); } }