List of usage examples for java.lang ProcessBuilder ProcessBuilder
public ProcessBuilder(String... command)
From source file:com.liferay.petra.doulos.processor.BaseShellDoulosRequestProcessor.java
protected void execute(ShellStatus shellStatus) throws Exception { shellStatus.status = "executing"; List<String> shellCommandsList = getShellCommands(shellStatus); shellCommandsList.add(0, "/bin/bash"); shellCommandsList.add(1, "-x"); shellCommandsList.add(2, "-c"); String[] shellCommands = shellCommandsList.toArray(new String[shellCommandsList.size()]); shellStatus.shellCommands = StringUtils.join(shellCommands, "\n"); ProcessBuilder processBuilder = new ProcessBuilder(shellCommands); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); StringBuilder sb = new StringBuilder(); String line = null;//from w w w . ja va2 s . com BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = bufferedReader.readLine()) != null) { sb.append(line); sb.append("\n"); } bufferedReader.close(); try { if (_log.isDebugEnabled()) { _log.debug("Wait for process to finish"); } process.waitFor(); shellStatus.exitValue = String.valueOf(process.exitValue()); shellStatus.output = sb.toString(); shellStatus.status = "finished"; } catch (Exception e) { Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); e.printStackTrace(printWriter); shellStatus.exception = writer.toString(); shellStatus.status = "exception"; } }
From source file:functionalTests.annotations.AptTest.java
private Result runApt() throws CompilationExecutionException { try {/*from www . j a v a2s .co m*/ ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(_aptCommand)); Map<String, String> env = processBuilder.environment(); env.put("CLASSPATH", _classpath); Process aptProcess = processBuilder.start(); BufferedReader stderr = new BufferedReader(new InputStreamReader(aptProcess.getErrorStream())); //flushOutput(stderr); return getResults(stderr); } catch (IOException ioExcp) { String msg = "Cannot execute the command " + compressCommand(_aptCommand) + ".reason:" + ioExcp.getMessage(); logger.error(msg, ioExcp); throw new CompilationExecutionException(msg, ioExcp); } catch (SecurityException secExcp) { String msg = "Cannot execute the command " + compressCommand(_aptCommand) + "; security access violation."; logger.error(msg, secExcp); throw new CompilationExecutionException(msg, secExcp); } }
From source file:bboss.org.artofsolving.jodconverter.office.OfficeProcess.java
public void start(boolean restart) throws IOException { ProcessQuery processQuery = new ProcessQuery("soffice.bin", unoUrl.getAcceptString()); long existingPid = processManager.findPid(processQuery); if (existingPid != PID_UNKNOWN) { throw new IllegalStateException( String.format("a process with acceptString '%s' is already running; pid %d", unoUrl.getAcceptString(), existingPid)); }/*from w w w .j a va 2 s . c om*/ if (!restart) { prepareInstanceProfileDir(); } List<String> command = new ArrayList<String>(); File executable = OfficeUtils.getOfficeExecutable(officeHome); if (runAsArgs != null) { command.addAll(Arrays.asList(runAsArgs)); } command.add(executable.getAbsolutePath()); if (!PlatformUtils.isWindows()) command.add("-accept=" + unoUrl.getAcceptString() + ";urp;"); else command.add("-accept=\"" + unoUrl.getAcceptString() + ";urp;\""); if (PlatformUtils.isWindows()) command.add("-env:UserInstallation=\"" + OfficeUtils.toUrl(instanceProfileDir) + "\""); else command.add("-env:UserInstallation=" + OfficeUtils.toUrl(instanceProfileDir) + ""); System.out.println("instanceProfileDir--------------:" + instanceProfileDir); command.add("-headless"); command.add("-nocrashreport"); command.add("-nodefault"); command.add("-nofirststartwizard"); command.add("-nolockcheck"); command.add("-nologo"); command.add("-norestore"); ProcessBuilder processBuilder = new ProcessBuilder(command); if (PlatformUtils.isWindows()) { if (this.officeHome != null) { if (officeHome.getAbsolutePath().toLowerCase().contains("libre")) addLiberofficeBasisAndUrePaths(processBuilder); else addBasisAndUrePaths(processBuilder); } else addBasisAndUrePaths(processBuilder); } logger.info(String.format("starting process with acceptString '%s' and profileDir '%s'", unoUrl, instanceProfileDir)); process = processBuilder.start(); pid = processManager.findPid(processQuery); logger.info("started process" + (pid != PID_UNKNOWN ? "; pid = " + pid : "")); }
From source file:com.atlassian.labs.bamboo.git.edu.nyu.cs.javagit.client.cli.ProcessUtilities.java
/** * Runs the command specified in the command line with the specified working directory. The * IParser is used to parse the response given by the command line. * * @param workingDirectory/*www .j a va2 s. co m*/ * The working directory in with which to start the process. * @param commandLine * The command line to run. * @param parser * The parser to use to parse the command line's response. * @return The command response from the <code>IParser</code>. * @throws IOException * Thrown if there are problems with the subprocess. * @throws JavaGitException */ public static CommandResponse runCommand(File workingDirectory, List<String> commandLine, IParser parser) throws IOException, JavaGitException { ProcessBuilder pb = new ProcessBuilder(commandLine); LOG.debug("Command:" + commandLine); if (workingDirectory != null) { pb.directory(workingDirectory); } pb.redirectErrorStream(true); Process p = startProcess(pb); getProcessOutput(p, parser); waitForAndDestroyProcess(p, parser); return parser.getResponse(); }
From source file:com.netflix.genie.server.jobmanager.impl.PrestoJobManagerImpl.java
/** * {@inheritDoc}// www . ja v a 2s . c om */ @Override public void launch() throws GenieException { LOG.info("called"); if (!this.isInitCalled()) { throw new GeniePreconditionException("Init wasn't called. Unable to continue."); } // Check the parameters final String prestoProtocol = ConfigurationManager.getConfigInstance().getString(PRESTO_PROTOCOL_KEY, null); if (prestoProtocol == null) { throw new GeniePreconditionException( "Presto protocol not set. Please configure " + PRESTO_PROTOCOL_KEY); } final String prestoMasterDomain = ConfigurationManager.getConfigInstance().getString(PRESTO_MASTER_DOMAIN, null); if (prestoMasterDomain == null) { throw new GeniePreconditionException( "Presto protocol not set. Please configure " + PRESTO_MASTER_DOMAIN); } // create the ProcessBuilder for this process final List<String> processArgs = this.createBaseProcessArguments(); processArgs.add("--server"); processArgs.add(prestoProtocol + this.getCluster().getName() + prestoMasterDomain); processArgs.add("--catalog"); processArgs.add("hive"); processArgs.add("--user"); processArgs.add(this.getJob().getUser()); processArgs.add("--debug"); processArgs.addAll(Arrays.asList(StringUtil.splitCmdLine(this.getJob().getCommandArgs()))); final ProcessBuilder processBuilder = new ProcessBuilder(processArgs); // construct the environment variables this.setupCommonProcess(processBuilder); this.setupPrestoProcess(processBuilder); // Launch the actual process this.launchProcess(processBuilder, ConfigurationManager.getConfigInstance() .getInt("com.netflix.genie.server.job.manager.presto.sleeptime", 5000)); }
From source file:com.googlecode.flyway.commandline.largetest.CommandLineLargeTest.java
/** * Runs the Flyway Command Line tool./*from w w w . ja v a2s . c o m*/ * * @param expectedReturnCode The expected return code for this invocation. * @param configFileName The config file name. {@code null} for default. * @param operation The operation {@code null} for none. * @param extraArgs The extra arguments to pass to the tool. * @return The standard output produced by the tool. * @throws Exception thrown when the invocation failed. */ private String runFlywayCommandLine(int expectedReturnCode, String configFileName, String operation, String... extraArgs) throws Exception { List<String> args = new ArrayList<String>(); String installDir = System.getProperty("installDir"); args.add(installDir + "/flyway." + flywayCmdLineExtensionForCurrentSystem()); if (operation != null) { args.add(operation); } if (configFileName != null) { String configFile = new ClassPathResource("largeTest.properties").getFile().getPath(); args.add("-configFile=" + configFile); } args.addAll(Arrays.asList(extraArgs)); ProcessBuilder builder = new ProcessBuilder(args); builder.directory(new File(installDir)); 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.openshift.internal.restclient.capability.resources.AbstractOpenShiftBinaryCapability.java
private void startProcess(String location) { String cmdLine = new StringBuilder(location).append(' ').append(buildArgs()).toString(); String[] args = StringUtils.split(cmdLine, " "); ProcessBuilder builder = new ProcessBuilder(args); LOG.debug("OpenShift binary args: {}", builder.command()); try {//from ww w . j av a 2s .c o m process = builder.start(); checkProcessIsAlive(); } catch (IOException e) { LOG.error("Could not start process for {}.", new Object[] { getName(), e }); throw new OpenShiftException(e, "Does your OpenShift binary location exist? Error starting process: %s", e.getMessage()); } }
From source file:gui.sqlmap.SqlmapUi.java
private void startSqlmap() { String python = textfieldPython.getText(); String workingDir = textfieldWorkingdir.getText(); String sqlmap = textfieldSqlmap.getText(); // Do some basic tests File f;//ww w . j a v a 2 s.c o m f = new File(python); if (!f.exists()) { JOptionPane.showMessageDialog(this, "Python path does not exist: " + python); return; } f = new File(workingDir); if (!f.exists()) { JOptionPane.showMessageDialog(this, "workingDir path does not exist: " + workingDir); return; } f = new File(sqlmap); if (!f.exists()) { JOptionPane.showMessageDialog(this, "sqlmap path does not exist: " + sqlmap); return; } // Write request file String requestFile = workingDir + "request.txt"; try { FileOutputStream fos = new FileOutputStream(requestFile); fos.write(httpMessage.getRequest()); fos.close(); } catch (IOException e) { JOptionPane.showMessageDialog(this, "could not write request: " + workingDir + "request.txt"); BurpCallbacks.getInstance().print("Error: " + e.getMessage()); } // Start sqlmap args = new ArrayList<String>(); args.add(python); args.add(sqlmap); args.add("-r"); args.add(requestFile); args.add("--batch"); args.add("-p"); args.add(attackParam.getName()); String sessionFile = workingDir + "sessionlog.txt"; args.add("-s"); args.add(sessionFile); args.add("--flush-session"); String traceFile = workingDir + "tracelog.txt"; args.add("-t"); args.add(traceFile); args.add("--disable-coloring"); args.add("--cleanup"); textareaCommand.setText(StringUtils.join(args, " ")); SwingWorker worker = new SwingWorker<String, Void>() { @Override public String doInBackground() { ProcessBuilder pb = new ProcessBuilder(args); //BurpCallbacks.getInstance().print(pb.command().toString()); pb.redirectErrorStream(true); Process proc; try { proc = pb.start(); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; int exit = -1; while ((line = br.readLine()) != null) { // Outputs your process execution addLine(line); try { exit = proc.exitValue(); if (exit == 0) { // Process finished } } catch (IllegalThreadStateException t) { // The process has not yet finished. // Should we stop it? //if (processMustStop()) // processMustStop can return true // after time out, for example. //{ // proc.destroy(); //} } } } catch (IOException ex) { BurpCallbacks.getInstance().print(ex.getLocalizedMessage()); } return ""; } @Override public void done() { } }; worker.execute(); }
From source file:metadata.etl.dataset.hdfs.HdfsMetadataEtl.java
private void extractLocal() throws Exception { URL localJarUrl = classLoader.getResource("jar/schemaFetch.jar"); String homeDir = System.getProperty("user.home"); String remoteJarFile = homeDir + "/.wherehows/schemaFetch.jar"; File dest = new File(remoteJarFile); try {/*from ww w. j a v a2s . co m*/ FileUtils.copyURLToFile(localJarUrl, dest); } catch (Exception e) { logger.error(e.toString()); } String outputSchemaFile = prop.getProperty(Constant.HDFS_SCHEMA_LOCAL_PATH_KEY); String outputSampleDataFile = prop.getProperty(Constant.HDFS_SAMPLE_LOCAL_PATH_KEY); String cluster = prop.getProperty(Constant.HDFS_CLUSTER_KEY); String whiteList = prop.getProperty(Constant.HDFS_WHITE_LIST_KEY); String numOfThread = prop.getProperty(Constant.HDFS_NUM_OF_THREAD_KEY, String.valueOf(1)); String hdfsUser = prop.getProperty(Constant.HDFS_REMOTE_USER_KEY); // String hdfsKeyTab = prop.getProperty(Constant.HDFS_REMOTE_KEYTAB_LOCATION_KEY); String hdfsExtractLogFile = outputSchemaFile + ".log"; String[] hadoopCmd = { "hadoop", "jar", remoteJarFile, "-D" + Constant.HDFS_SCHEMA_REMOTE_PATH_KEY + "=" + outputSchemaFile, "-D" + Constant.HDFS_SAMPLE_REMOTE_PATH_KEY + "=" + outputSampleDataFile, "-D" + Constant.HDFS_CLUSTER_KEY + "=" + cluster, "-D" + Constant.HDFS_WHITE_LIST_KEY + "=" + whiteList, "-D" + Constant.HDFS_NUM_OF_THREAD_KEY + "=" + numOfThread, "-D" + Constant.HDFS_REMOTE_USER_KEY + "=" + hdfsUser, "-Dlog.file.name=hdfs_schema_fetch" }; // delete the line (no kerberos needed): "-D" + Constant.HDFS_REMOTE_KEYTAB_LOCATION_KEY + "=" + hdfsKeyTab, ProcessBuilder pb = new ProcessBuilder(hadoopCmd); File logFile = new File(hdfsExtractLogFile); pb.redirectErrorStream(true); pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile)); Process process = pb.start(); int pid = -1; if (process.getClass().getName().equals("java.lang.UNIXProcess")) { /* get the PID on unix/linux systems */ try { Field f = process.getClass().getDeclaredField("pid"); f.setAccessible(true); pid = f.getInt(process); } catch (Throwable e) { } } logger.info("executue command [PID=" + pid + "]: " + hadoopCmd); // wait until this process finished. int execResult = process.waitFor(); // if the process failed, log the error and throw exception if (execResult > 0) { BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream())); String errString = "HDFS Metadata Extract Error:\n"; String line = ""; while ((line = br.readLine()) != null) errString = errString.concat(line).concat("\n"); logger.error("*** Process failed, status: " + execResult); logger.error(errString); throw new Exception("Process + " + pid + " failed"); } }
From source file:com.frostwire.gui.updates.UpdateMediator.java
public void startUpdate() { GUIMediator.safeInvokeLater(new Runnable() { public void run() { File executableFile = getUpdateBinaryFile(); if (executableFile == null || latestMsg == null) { return; }//from w w w . j a v a 2 s. c o m try { if (OSUtils.isWindows()) { String[] commands = new String[] { "CMD.EXE", "/C", executableFile.getAbsolutePath() }; ProcessBuilder pbuilder = new ProcessBuilder(commands); pbuilder.start(); } else if (OSUtils.isLinux() && OSUtils.isUbuntu()) { String[] commands = new String[] { "gdebi-gtk", executableFile.getAbsolutePath() }; ProcessBuilder pbuilder = new ProcessBuilder(commands); pbuilder.start(); } else if (OSUtils.isMacOSX()) { String[] mountCommand = new String[] { "hdiutil", "attach", executableFile.getAbsolutePath() }; String[] finderShowCommand = new String[] { "open", "/Volumes/" + FilenameUtils.getBaseName(executableFile.getName()) }; ProcessBuilder pbuilder = new ProcessBuilder(mountCommand); Process mountingProcess = pbuilder.start(); mountingProcess.waitFor(); pbuilder = new ProcessBuilder(finderShowCommand); pbuilder.start(); } GUIMediator.shutdown(); } catch (Throwable e) { LOG.error("Unable to launch new installer", e); } } }); }