List of usage examples for java.lang ProcessBuilder ProcessBuilder
public ProcessBuilder(String... command)
From source file:com.quartzdesk.executor.core.job.LocalCommandExecutorJob.java
@Override protected void executeJob(JobExecutionContext context) throws JobExecutionException { log.debug("Inside job: {}", context.getJobDetail().getKey()); JobDataMap jobDataMap = context.getMergedJobDataMap(); // command//from ww w.j a va 2 s . c om String command = jobDataMap.getString(JDM_KEY_COMMAND); if (command == null) { throw new JobExecutionException("Missing required '" + JDM_KEY_COMMAND + "' job data map parameter."); } // command arguments (optional) String commandArgs = jobDataMap.getString(JDM_KEY_COMMAND_ARGS); // command work directory (optional) String commandWorkDir = jobDataMap.getString(JDM_KEY_COMMAND_WORK_DIR); File commandWorkDirFile = null; if (commandWorkDir != null) { commandWorkDirFile = new File(commandWorkDir); if (!commandWorkDirFile.exists() || !commandWorkDirFile.isDirectory()) { throw new JobExecutionException( "Command work directory '" + commandWorkDirFile.getAbsolutePath() + "' specified in the '" + JDM_KEY_COMMAND_WORK_DIR + "' job data map parameter does not exist."); } } // execute the command List<String> commandLine = prepareCommandLine(command, commandArgs); ProcessBuilder processBuilder = new ProcessBuilder(commandLine); processBuilder.redirectErrorStream(true); // set the process work directory if specified; otherwise the default work directory is used if (commandWorkDirFile != null) { processBuilder.directory(commandWorkDirFile); } // we could possibly set the process environment here //processBuilder.environment() try { log.info("Executing local command using command line: {}", commandLine); ExecutorService standardOutputExecutor = getProcessOutputExecutor(context); Process process = processBuilder.start(); StandardOutputReaderCallable stdOutCallable = new StandardOutputReaderCallable( process.getInputStream()); Future<String> stdOutDataFuture = standardOutputExecutor.submit(stdOutCallable); int exitCode = process.waitFor(); // wait for the process to finish log.debug("Local command finished with exit code: {}", exitCode); context.setResult(exitCode); // exit code is used as the job's execution result (visible in the QuartzDesk GUI) try { String output = stdOutDataFuture.get(); if (StringUtils.isBlank(output)) { log.info("Local command produced no output."); } else { log.info("Local command produced the following output:{}{}", CommonConst.NL, output); } } catch (Exception e) // CancellationException, ExecutionException, InterruptedException { log.warn("Error getting process data.", e); } // if result != 0, we typically want to throw JobExecutionException indicating a job execution failure if (exitCode != 0) { throw new JobExecutionException("Command finished with non-zero exit code: " + exitCode); } } catch (IOException e) { throw new JobExecutionException("Error starting command process.", e); } catch (InterruptedException e) { throw new JobExecutionException("Command process has been interrupted.", e); } }
From source file:edu.pitt.dbmi.ccd.queue.service.AlgorithmQueueService.java
@Async public Future<Void> runAlgorithmFromQueue(JobQueueInfo jobQueueInfo) { Long queueId = jobQueueInfo.getId(); String fileName = jobQueueInfo.getFileName() + ".txt"; String jsonFileName = jobQueueInfo.getFileName() + ".json"; String commands = jobQueueInfo.getCommands(); String tmpDirectory = jobQueueInfo.getTmpDirectory(); String outputDirectory = jobQueueInfo.getOutputDirectory(); List<String> cmdList = new LinkedList<>(); cmdList.addAll(Arrays.asList(commands.split(";"))); cmdList.add("--out"); cmdList.add(tmpDirectory);//from ww w. j av a2 s . co m StringBuilder sb = new StringBuilder(); cmdList.forEach(cmd -> { sb.append(cmd); sb.append(" "); }); LOGGER.info("Algorithm command: " + sb.toString()); String errorFileName = String.format("error_%s", fileName); Path error = Paths.get(tmpDirectory, errorFileName); Path errorDest = Paths.get(outputDirectory, errorFileName); Path src = Paths.get(tmpDirectory, fileName); Path dest = Paths.get(outputDirectory, fileName); Path json = Paths.get(tmpDirectory, jsonFileName); Path jsonDest = Paths.get(outputDirectory, jsonFileName); try { ProcessBuilder pb = new ProcessBuilder(cmdList); pb.redirectError(error.toFile()); Process process = pb.start(); //Get process Id Long pid = Processes.processId(process); JobQueueInfo queuedJobInfo = jobQueueInfoService.findOne(queueId); LOGGER.info("Set Job's pid to be: " + pid); queuedJobInfo.setPid(pid); jobQueueInfoService.saveJobIntoQueue(queuedJobInfo); process.waitFor(); if (process.exitValue() == 0) { LOGGER.info(String.format("Moving txt file %s to %s", src, dest)); Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING); LOGGER.info(String.format("Moving json file %s to %s", json, dest)); Files.move(json, jsonDest, StandardCopyOption.REPLACE_EXISTING); Files.deleteIfExists(error); } else { LOGGER.info(String.format("Deleting tmp txt file %s", src)); Files.deleteIfExists(src); LOGGER.info(String.format("Moving error file %s to %s", error, errorDest)); Files.move(error, errorDest, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException | InterruptedException exception) { LOGGER.error("Algorithm did not run successfully.", exception); } LOGGER.info("Delete Job ID from queue: " + queueId); jobQueueInfoService.deleteJobById(queueId); return new AsyncResult<>(null); }
From source file:io.hops.hopsworks.common.security.PKIUtils.java
public static String createCRL(Settings settings, boolean intermediate) throws IOException, InterruptedException { logger.info("Creating crl..."); String generatedCrlFile;//from w w w . j ava 2s . c o m List<String> cmds = new ArrayList<>(); cmds.add("openssl"); cmds.add("ca"); cmds.add("-batch"); cmds.add("-config"); if (intermediate) { cmds.add(settings.getIntermediateCaDir() + "/openssl-intermediate.cnf"); generatedCrlFile = settings.getIntermediateCaDir() + "/crl/intermediate.crl.pem"; } else { cmds.add(settings.getCaDir() + "/openssl-ca.cnf"); generatedCrlFile = settings.getCaDir() + "/crl/ca.crl.pem"; } cmds.add("-passin"); cmds.add("pass:" + settings.getHopsworksMasterPasswordSsl()); cmds.add("-gencrl"); cmds.add("-out"); cmds.add(generatedCrlFile); StringBuilder sb = new StringBuilder("/usr/bin/"); for (String s : cmds) { sb.append(s).append(" "); } logger.info(sb.toString()); Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true) .start(); BufferedReader br = new BufferedReader( new InputStreamReader(process.getInputStream(), Charset.forName("UTF8"))); String line; while ((line = br.readLine()) != null) { logger.info(line); } process.waitFor(); int exitValue = process.exitValue(); if (exitValue != 0) { throw new RuntimeException("Failed to create crl. Exit value: " + exitValue); } logger.info("Created crl."); return FileUtils.readFileToString(new File(generatedCrlFile)); }
From source file:com.googlecode.flyway.ant.AntLargeTest.java
/** * Runs Ant in this directory with these extra arguments. * * @param expectedReturnCode The expected return code for this invocation. * @param dir The directory below src/test/resources to run maven in. * @param extraArgs The extra arguments (if any) for Maven. * @return The standard output./*from w w w . j a v a2s. c om*/ * @throws Exception When the execution failed. */ private String runAnt(int expectedReturnCode, String dir, String... extraArgs) throws Exception { String antHome = System.getenv("ANT_HOME"); String extension = ""; if (System.getProperty("os.name").startsWith("Windows")) { extension = ".bat"; } List<String> args = new ArrayList<String>(); args.add(antHome + "/bin/ant" + extension); args.add("-DlibDir=" + System.getProperty("libDir")); args.addAll(Arrays.asList(extraArgs)); ProcessBuilder builder = new ProcessBuilder(args); builder.directory(new File(installDir + "/" + dir)); builder.redirectErrorStream(true); Process process = builder.start(); String stdOut = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream(), "UTF-8")); int returnCode = process.waitFor(); System.out.print(stdOut); assertEquals("Unexpected return code", expectedReturnCode, returnCode); return stdOut; }
From source file:com.googlecode.flyway.maven.largetest.MavenLargeTest.java
/** * Runs Maven in this directory with these extra arguments. * * @param expectedReturnCode The expected return code for this invocation. * @param dir The directory below src/test/resources to run maven in. * @param extraArgs The extra arguments (if any) for Maven. * @return The standard output./*from ww w .ja v a 2s.c o m*/ * @throws Exception When the execution failed. */ private String runMaven(int expectedReturnCode, String dir, String... extraArgs) throws Exception { String m2Home = System.getenv("M2_HOME"); String flywayVersion = System.getProperty("flywayVersion"); String extension = ""; if (System.getProperty("os.name").startsWith("Windows")) { extension = ".bat"; } List<String> args = new ArrayList<String>(); args.add(m2Home + "/bin/mvn" + extension); args.add("-Dflyway.version=" + flywayVersion); args.addAll(Arrays.asList(extraArgs)); ProcessBuilder builder = new ProcessBuilder(args); builder.directory(new File(installDir + "/" + dir)); builder.redirectErrorStream(true); Process process = builder.start(); String stdOut = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream(), "UTF-8")); int returnCode = process.waitFor(); System.out.print(stdOut); assertEquals("Unexpected return code", expectedReturnCode, returnCode); return stdOut; }
From source file:com.synopsys.integration.blackduck.codelocation.signaturescanner.command.ScanCommandCallable.java
@Override public ScanCommandOutput call() { String commandToExecute = "command_not_yet_configured"; try {/*from w w w . jav a 2 s . c om*/ final ScanPaths scanPaths = scanPathsUtility .determineSignatureScannerPaths(scanCommand.getInstallDirectory()); final List<String> cmd = scanCommand.createCommandForProcessBuilder(logger, scanPaths, scanCommand.getOutputDirectory().getAbsolutePath()); cmd.add(scanCommand.getTargetPath()); commandToExecute = createPrintableCommand(cmd); logger.info(String.format("Black Duck CLI command: %s", commandToExecute)); final File standardOutFile = scanPathsUtility.createStandardOutFile(scanCommand.getOutputDirectory()); try (FileOutputStream outputFileStream = new FileOutputStream(standardOutFile)) { final ScannerSplitStream splitOutputStream = new ScannerSplitStream(logger, outputFileStream); final ProcessBuilder processBuilder = new ProcessBuilder(cmd); processBuilder.environment().putAll(intEnvironmentVariables.getVariables()); if (!scanCommand.isDryRun()) { if (!StringUtils.isEmpty(scanCommand.getApiToken())) { processBuilder.environment().put("BD_HUB_TOKEN", scanCommand.getApiToken()); } else { processBuilder.environment().put("BD_HUB_PASSWORD", scanCommand.getPassword()); } } processBuilder.environment().put("BD_HUB_NO_PROMPT", "true"); final Process blackDuckCliProcess = processBuilder.start(); // The cli logs go the error stream for some reason final StreamRedirectThread redirectThread = new StreamRedirectThread( blackDuckCliProcess.getErrorStream(), splitOutputStream); redirectThread.start(); int returnCode = -1; try { returnCode = blackDuckCliProcess.waitFor(); // the join method on the redirect thread will wait until the thread is dead // the thread will die when it reaches the end of stream and the run method is finished redirectThread.join(); } finally { if (blackDuckCliProcess.isAlive()) { blackDuckCliProcess.destroy(); } if (redirectThread.isAlive()) { redirectThread.interrupt(); } } splitOutputStream.flush(); logger.info(IOUtils.toString(blackDuckCliProcess.getInputStream(), StandardCharsets.UTF_8)); logger.info("Black Duck Signature Scanner return code: " + returnCode); logger.info( "You can view the logs at: '" + scanCommand.getOutputDirectory().getCanonicalPath() + "'"); if (returnCode != 0) { return ScanCommandOutput.FAILURE(scanCommand.getName(), logger, scanCommand, commandToExecute, returnCode); } } } catch (final Exception e) { final String errorMessage = String.format("There was a problem scanning target '%s': %s", scanCommand.getTargetPath(), e.getMessage()); return ScanCommandOutput.FAILURE(scanCommand.getName(), logger, scanCommand, commandToExecute, errorMessage, e); } if (!scanCommand.isDryRun() && cleanupOutput) { FileUtils.deleteQuietly(scanCommand.getOutputDirectory()); } else if (scanCommand.isDryRun() && cleanupOutput) { // delete everything except dry run files final File[] outputFiles = scanCommand.getOutputDirectory().listFiles(); for (final File outputFile : outputFiles) { if (!DRY_RUN_FILES_TO_KEEP.contains(outputFile.getName())) { FileUtils.deleteQuietly(outputFile); } } } return ScanCommandOutput.SUCCESS(scanCommand.getName(), logger, scanCommand, commandToExecute); }
From source file:com.diffplug.gradle.CmdLine.java
/** Runs the given command in the given directory with the given echo setting. */ public static Result runCmd(File directory, String cmd, boolean echoCmd, boolean echoOutput) throws IOException { // set the cmds List<String> cmds = getPlatformCmds(cmd); ProcessBuilder builder = new ProcessBuilder(cmds); // set the working directory builder.directory(directory);/*w w w . j a va 2 s. co m*/ // execute the command Process process = builder.start(); // wrap the process' input and output try (BufferedReader stdInput = new BufferedReader( new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); BufferedReader stdError = new BufferedReader( new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()));) { if (echoCmd) { System.out.println("cmd>" + cmd); } // dump the output ImmutableList.Builder<String> output = ImmutableList.builder(); ImmutableList.Builder<String> error = ImmutableList.builder(); String line = null; while ((line = stdInput.readLine()) != null) { output.add(line); if (echoOutput) { System.out.println(line); } } // dump the input while ((line = stdError.readLine()) != null) { error.add(line); if (echoOutput) { System.err.println(line); } } // check that the process exited correctly int exitValue = process.waitFor(); if (exitValue != EXIT_VALUE_SUCCESS) { throw new RuntimeException("'" + cmd + "' exited with " + exitValue); } // returns the result of this successful execution return new Result(directory, cmd, output.build(), error.build()); } catch (InterruptedException e) { // this isn't expected, but it's possible throw new RuntimeException(e); } }
From source file:com.sms.server.service.parser.MetadataParser.java
public MediaElement parse(MediaElement mediaElement) { try {/*from w w w . j av a 2 s . c o m*/ // Use transcoder to parse file metadata File parser = transcodeService.getTranscoder(); String[] command = new String[] { parser.getAbsolutePath(), "-i", mediaElement.getPath() }; ProcessBuilder processBuilder = new ProcessBuilder(command).redirectErrorStream(true); Process process = processBuilder.start(); String[] metadata = readInputStream(process.getInputStream()); // Get Media Type Byte mediaType = mediaElement.getType(); // Begin Parsing for (String line : metadata) { Matcher matcher; if (mediaType == MediaElementType.AUDIO || mediaType == MediaElementType.VIDEO) { // // Duration // matcher = DURATION.matcher(line); if (matcher.find()) { int hours = Integer.parseInt(matcher.group(1)); int minutes = Integer.parseInt(matcher.group(2)); int seconds = Integer.parseInt(matcher.group(3)); mediaElement.setDuration(hours * 3600 + minutes * 60 + seconds); } // // Bitrate // matcher = BITRATE.matcher(line); if (matcher.find()) { mediaElement.setBitrate(Integer.parseInt(matcher.group(1))); } // // Audio Stream // matcher = AUDIO_STREAM.matcher(line); if (matcher.find()) { // Language // Always set audio language for video elements if (matcher.group(1) == null && mediaType == MediaElementType.VIDEO) { mediaElement.setAudioLanguage( addToCommaSeparatedList(mediaElement.getAudioLanguage(), "und")); } // Set audio language if present if (matcher.group(1) != null) { mediaElement.setAudioLanguage(addToCommaSeparatedList(mediaElement.getAudioLanguage(), String.valueOf(matcher.group(2)))); } // Codec mediaElement.setAudioCodec(addToCommaSeparatedList(mediaElement.getAudioCodec(), String.valueOf(matcher.group(3)))); //Sample Rate mediaElement.setAudioSampleRate(addToCommaSeparatedList(mediaElement.getAudioSampleRate(), String.valueOf(matcher.group(4)))); //Configuration mediaElement.setAudioConfiguration(addToCommaSeparatedList( mediaElement.getAudioConfiguration(), String.valueOf(matcher.group(5)))); } } if (mediaType == MediaElementType.AUDIO) { // // Title // matcher = TITLE.matcher(line); if (matcher.find()) { mediaElement.setTitle(String.valueOf(matcher.group(1))); } // // Artist // matcher = ARTIST.matcher(line); if (matcher.find()) { mediaElement.setArtist(String.valueOf(matcher.group(2))); } // // Album Artist // matcher = ALBUMARTIST.matcher(line); if (matcher.find()) { mediaElement.setAlbumArtist(String.valueOf(matcher.group(2))); } // // Album // matcher = ALBUM.matcher(line); if (matcher.find()) { mediaElement.setAlbum(String.valueOf(matcher.group(1))); } // // Comment // matcher = COMMENT.matcher(line); if (matcher.find()) { mediaElement.setDescription(String.valueOf(matcher.group(1))); } // // Date // matcher = YEAR.matcher(line); if (matcher.find()) { mediaElement.setYear(Short.parseShort(matcher.group(2))); } // // Disc Number // matcher = DISCNUMBER.matcher(line); if (matcher.find()) { mediaElement.setDiscNumber(Byte.parseByte(matcher.group(2))); } // // Disc Subtitle // matcher = DISCSUBTITLE.matcher(line); if (matcher.find()) { mediaElement.setDiscSubtitle(String.valueOf(matcher.group(1))); } // // Track Number // matcher = TRACK.matcher(line); if (matcher.find()) { mediaElement.setTrackNumber(Short.parseShort(matcher.group(1))); } // // Genre // matcher = GENRE.matcher(line); if (matcher.find()) { mediaElement.setGenre(String.valueOf(matcher.group(1))); } } if (mediaType == MediaElementType.VIDEO) { // // Video Stream // matcher = VIDEO_STREAM.matcher(line); // Only pull metadata for the first video stream (embedded images are also detected as video...) if (matcher.find() && mediaElement.getVideoCodec() == null) { // Codec mediaElement.setVideoCodec(String.valueOf(matcher.group(1))); // Dimensions short width = Short.parseShort(matcher.group(2)); short height = Short.parseShort(matcher.group(3)); if (width > 0 && height > 0) { mediaElement.setVideoWidth(width); mediaElement.setVideoHeight(height); } } // // Subtitle Stream // matcher = SUBTITLE_STREAM.matcher(line); if (matcher.find()) { // Language if (matcher.group(1) == null) { mediaElement.setSubtitleLanguage( addToCommaSeparatedList(mediaElement.getSubtitleLanguage(), "und")); } else { mediaElement.setSubtitleLanguage(addToCommaSeparatedList( mediaElement.getSubtitleLanguage(), String.valueOf(matcher.group(2)))); } // Format mediaElement.setSubtitleFormat(addToCommaSeparatedList(mediaElement.getSubtitleFormat(), String.valueOf(matcher.group(3)))); //Forced if (matcher.group(4) == null) { mediaElement.setSubtitleForced( addToCommaSeparatedList(mediaElement.getSubtitleForced(), "false")); } else { mediaElement.setSubtitleForced( addToCommaSeparatedList(mediaElement.getSubtitleForced(), "true")); } } } } } catch (IOException x) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Unable to parse metadata for file " + mediaElement.getPath(), x); } return mediaElement; }
From source file:com.liferay.blade.tests.BladeCLI.java
public static String startServerWindows(File workingDir, String... bladeArgs) throws Exception { String bladeCLIJarPath = getLatestBladeCLIJar(); List<String> command = new ArrayList<>(); command.add("start"); command.add("/b"); command.add("java"); command.add("-jar"); command.add(bladeCLIJarPath);/*from w w w . j a v a 2 s .com*/ for (String arg : bladeArgs) { command.add(arg); } Process process = new ProcessBuilder(command.toArray(new String[0])).directory(workingDir).start(); process.waitFor(); InputStream stream = process.getInputStream(); String output = new String(IO.read(stream)); InputStream errorStream = process.getErrorStream(); String errors = new String(IO.read(errorStream)); assertTrue(errors, errors == null || errors.isEmpty()); return output; }
From source file:de.huberlin.wbi.hiway.common.Worker.java
private int exec() { File script = new File("./" + containerId); script.setExecutable(true);//from w w w . ja va2 s . c om ProcessBuilder processBuilder = new ProcessBuilder(script.getPath()); processBuilder.directory(new File(".")); Process process; int exitValue = -1; try { File stdOutFile = new File(Invocation.STDOUT_FILENAME); File stdErrFile = new File(Invocation.STDERR_FILENAME); processBuilder.redirectOutput(stdOutFile); processBuilder.redirectError(stdErrFile); process = processBuilder.start(); exitValue = process.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); System.exit(-1); } return exitValue; }