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:net.urlgrey.mythpodcaster.transcode.FFMpegTranscoderImpl.java
public void transcode(File workingDirectory, GenericTranscoderConfigurationItem genericConfig, File inputFile, File outputFile) throws Exception { LOG.info("transcode started: inputFile [" + inputFile.getAbsolutePath() + "], outputFile [" + outputFile.getAbsolutePath() + "]"); FFMpegTranscoderConfigurationItem config = (FFMpegTranscoderConfigurationItem) genericConfig; List<String> commandList = new ArrayList<String>(); commandList.add(niceLocation);// w ww . ja va2s. c om commandList.add("-n"); commandList.add(Integer.toString(config.getNiceness())); commandList.add(ffmpegLocation); commandList.add("-i"); commandList.add(inputFile.getAbsolutePath()); commandList.addAll(config.getParsedEncoderArguments()); commandList.add(outputFile.getAbsolutePath()); ProcessBuilder pb = new ProcessBuilder(commandList); // Needed for ffmpeg pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:"); pb.redirectErrorStream(true); pb.directory(workingDirectory); Process process = null; try { // Get the ffmpeg process process = pb.start(); // We give a couple of secs to complete task if needed Future<List<String>> stdout = pool.submit(new OutputMonitor(process.getInputStream())); List<String> result = stdout.get(config.getTimeout(), TimeUnit.SECONDS); process.waitFor(); final int exitValue = process.exitValue(); LOG.info("FFMPEG exit value: " + exitValue); if (exitValue != 0) { for (String line : result) { LOG.error(line); } throw new Exception("FFMpeg return code indicated failure: " + exitValue); } } catch (InterruptedException e) { throw new Exception("FFMpeg process interrupted by another thread", e); } catch (ExecutionException ee) { throw new Exception("Something went wrong parsing FFMpeg output", ee); } catch (TimeoutException te) { // We could not get the result before timeout throw new Exception("FFMpeg process timed out", te); } catch (RuntimeException re) { // Unexpected output from FFMpeg throw new Exception("Something went wrong parsing FFMpeg output", re); } finally { if (process != null) { process.destroy(); } } LOG.debug("transcoding finished"); }
From source file:org.p_vcd.process.ProcessBase.java
private void runCommandInternal(String command, ProcessArguments commandArgs, File workingDir, StringBuffer sbSaveStdout, StringBuffer sbSaveStderr) throws Exception { commandArgs.insertFirst(command);/*from w w w. j a va 2 s .c om*/ FileUtils.forceMkdir(workingDir); StringBuffer sbLog = new StringBuffer(); sbLog.append("\n").append(MyUtil.getFormateDate()); commandArgs.addToLog(sbLog); System.out.println(sbLog.toString()); this.status.appendOutputLine(sbLog.toString()); ProcessBuilder pb = new ProcessBuilder(commandArgs.getCommands()); pb.directory(workingDir); pb.redirectInput(Redirect.INHERIT); pb.redirectOutput(Redirect.PIPE); pb.redirectError(Redirect.PIPE); long init = System.currentTimeMillis(); this.currentSystemProcess = pb.start(); PrintThreadWithStatus thStdout = new PrintThreadWithStatus(this.currentSystemProcess.getInputStream(), command, this.status, sbSaveStdout); PrintThreadWithStatus thStderr = new PrintThreadWithStatus(this.currentSystemProcess.getErrorStream(), command, this.status, sbSaveStderr); this.currentSystemProcess.getOutputStream().close(); thStdout.start(); thStderr.start(); int ret = -1; try { this.processRunning = true; ret = this.currentSystemProcess.waitFor(); } catch (InterruptedException ex) { ex.printStackTrace(); } finally { this.processRunning = false; } try { thStderr.join(); } catch (InterruptedException ex) { ex.printStackTrace(); } try { thStdout.join(); } catch (InterruptedException ex) { ex.printStackTrace(); } long milis = System.currentTimeMillis() - init; if (ret != 0) { throw new Exception("command error code=" + ret + " (" + milis + " ms)"); } sbLog = new StringBuffer(); sbLog.append(MyUtil.getFormateDate()).append("command ").append(command).append(" ok (").append(milis) .append(" ms)"); System.out.println(sbLog.toString()); this.status.appendOutputLine(sbLog.toString()); }
From source file:com.c4om.autoconf.ulysses.configanalyzer.guilauncher.ChromeAppEditorGUILauncher.java
/** * @see com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.GUILauncher#launchGUI(com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.datastructures.ConfigurationAnalysisContext, com.c4om.autoconf.ulysses.interfaces.Target) *///from w w w. j a va2s . c o m @SuppressWarnings("resource") @Override public void launchGUI(ConfigurationAnalysisContext context, Target target) throws GUILaunchException { try { List<File> temporaryFolders = this.getTemporaryStoredChangesetsAndConfigs(context, target); for (File temporaryFolder : temporaryFolders) { //The temporary folder where one subfolder per analyzer execution will be stored (and removed). File temporaryFolderRoot = temporaryFolder.getParentFile().getParentFile(); System.out.println("Writing launch properties."); //Now, we build the properties file Properties launchProperties = new Properties(); String relativeTemporaryFolder = temporaryFolder.getAbsolutePath() .replaceAll("^" + Pattern.quote(temporaryFolderRoot.getAbsolutePath()), "") .replaceAll("^" + Pattern.quote(File.separator), "") .replaceAll(Pattern.quote(File.separator) + "$", "") .replaceAll(Pattern.quote(File.separator) + "+", "/"); // launchProperties.put(KEY_LOAD_RECOMMENDATIONS_FILE, relativeTemporaryFolder+CHANGESET_TO_APPLY); launchProperties.put(KEY_CATALOG, relativeTemporaryFolder + CATALOG_FILE_PATH); Writer writer = new OutputStreamWriter( new FileOutputStream(new File(temporaryFolderRoot, LAUNCH_PROPERTIES_FILE_NAME)), Charsets.UTF_8); launchProperties.store(writer, ""); writer.close(); System.out.println("Launch properties written!!!!"); System.out.println("Launching XML editor Chrome app"); Properties configurationAnalyzerProperties = context.getConfigurationAnalyzerSettings(); String chromeLocation = configurationAnalyzerProperties.getProperty(PROPERTIES_KEY_CHROME_LOCATION); String editorChromeAppLocation = configurationAnalyzerProperties .getProperty(PROPERTIES_KEY_EDITOR_CHROME_APP_LOCATION); ProcessBuilder chromeEditorPB = new ProcessBuilder( ImmutableList.of(chromeLocation, "--load-and-launch-app=" + editorChromeAppLocation)); chromeEditorPB.directory(new File(editorChromeAppLocation)); chromeEditorPB.start(); System.out.println("Editor started!!!"); System.out.println("Now, make all your changes and press ENTER when finished..."); new Scanner(System.in).nextLine(); FileUtils.forceDeleteOnExit(temporaryFolder.getParentFile()); } } catch (IOException e) { throw new GUILaunchException(e); } }
From source file:com.github.jrh3k5.mojo.flume.process.AgentProcessTest.java
/** * Test the construction of the Flume process. * //from w w w . j a va 2 s. c o m * @throws Exception * If any errors occur during the test run. */ @Test public void testBuildFlumeProcess() throws Exception { final List<String> args = Arrays.asList("arg1", "arg2"); final AgentProcess.ProcessBuilderProxy builderProxy = new AgentProcess.ProcessBuilderProxy(flumeDirectory, args); final ProcessBuilder builder = builderProxy.newProcessBuilder(); assertThat(builder.command()).isEqualTo(args); assertThat(builder.directory()).isEqualTo(flumeDirectory); assertThat(builder.redirectErrorStream()).isTrue(); }
From source file:io.wcm.maven.plugins.nodejs.mojo.Task.java
/** * Executes the {@link Process} with commands returned by {@link #getCommand(NodeInstallationInformation)}. * @param information//from ww w . j a v a2s. c om * @throws MojoExecutionException */ public void execute(NodeInstallationInformation information) throws MojoExecutionException { ProcessBuilder processBuilder = new ProcessBuilder(getCommand(information)); if (workingDirectory != null) { if (!workingDirectory.exists()) { workingDirectory.mkdir(); } processBuilder.directory(workingDirectory); } setNodePath(processBuilder, information); startProcess(processBuilder); }
From source file:org.zaproxy.zap.extension.invoke.InvokeAppWorker.java
@Override protected Void doInBackground() throws Exception { String url = ""; // Full URL String host = ""; // Just the server name, e.g. localhost String port = ""; // the port String site = ""; // e.g. http://localhost:8080/ String postdata = ""; // only present in POST ops String cookie = ""; // from the request header HistoryReference historyRef = msg.getHistoryRef(); int msgid = -1; if (historyRef != null) { msgid = historyRef.getHistoryId(); }//from w w w .j a v a2s . c om URI uri = msg.getRequestHeader().getURI(); url = uri.toString(); host = uri.getHost(); site = uri.getScheme() + "://" + uri.getHost(); if (uri.getPort() > 0) { port = String.valueOf(uri.getPort()); site = site + ":" + port + "/"; } else { if (uri.getScheme().equalsIgnoreCase("http")) { port = "80"; } else if (uri.getScheme().equalsIgnoreCase("https")) { port = "443"; } site = site + "/"; } if (msg.getRequestBody() != null) { postdata = msg.getRequestBody().toString(); postdata = postdata.replaceAll("\n", "\\n"); } Vector<String> cookies = msg.getRequestHeader().getHeaders(HttpHeader.COOKIE); if (cookies != null && cookies.size() > 0) { cookie = cookies.get(0); } List<String> cmd = new ArrayList<>(); cmd.add(command); if (parameters != null) { for (String parameter : parameters.split(" ")) { // Replace all of the tags String finalParameter = parameter.replace("%url%", url).replace("%host%", host) .replace("%port%", port).replace("%site%", site).replace("%cookie%", cookie) .replace("%postdata%", postdata).replace("%msgid%", String.valueOf(msgid)); // Replace header tags Matcher headers = Pattern.compile("%header-([A-z0-9_-]+)%").matcher(finalParameter); while (headers.find()) { String headerValue = msg.getRequestHeader().getHeader(headers.group(1)); if (headerValue == null) { headerValue = ""; } finalParameter = finalParameter.replace(headers.group(0), headerValue); } cmd.add(finalParameter); } } logger.debug("Invoking: " + cmd.toString()); View.getSingleton().getOutputPanel().append("\n" + cmd.toString() + "\n"); ProcessBuilder pb = new ProcessBuilder(cmd); if (workingDir != null) { pb.directory(workingDir); } pb.redirectErrorStream(true); Process proc; try { proc = pb.start(); } catch (final Exception e) { View.getSingleton().getOutputPanel() .append(Constant.messages.getString("invoke.error") + e.getLocalizedMessage() + "\n"); logger.warn("Failed to start the process: " + e.getMessage(), e); return null; } if (captureOutput) { try (BufferedReader brOut = new BufferedReader(new InputStreamReader(proc.getInputStream()))) { String line; boolean isOutput = false; StringBuilder sb = new StringBuilder(); if (msg.getNote() != null) { sb.append(msg.getNote()); sb.append('\n'); } // Show any stdout/error messages while ((line = brOut.readLine()) != null) { View.getSingleton().getOutputPanel().append(line + "\n"); sb.append(line); sb.append('\n'); isOutput = true; } if (isOutput) { // Somethings been written, switch to the Output tab View.getSingleton().getOutputPanel().setTabFocus(); } if (outputNote) { HistoryReference hr = msg.getHistoryRef(); if (hr != null) { hr.setNote(sb.toString()); } } } } return null; }
From source file:azkaban.jobExecutor.utils.process.AzkabanProcess.java
/** * Execute this process, blocking until it has completed. */// w ww . j a va 2 s. c o m public void run() throws IOException { if (this.isStarted() || this.isComplete()) { throw new IllegalStateException("The process can only be used once."); } ProcessBuilder builder = new ProcessBuilder(cmd); builder.directory(new File(workingDir)); builder.environment().putAll(env); builder.redirectErrorStream(true); this.process = builder.start(); try { this.processId = processId(process); if (processId == 0) { logger.debug("Spawned thread with unknown process id"); } else { logger.debug("Spawned thread with process id " + processId); } this.startupLatch.countDown(); LogGobbler outputGobbler = new LogGobbler(new InputStreamReader(process.getInputStream()), logger, Level.INFO, 30); LogGobbler errorGobbler = new LogGobbler(new InputStreamReader(process.getErrorStream()), logger, Level.ERROR, 30); outputGobbler.start(); errorGobbler.start(); int exitCode = -1; try { exitCode = process.waitFor(); } catch (InterruptedException e) { logger.info("Process interrupted. Exit code is " + exitCode, e); } completeLatch.countDown(); // try to wait for everything to get logged out before exiting outputGobbler.awaitCompletion(5000); errorGobbler.awaitCompletion(5000); if (exitCode != 0) { String output = new StringBuilder().append("Stdout:\n").append(outputGobbler.getRecentLog()) .append("\n\n").append("Stderr:\n").append(errorGobbler.getRecentLog()).append("\n") .toString(); throw new ProcessFailureException(exitCode, output); } } finally { IOUtils.closeQuietly(process.getInputStream()); IOUtils.closeQuietly(process.getOutputStream()); IOUtils.closeQuietly(process.getErrorStream()); } }
From source file:com.hivemq.maven.HiveMQMojo.java
/** * Starts the HiveMQ process with the given parameters * * @param commandParameters the parameters * @return the running HiveMQ process/*from www. ja va 2s . c o m*/ * @throws MojoExecutionException if the execution of HiveMQ did not work */ private Process startHiveMQ(final List<String> commandParameters) throws MojoExecutionException { final ProcessBuilder processBuilder = new ProcessBuilder(commandParameters); processBuilder.directory(hiveMQDir); processBuilder.redirectErrorStream(true); Process p; try { p = processBuilder.start(); } catch (IOException e) { log.error("An error occured while starting HiveMQ:", e); throw new MojoExecutionException("An error occured while starting HiveMQ", e); } return p; }
From source file:org.craftercms.deployer.git.processor.ShellProcessor.java
@Override public void doProcess(SiteConfiguration siteConfiguration, PublishedChangeSet changeSet) throws PublishingException { checkConfiguration(siteConfiguration); LOGGER.debug("Starting Shell Processor"); ProcessBuilder builder = new ProcessBuilder(); builder.directory(getWorkingDir(workingDir, siteConfiguration.getSiteId())); LOGGER.debug("Working directory is " + workingDir); HashMap<String, String> argumentsMap = buildArgumentsMap(getFileList(changeSet)); if (asSingleCommand) { StrSubstitutor substitutor = new StrSubstitutor(argumentsMap, "%{", "}"); String execComand = substitutor.replace(command); LOGGER.debug("Command to be Executed is " + execComand); builder.command("/bin/bash", "-c", execComand); } else {// w w w . java 2s. c om Set<String> keys = argumentsMap.keySet(); ArrayList<String> commandAsList = new ArrayList<String>(); commandAsList.add(command.trim()); for (String key : keys) { if (!key.equalsIgnoreCase(INCLUDE_FILTER_PARAM)) { commandAsList.add(argumentsMap.get(key)); } } LOGGER.debug("Command to be Executed is " + StringUtils.join(commandAsList, " ")); builder.command(commandAsList); } builder.environment().putAll(enviroment); builder.redirectErrorStream(true); try { Process process = builder.start(); process.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String str; while ((str = reader.readLine()) != null) { LOGGER.info("PROCESS OUTPUT :" + str); } reader.close(); LOGGER.info("Process Finish with Exit Code " + process.exitValue()); LOGGER.debug("Process Output "); } catch (IOException ex) { LOGGER.error("Error ", ex); } catch (InterruptedException e) { LOGGER.error("Error ", e); } finally { LOGGER.debug("End of Shell Processor"); } }
From source file:dk.netarkivet.wayback.aggregator.IndexAggregator.java
/** * Calls the Unix sort command with the options <code>$filesNames -o * $outputfile -T WaybackSettings#WAYBACK_AGGREGATOR_TEMP_DIR. * <p>//from ww w. ja v a 2s. com * Sets the LC_ALL environment variable before making the call. * * @param files The files to merge and sort * @param outputFile The resulting sorted file * @param additionalArgs A list af extra arguments, which (if different from null) are added to the sort call.<p> * Note: If any of the args contain a whitespace the call will fail. */ private void processFiles(File[] files, File outputFile, List<String> additionalArgs) { if (files.length == 0) { // Empty file list will cause sort to wait for further input, // and the call will therefore never return return; } Process p = null; try { List<String> inputFileList = new LinkedList<String>(); for (int i = 0; i < files.length; i++) { if (files[i].exists() && files[i].isFile()) { inputFileList.add(files[i].getCanonicalPath()); } else { log.warn("File " + files[i] + " doesn't exist or isn't a regular file, " + "dropping from list of files to " + "sort and merge"); } } List<String> cmd = new LinkedList<String>(); // Prepare to run the unix sort command, see sort manual page for // details cmd.add("sort"); cmd.addAll(inputFileList); cmd.add("-o"); cmd.add(outputFile.getCanonicalPath()); cmd.add("-T"); cmd.add(Settings.get(WaybackSettings.WAYBACK_AGGREGATOR_TEMP_DIR)); if (additionalArgs != null && !additionalArgs.isEmpty()) { for (String argument : additionalArgs) { ArgumentNotValid.checkTrue(argument.indexOf(' ') == -1, "The argument '" + argument + "' contains spaces, this isn't allowed "); } cmd.addAll(additionalArgs); } ProcessBuilder pb = new ProcessBuilder(cmd); // Reset all locale definitions pb.environment().put("LC_ALL", "C"); // Run the command in the user.dir directory pb.directory(new File(System.getProperty("user.dir"))); p = pb.start(); p.waitFor(); if (p.exitValue() != 0) { log.error("Failed to sort index files, sort exited with " + "return code " + p.exitValue()); } } catch (Exception e) { log.error("Failed to aggregate indexes ", e); } }