List of usage examples for java.lang ProcessBuilder command
List command
To view the source code for java.lang ProcessBuilder command.
Click Source Link
From source file:cz.cuni.amis.planning4j.validation.external.ValValidator.java
@Override public IValidationResult validate(IPDDLFileDomainProvider domainProvider, IPDDLFileProblemProvider problemProvider, List<ActionDescription> plan) { File mainExecutable = new File(validatorDirectory, getValidatorFolderName() + File.separatorChar + getValidatorExecutableName()); if (!mainExecutable.exists()) { String toolMessage = "Could not find validator executable '" + getValidatorExecutableName() + "' in directory " + validatorDirectory.getAbsolutePath(); throw new ValidationException(toolMessage); }/*from w ww. ja v a 2s .c o m*/ FileWriter planWriter = null; Process process = null; try { /** * Write the plan to a temp file */ File planTempFile = File.createTempFile("plan", ".soln"); planWriter = new FileWriter(planTempFile); for (ActionDescription action : plan) { planWriter.write(action.getStartTime() + ": (" + action.getName() + " "); for (String param : action.getParameters()) { planWriter.write(param + " "); } planWriter.write(") [" + action.getDuration() + "]\n"); } planWriter.close(); planWriter = null; /** * Invoke the validator */ ProcessBuilder processBuilder = new ProcessBuilder(mainExecutable.getAbsolutePath(), "-s", //silent mode for simple parsing - only errors are printed to the stdout domainProvider.getDomainFile().getAbsolutePath(), problemProvider.getProblemFile().getAbsolutePath(), planTempFile.getAbsolutePath()); logger.info("Starting VAL validator."); if (logger.isDebugEnabled()) { logger.debug("The command: " + processBuilder.command()); } process = processBuilder.start(); Scanner outputScanner = new Scanner(process.getInputStream()); StringBuilder consoleOutputBuilder = new StringBuilder(); boolean hasNonEmptyLines = false; if (logger.isTraceEnabled()) { logger.trace("Validator output:"); } while (outputScanner.hasNextLine()) { String line = outputScanner.nextLine(); if (!consoleOutputBuilder.toString().isEmpty()) { consoleOutputBuilder.append("\n"); } if (!line.trim().isEmpty()) { hasNonEmptyLines = true; } consoleOutputBuilder.append(line); if (logger.isTraceEnabled()) { logger.trace(line); } } if (logger.isTraceEnabled()) { logger.trace("Validator output end."); } try { //clean the error stream. Otherwise this might prevent the process from being terminated / cleared from the process table IOUtils.toString(process.getErrorStream()); } catch (IOException ex) { logger.warn("Could not clear error stream.", ex); } process.waitFor(); boolean valid = !hasNonEmptyLines; //validator is run in silent mode, so any output means plan is not valid. logger.info("Validation finished. Result is: " + valid); return new ValidationResult(valid, consoleOutputBuilder.toString()); } catch (Exception ex) { if (planWriter != null) { try { planWriter.close(); } catch (Exception ignored) { } } if (process != null) { process.destroy(); try { //clean the streams so that the process does not hang in the process table IOUtils.toString(process.getErrorStream()); IOUtils.toString(process.getInputStream()); } catch (Exception ignored) { logger.warn("Could not clear output/error stream.", ignored); } } throw new ValidationException("Error during validation", ex); } }
From source file:org.opencb.cellbase.lib.loader.MongoDBCellBaseLoader.java
protected boolean runCreateIndexProcess(Path indexFilePath) throws IOException, InterruptedException { // DatabaseProperties mongodbCredentials = cellBaseConfiguration.getDatabases().get("mongodb"); DatabaseCredentials mongodbCredentials = cellBaseConfiguration.getDatabases().getMongodb(); List<String> args = new ArrayList<>(); args.add("mongo"); args.add("--host"); args.add(mongodbCredentials.getHost()); if (mongodbCredentials.getUser() != null && !mongodbCredentials.getUser().equals("")) { args.addAll(Arrays.asList("-u", mongodbCredentials.getUser(), "-p", mongodbCredentials.getPassword())); }/*from w ww . jav a 2 s . c om*/ if (cellBaseConfiguration != null && mongodbCredentials.getOptions().get("authenticationDatabase") != null) { args.add("--authenticationDatabase"); args.add(mongodbCredentials.getOptions().get("authenticationDatabase")); logger.debug("MongoDB 'authenticationDatabase' database parameter set to '{}'", mongodbCredentials.getOptions().get("authenticationDatabase")); } args.add(database); args.add(indexFilePath.toString()); ProcessBuilder processBuilder = new ProcessBuilder(args); logger.debug("Executing command: '{}'", StringUtils.join(processBuilder.command(), " ")); // processBuilder.redirectErrorStream(true); // if (logFilePath != null) { // processBuilder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(logFilePath))); // } Process process = processBuilder.start(); process.waitFor(); // Check process output boolean executedWithoutErrors = true; int genomeInfoExitValue = process.exitValue(); if (genomeInfoExitValue != 0) { logger.warn("Error executing {}, error code: {}", indexFilePath, genomeInfoExitValue); executedWithoutErrors = false; } return executedWithoutErrors; }
From source file:com.hellblazer.process.impl.AbstractManagedProcess.java
/** * The actual execution process. Control will not return until the command * list execution has finished./*from ww w .j ava 2 s . c om*/ * * @param commands * - the command list to execute * * @throws IOException * - if anything goes wrong during the execution. */ protected void primitiveExecute(List<String> commands) throws IOException { ProcessBuilder builder = new ProcessBuilder(); builder.directory(directory); if (environment != null) { builder.environment().putAll(environment); } builder.command(commands); builder.redirectErrorStream(true); // combine OUT and ERR into one // stream Process p = builder.start(); final BufferedReader shellReader = new BufferedReader(new InputStreamReader(p.getInputStream())); Runnable reader = new Runnable() { @Override public void run() { String line; try { line = shellReader.readLine(); } catch (IOException e) { if (!"Stream closed".equals(e.getMessage()) && !e.getMessage().contains("Bad file descriptor")) { log.log(Level.SEVERE, "Failed reading process output", e); } return; } while (line != null) { if (log.isLoggable(Level.FINE) && line != null) { log.fine("[" + id + "] " + line); } try { line = shellReader.readLine(); } catch (IOException e) { if (!"Stream closed".equals(e.getMessage())) { log.log(Level.SEVERE, "Failed reading process output", e); } return; } } } }; Thread readerThread = new Thread(reader, "Process reader for: " + getCommand()); readerThread.setDaemon(true); readerThread.start(); try { p.waitFor(); } catch (InterruptedException e) { return; } finally { readerThread.interrupt(); p.destroy(); } }
From source file:edu.rice.dca.soaplabPBS.PBSJob.java
/************************************************************************** * Called before the execution. Here, a sub-class has a chance to * change/add/remove some command-line arguments and/or * environment variables, or even the working directory (all of * these are in the given ProcessBuilder). * * The method can thrown an exception if the current set of * arguments is not good for being executed. **************************************************************************/ protected void preExec(ProcessBuilder pb) throws SoaplabException { report("Name: " + getServiceName()); report("Job ID: " + getId()); StringBuilder buf = new StringBuilder(); buf.append("Program and parameters:\n"); for (String str : pb.command()) { buf.append(str);/*from w w w . ja va2 s . co m*/ buf.append("\n"); } buf.append("--- end of parameters\n"); report(buf.toString()); }
From source file:eu.numberfour.n4js.npmexporter.ui.NpmExportWizard.java
@Override public boolean performFinish() { String destination = exportPage.getDestinationValue(); List<IProject> toExport = exportPage.getChosenProjects(); boolean shouldPackAsTarball = exportPage.getShouldPackAsTarball(); File folder = new File(destination); // remap all IProjects List<? extends IN4JSProject> toExportIN4JSProjects = mapToIN4JSProjects(toExport); if (runTools() && toolRunnerPage.isToolrunRequested()) { // bring to front. ((WizardDialog) getContainer()).showPage(toolRunnerPage); }//from ww w . java 2s . c o m try { npmExporter.export(toExportIN4JSProjects, folder); if (shouldPackAsTarball) { npmExporter.tarAndZip(toExportIN4JSProjects, folder); } boolean runIt = runTools() && toolRunnerPage.queryRunTool(); if (runIt) { final List<String> toolCommand = toolRunnerPage.getCommand(); getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { List<String> cmds = newArrayList(); // cmds.add("echo"); // prepend with echo for debug TODO remove // cmds.addAll(toolCommand); cmds.add("bash"); cmds.add("-login"); cmds.add("-c"); // cmds.addAll(toolCommand); cmds.add(Joiner.on(" ").join(toolCommand)); System.out.println("Comman will be: " + Joiner.on(" :: ").join(cmds)); for (IN4JSProject p : toExportIN4JSProjects) { String info = "Processing " + p.toString() + "\n"; System.out.println(info); toolRunnerPage.appendText(info); File dir = npmExporter.exportDestination(p, folder); ProcessBuilder pb = new ProcessBuilder(); pb.directory(dir); pb.command(cmds); pb.redirectErrorStream(true); Process proc = pb.start(); // handle each of proc's streams in a separate thread ExecutorService handlerThreadPool = Executors.newFixedThreadPool(3); // handlerThreadPool.submit(new Runnable() { // @Override // public void run() { // // we want to write to the stdin of the process // BufferedWriter stdin = new BufferedWriter( // new OutputStreamWriter(proc.getOutputStream())); // // // read from our own stdin so we can write it to proc's stdin // BufferedReader myStdin = // new BufferedReader(new InputStreamReader(System.in)); // String line = null; // try { // do { // line = myStdin.readLine(); // stdin.write(String.format("%s%n", line)); // stdin.flush(); // } while(! "exit".equalsIgnoreCase(line)); // } catch(IOException e) { // e.printStackTrace(); // } // } // }); handlerThreadPool.submit(new Runnable() { @Override public void run() { // we want to read the stdout of the process BufferedReader stdout = new BufferedReader( new InputStreamReader(proc.getInputStream())); String line; try { while (null != (line = stdout.readLine())) { System.err.printf("[stderr] %s%n", line); toolRunnerPage.appendConsoleOut(line); } } catch (IOException e) { e.printStackTrace(); } } }); handlerThreadPool.submit(new Runnable() { @Override public void run() { // we want to read the stderr of the process BufferedReader stderr = new BufferedReader( new InputStreamReader(proc.getErrorStream())); String line; try { while (null != (line = stderr.readLine())) { System.err.printf("[stderr] %s%n", line); toolRunnerPage.appendConsoleErr(line); } } catch (IOException e) { e.printStackTrace(); } } }); // wait for the process to terminate int exitCode = proc.waitFor(); System.out.printf("Process terminated with exit code %d%n", exitCode); handlerThreadPool.shutdown(); } // done with all projects. // wait for close. toolRunnerPage.queryCloseDialog(); } catch (Exception e) { throw new InvocationTargetException(e); } } }); } } catch (IOException | ArchiveException | CompressorException e) { e.printStackTrace(); Status s = new Status(ERROR, NpmExporterActivator.PLUGIN_ID, "Error occured during export.", e); N4JSActivator.getInstance().getLog().log(s); return false; } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // successfully done, then store relevant history: exportPage.finish(); if (runTools()) { toolRunnerPage.finish(); } return true; }
From source file:org.zgis.wps.swat.AnnotatedSwatRunnerAlgorithm.java
@Execute public void runSwatProcess() throws IOException { logger.info("Trying to run SWAT model"); //TODO make a list of needed directories and create in loop String tempDirStr = ExecutionContextFactory.getContext().getTempDirectoryPath(); File tempDir = new File(tempDirStr + System.getProperty("file.separator")); File swatModelDir = new File(tempDirStr + System.getProperty("file.separator") + "swatmodel" + System.getProperty("file.separator")); logger.info("Temp dir is: " + tempDirStr); logger.info("Temp file is: " + tempDir.getAbsolutePath()); try {//from w w w . j av a 2s .c o m if (!tempDir.isDirectory() && !tempDir.mkdirs()) { throw new IOException("Could not create temp dir " + tempDir); } if (!swatModelDir.isDirectory() && !swatModelDir.mkdirs()) { throw new IOException("Could not create swatmodel dir " + tempDir); } //unpack swat model if (swatInputZip == null) { logger.info("SwatInputZip was NULL"); } else if (swatInputZip.size() != 1) { logger.info("SwatInputZip size != 1 - " + swatInputZip.size()); } else { logger.info("Unpacking swatInputZip " + swatInputZip.get(0).getBaseFile(false).getAbsolutePath() + " to " + swatModelDir.getAbsolutePath()); net.lingala.zip4j.core.ZipFile zipFile = new net.lingala.zip4j.core.ZipFile( swatInputZip.get(0).getBaseFile(false)); zipFile.extractAll(swatModelDir.getAbsolutePath()); } URI jarUri = this.getJarURI(); logger.debug("Jar-File URI " + jarUri); //FIXME this is bullshit, make own jar for every OS and provide executable this way. String exeFilename = "swat/swat_rel64"; if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { exeFilename = exeFilename.concat("_win.exe"); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac")) { exeFilename = exeFilename.concat("_osx"); } else if (System.getProperty("os.name").toLowerCase().startsWith("linux")) { exeFilename = exeFilename.concat("_linux"); } else { logger.warn("Could not determine OS, trying generic executable name"); } URI exeFile = getFile(jarUri, exeFilename); new File(exeFile).setExecutable(true); ProcessBuilder pb = new ProcessBuilder(new File(exeFile).toString()); pb.redirectErrorStream(true); pb.directory(swatModelDir); Process process = pb.start(); InputStream stdOutStream = process.getInputStream(); InputStreamReader isr = new InputStreamReader(stdOutStream); BufferedReader br = new BufferedReader(isr); String line; logger.info(String.format("Output of running %s is:\n", Arrays.toString(pb.command().toArray()))); while ((line = br.readLine()) != null) { logger.info(line); this.swatConsoleOutput = this.swatConsoleOutput.concat(line).concat("\n"); } int exitValue = process.waitFor(); if (exitValue != 0) { throw new IOException("SWAT didn't complete successfully"); } Collection<File> outFiles = FileUtils.listFiles(swatModelDir, new WildcardFileFilter("output.*"), TrueFileFilter.TRUE); File outFilesZippend = org.n52.wps.io.IOUtils.zip(outFiles.toArray(new File[outFiles.size()])); this.swatOutputZipped = new GenericFileData(outFilesZippend, "application/zip"); } catch (URISyntaxException e) { logger.error("Could not determine uri of jar. ", e); throw new IOException("Could not determine uri of jar. ", e); } catch (InterruptedException e) { logger.error("Exception on running SWAT process.", e); throw new IOException("Exception on running SWAT process.", e); } catch (net.lingala.zip4j.exception.ZipException e) { logger.error("Could not extract swat input model.", e); throw new IOException("Could not extract swat input model.", e); } finally { //TODO FIXME is that really necessary? The Execution context should delete this? /* if (tempDir.isDirectory()) { FileUtils.deleteDirectory(tempDir); } */ } }
From source file:uk.ac.ebi.eva.pipeline.jobs.steps.VepAnnotationGeneratorStep.java
@Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ObjectMap pipelineOptions = jobOptions.getPipelineOptions(); ProcessBuilder processBuilder = new ProcessBuilder("perl", pipelineOptions.getString("app.vep.path"), "--cache", "--cache_version", pipelineOptions.getString("app.vep.cache.version"), "-dir", pipelineOptions.getString("app.vep.cache.path"), "--species", pipelineOptions.getString("app.vep.cache.species"), "--fasta", pipelineOptions.getString("input.fasta"), "--fork", pipelineOptions.getString("app.vep.num-forks"), "-i", pipelineOptions.getString("vep.input"), "-o", "STDOUT", "--force_overwrite", "--offline", "--everything"); logger.debug("VEP annotation parameters = " + Arrays.toString(processBuilder.command().toArray())); logger.info("Starting read from VEP output"); Process process = processBuilder.start(); long written = connectStreams(new BufferedInputStream(process.getInputStream()), new GZIPOutputStream(new FileOutputStream(pipelineOptions.getString("vep.output")))); int exitValue = process.waitFor(); logger.info("Finishing read from VEP output, bytes written: " + written); if (exitValue > 0) { String errorLog = pipelineOptions.getString("vep.output") + ".errors.txt"; connectStreams(new BufferedInputStream(process.getErrorStream()), new FileOutputStream(errorLog)); throw new Exception("Error while running VEP (exit status " + exitValue + "). See " + errorLog + " for the errors description from VEP."); }//w ww . j av a2s. c om return RepeatStatus.FINISHED; }
From source file:com.photon.phresco.plugins.xcode.XcodeBuild.java
/** * Execute the xcode command line utility. *//* ww w. j ava 2s . co m*/ public void execute() throws MojoExecutionException { if (!xcodeCommandLine.exists()) { throw new MojoExecutionException( "Invalid path, invalid xcodebuild file: " + xcodeCommandLine.getAbsolutePath()); } /* * // Compute archive name String archiveName = * project.getBuild().getFinalName() + ".cust"; File finalDir = new * File(buildDirectory, archiveName); * * // Configure archiver MavenArchiver archiver = new MavenArchiver(); * archiver.setArchiver(jarArchiver); archiver.setOutputFile(finalDir); */ try { if (!SdkVerifier.isAvailable(sdk)) { throw new MojoExecutionException("Selected version " + sdk + " is not available!"); } } catch (IOException e2) { throw new MojoExecutionException("SDK verification failed!"); } catch (InterruptedException e2) { throw new MojoExecutionException("SDK verification interrupted!"); } try { init(); configure(); ProcessBuilder pb = new ProcessBuilder(xcodeCommandLine.getAbsolutePath()); // Include errors in output pb.redirectErrorStream(true); List<String> commands = pb.command(); if (xcodeProject != null) { commands.add("-project"); commands.add(xcodeProject); } if (StringUtils.isNotBlank(configuration)) { commands.add("-configuration"); commands.add(configuration); } if (StringUtils.isNotBlank(sdk)) { commands.add("-sdk"); commands.add(sdk); } commands.add("OBJROOT=" + buildDirectory); commands.add("SYMROOT=" + buildDirectory); commands.add("DSTROOT=" + buildDirectory); if (StringUtils.isNotBlank(xcodeTarget)) { commands.add("-target"); commands.add(xcodeTarget); } if (StringUtils.isNotBlank(gccpreprocessor)) { commands.add("GCC_PREPROCESSOR_DEFINITIONS=" + gccpreprocessor); } if (unittest) { commands.add("clean"); commands.add("build"); } getLog().info("List of commands" + pb.command()); // pb.command().add("install"); pb.directory(new File(basedir)); Process child = pb.start(); // Consume subprocess output and write to stdout for debugging InputStream is = new BufferedInputStream(child.getInputStream()); int singleByte = 0; while ((singleByte = is.read()) != -1) { // output.write(buffer, 0, bytesRead); System.out.write(singleByte); } child.waitFor(); int exitValue = child.exitValue(); getLog().info("Exit Value: " + exitValue); if (exitValue != 0) { throw new MojoExecutionException("Compilation error occured. Resolve the error(s) and try again!"); } if (!unittest) { //In case of unit testcases run, the APP files will not be generated. createdSYM(); createApp(); } /* * child.waitFor(); * * InputStream in = child.getInputStream(); InputStream err = * child.getErrorStream(); getLog().error(sb.toString()); */ } catch (IOException e) { getLog().error("An IOException occured."); throw new MojoExecutionException("An IOException occured", e); } catch (InterruptedException e) { getLog().error("The clean process was been interrupted."); throw new MojoExecutionException("The clean process was been interrupted", e); } catch (MojoFailureException e) { // TODO Auto-generated catch block e.printStackTrace(); } File directory = new File(this.basedir + "/pom.xml"); this.project.getArtifact().setFile(directory); }
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 {//from w w w. j a v a2 s.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:org.raspinloop.fmi.VMRunner.java
@Override public void run() { String separator = System.getProperty("file.separator"); String path = System.getProperty("java.home") + separator + "bin" + separator + "java"; ProcessBuilder processBuilder; try {/*from www. j a v a 2 s .com*/ processBuilder = new ProcessBuilder(path, VMRunnerUtils.getRunnerAgentArgument(".", jSonConfigName, false), VMRunnerUtils.getWeaverAgentArgument(".", false), vMArguments, "-cp", classPath.stream().collect(Collectors.joining(":")), className, programArguments); } catch (Exception e) { logger.error("Cannot configure process: " + e.getMessage()); throw new VMRunnerUncheckedException(e); } if (System.getProperty("mock") == null || !System.getProperty("mock").equalsIgnoreCase("true")) { try { logger.debug( "==> starting JVM " + processBuilder.command().stream().collect(Collectors.joining(" "))); process = processBuilder.inheritIO().start(); } catch (Exception e) { logger.error("Cannot start process: " + e.getMessage()); throw new VMRunnerUncheckedException(e); } CompletableFuture.supplyAsync(() -> { try { return process.waitFor(); } catch (InterruptedException e) { throw new RuntimeException(e); } }).thenAccept(i -> logger.info("<== JVM Stopped code(" + i + ")")); } else { logger.info("PLEASE RUN " + processBuilder.command().stream().collect(Collectors.joining(" "))); while (true) { try { Thread.sleep(100); } catch (InterruptedException e) { logger.info("PLEASE STOP "); return; } } } }