List of usage examples for org.apache.commons.exec DefaultExecuteResultHandler DefaultExecuteResultHandler
public DefaultExecuteResultHandler()
From source file:de.tu_dresden.psy.fca.ConexpCljBridge.java
public ConexpCljBridge() { this.b = new byte[1]; /**// w ww . j av a2 s . c om * build the command line (see conexp-clj/bin/conexp-clj) */ String java_bin = Launcher.getJavaCommand(); CommandLine conexp_cmd = new CommandLine(java_bin); conexp_cmd.addArgument("-server"); conexp_cmd.addArgument("-cp"); conexp_cmd.addArgument("./conexp-clj/lib/conexp-clj-0.0.7-alpha-SNAPSHOT-standalone.jar"); conexp_cmd.addArgument("clojure.main"); conexp_cmd.addArgument("-e"); conexp_cmd.addArgument(""); conexp_cmd.addArgument("./conexp-clj/lib/conexp-clj.clj"); /** * open the pipes */ this.to_conexp = new PipedOutputStream(); try { this.stream_to_conexp = new PipedInputStream(this.to_conexp, 2048); } catch (IOException e2) { e2.printStackTrace(); } this.stream_error_conexp = new PipedOutputStream(); this.stream_from_conexp = new PipedOutputStream(); try { this.from_conexp = new PipedInputStream(this.stream_from_conexp, 2048); } catch (IOException e1) { e1.printStackTrace(); } try { this.error_conexp = new PipedInputStream(this.stream_error_conexp, 2048); } catch (IOException e1) { e1.printStackTrace(); } /** * setup apache commons exec */ this.result = new DefaultExecuteResultHandler(); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setStreamHandler( new PumpStreamHandler(this.stream_from_conexp, this.stream_error_conexp, this.stream_to_conexp)); /** * run in non-blocking mode */ try { executor.execute(conexp_cmd, this.result); } catch (ExecuteException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } this.output_buffer = ""; }
From source file:com.jredrain.startup.AgentProcessor.java
@Override public Response execute(final Request request) throws TException { if (!this.password.equalsIgnoreCase(request.getPassword())) { return errorPasswordResponse(request); }/*w w w. j ava 2s.c o m*/ String command = request.getParams().get("command") + EXITCODE_SCRIPT; String pid = request.getParams().get("pid"); //?? Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L); boolean timeoutFlag = timeout > 0; logger.info("[redrain]:execute:{},pid:{}", command, pid); File shellFile = CommandUtils.createShellFile(command, pid); Integer exitValue; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final Response response = Response.response(request); final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE); final Timer timer = new Timer(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath()); final DefaultExecutor executor = new DefaultExecutor(); ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream); executor.setStreamHandler(stream); response.setStartTime(new Date().getTime()); //?0,shell executor.setExitValue(0); if (timeoutFlag) { //... executor.setWatchdog(watchdog); // timer.schedule(new TimerTask() { @Override public void run() { //,kill... if (watchdog.isWatching()) { /** * watchdogdestroyProcesskill... * watchdog.destroyProcess(); */ timer.cancel(); watchdog.stop(); //call kill... request.setAction(Action.KILL); try { kill(request); response.setExitCode(RedRain.StatusCode.TIME_OUT.getValue()); } catch (TException e) { e.printStackTrace(); } } } }, timeout * 60 * 1000); // resultHandler = new DefaultExecuteResultHandler() { @Override public void onProcessComplete(int exitValue) { super.onProcessComplete(exitValue); timer.cancel(); } @Override public void onProcessFailed(ExecuteException e) { super.onProcessFailed(e); timer.cancel(); } }; } executor.execute(commandLine, resultHandler); resultHandler.waitFor(); } catch (Exception e) { if (e instanceof ExecuteException) { exitValue = ((ExecuteException) e).getExitValue(); } else { exitValue = RedRain.StatusCode.ERROR_EXEC.getValue(); } if (RedRain.StatusCode.KILL.getValue().equals(exitValue)) { if (timeoutFlag) { timer.cancel(); watchdog.stop(); } logger.info("[redrain]:job has be killed!at pid :{}", request.getParams().get("pid")); } else { logger.info("[redrain]:job execute error:{}", e.getCause().getMessage()); } } finally { exitValue = resultHandler.getExitValue(); if (CommonUtils.notEmpty(outputStream.toByteArray())) { try { outputStream.flush(); String text = outputStream.toString(); if (notEmpty(text)) { try { text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), ""); response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY))); exitValue = Integer.parseInt(text .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim()); } catch (IndexOutOfBoundsException e) { response.setMessage(text); } } outputStream.close(); } catch (Exception e) { logger.error("[redrain]:error:{}", e); } } if (RedRain.StatusCode.TIME_OUT.getValue() == response.getExitCode()) { response.setSuccess(false).end(); } else { response.setExitCode(exitValue) .setSuccess(response.getExitCode() == RedRain.StatusCode.SUCCESS_EXIT.getValue()).end(); } if (shellFile != null) { shellFile.delete();// } } logger.info("[redrain]:execute result:{}", response.toString()); watchdog.stop(); return response; }
From source file:com.github.stephenc.mongodb.maven.StartMongoMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { if (skip) {/*from ww w. j ava 2 s.com*/ getLog().info("Skipping mongodb: mongodb.skip==true"); return; } if (installation == null) { getLog().info("Using mongod from PATH"); } else { getLog().info("Using mongod installed in " + installation); } getLog().info("Using database root of " + databaseRoot); final Logger mongoLogger = Logger.getLogger("com.mongodb"); Level mongoLevel = mongoLogger.getLevel(); try { mongoLogger.setLevel(Level.SEVERE); MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = false; opts.connectionsPerHost = 1; opts.connectTimeout = 50; opts.socketTimeout = 50; Mongo instance; try { instance = new Mongo(new ServerAddress("localhost", port), opts); List<String> databaseNames = instance.getDatabaseNames(); throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance with the following databases " + databaseNames); } catch (MongoException.Network e) { // fine... no instance running } catch (MongoException e) { throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance"); } catch (UnknownHostException e) { // ignore... localhost is always known! } } finally { mongoLogger.setLevel(mongoLevel); } CommandLine commandLine = null; if (installation != null && installation.isDirectory()) { File bin = new File(installation, "bin"); File exe = new File(bin, Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod"); if (exe.isFile()) { commandLine = new CommandLine(exe); } else { throw new MojoExecutionException("Could not find mongo executables in specified installation: " + installation + " expected to find " + exe + " but it does not exist."); } } if (commandLine == null) { commandLine = new CommandLine(Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod"); } if (databaseRoot.isFile()) { throw new MojoExecutionException("Database root " + databaseRoot + " is a file and not a directory"); } if (databaseRoot.isDirectory() && cleanDatabaseRoot) { getLog().info("Cleaning database root directory: " + databaseRoot); try { FileUtils.deleteDirectory(databaseRoot); } catch (IOException e) { throw new MojoExecutionException("Could not clean database root directory " + databaseRoot, e); } } if (!databaseRoot.isDirectory()) { getLog().debug("Creating database root directory: " + databaseRoot); if (!databaseRoot.mkdirs()) { throw new MojoExecutionException("Could not create database root directory " + databaseRoot); } } if (!verbose) { commandLine.addArgument("--quiet"); } commandLine.addArgument("--logpath"); commandLine.addArgument(logPath.getAbsolutePath()); if (logAppend) { commandLine.addArgument("--logappend"); } commandLine.addArgument(auth ? "--auth" : "--noauth"); commandLine.addArgument("--port"); commandLine.addArgument(Integer.toString(port)); commandLine.addArgument("--dbpath"); commandLine.addArgument(databaseRoot.getAbsolutePath()); if (additionalArguments != null) { for (String aa : additionalArguments) { commandLine.addArgument(aa); } } Executor exec = new DefaultExecutor(); DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler(); exec.setWorkingDirectory(databaseRoot); ProcessObserver processObserver = new ProcessObserver(new ShutdownHookProcessDestroyer()); exec.setProcessDestroyer(processObserver); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); getLog().info("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr)); try { exec.execute(commandLine, execHandler); getLog().info("Waiting for MongoDB to start..."); long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(120); mongoLevel = mongoLogger.getLevel(); try { mongoLogger.setLevel(Level.SEVERE); while (System.currentTimeMillis() < timeout && !execHandler.hasResult()) { MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = false; opts.connectionsPerHost = 1; opts.connectTimeout = 250; opts.socketTimeout = 250; Mongo instance; try { instance = new Mongo(new ServerAddress("localhost", port), opts); List<String> databaseNames = instance.getDatabaseNames(); getLog().info("MongoDb started."); getLog().info("Databases: " + databaseNames); } catch (MongoException.Network e) { // ignore, wait and try again try { Thread.sleep(50); } catch (InterruptedException e1) { // ignore } continue; } catch (MongoException e) { getLog().info("MongoDb started."); getLog().info("Unable to list databases due to " + e.getMessage()); } break; } } finally { mongoLogger.setLevel(mongoLevel); } if (execHandler.hasResult()) { ExecuteException exception = execHandler.getException(); if (exception != null) { throw new MojoFailureException(exception.getMessage(), exception); } throw new MojoFailureException( "Command " + commandLine + " exited with exit code " + execHandler.getExitValue()); } Map pluginContext = session.getPluginContext(getPluginDescriptor(), project); pluginContext.put(ProcessObserver.class.getName() + ":" + Integer.toString(port), processObserver); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:beans.DeployManagerImpl.java
private void execute(CommandLine cmdLine, ServerNode server) { try {/*w w w . j a v a2 s .c om*/ DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ProcExecutor executor = executorFactory.getDeployExecutor(server); logger.info("executing command [{}]", cmdLine); executor.execute(cmdLine, ApplicationContext.get().conf().server.environment.getEnvironment(), resultHandler); logger.info("The process instanceId: {}", executor.getId()); } catch (ExecuteException e) { logger.error("Failed to execute process. Exit value: " + e.getExitValue(), e); throw new ServerException("Failed to execute process. Exit value: " + e.getExitValue(), e); } catch (IOException e) { logger.error("Failed to execute process", e); throw new ServerException("Failed to execute process.", e); } }
From source file:com.tascape.qa.th.android.comm.Adb.java
public ExecuteWatchdog adbAsync(final List<Object> arguments, long timeoutMillis) throws IOException { CommandLine cmdLine = new CommandLine(ADB); if (!this.serial.isEmpty()) { cmdLine.addArgument("-s"); cmdLine.addArgument(serial);//ww w . j a v a 2s . c om } arguments.forEach((arg) -> { cmdLine.addArgument(arg + ""); }); LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " ")); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis); Executor executor = new DefaultExecutor(); executor.setWatchdog(watchdog); executor.setStreamHandler(new ESH()); executor.execute(cmdLine, new DefaultExecuteResultHandler()); return watchdog; }
From source file:io.selendroid.android.impl.AbstractDevice.java
private void startLogging() { logoutput = new ByteArrayOutputStream(); DefaultExecutor exec = new DefaultExecutor(); exec.setStreamHandler(new PumpStreamHandler(logoutput)); CommandLine command = adbCommand("logcat", "ResourceType:S", "dalvikvm:S", "Trace:S", "SurfaceFlinger:S", "StrictMode:S", "ExchangeService:S", "SVGAndroid:S", "skia:S", "LoaderManager:S", "ActivityThread:S", "-v", "time"); log.info("starting logcat:"); log.fine(command.toString());/* w w w . j ava 2 s . c o m*/ try { exec.execute(command, new DefaultExecuteResultHandler()); logcatWatchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); exec.setWatchdog(logcatWatchdog); } catch (IOException e) { e.printStackTrace(); } }
From source file:Logi.GSeries.Service.LogiGSKService.java
public void showSystemTray() { if ((systemTray != null) && !systemTrayVisible) { systemTray.setEnabled(true);// ww w .j a v a2 s. c om systemTrayVisible = true; return; } try { systemTray = SystemTray.getNative(); } catch (Exception ex) { System.out.println(ex.getMessage()); Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } if (systemTray != null) { try { systemTray.setImage(GSK_Icon); } catch (Exception e) { System.err.println("Problem setting system tray icon."); } systemTrayVisible = true; callbackOpen = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final MenuItem entry = (MenuItem) e.getSource(); try { CommandLine commandLine = new CommandLine("java"); commandLine.addArgument("-jar"); String jarPath = new URI( LogiGSKService.class.getProtectionDomain().getCodeSource().getLocation().getPath()) .getPath(); commandLine.addArgument(jarPath, false); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(1); executor.execute(commandLine, new DefaultExecuteResultHandler()); } catch (URISyntaxException ex) { Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } } }; callbackAbout = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final MenuItem entry = (MenuItem) e.getSource(); JOptionPane.showMessageDialog(null, "<HTML>LogiGSK V1.0</HTML>", "LogiGSK", JOptionPane.INFORMATION_MESSAGE); } }; Menu mainMenu = systemTray.getMenu(); MenuItem openEntry = new MenuItem("Open", new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final MenuItem entry = (MenuItem) e.getSource(); entry.setCallback(callbackOpen); try { CommandLine commandLine = new CommandLine("java"); commandLine.addArgument("-jar"); String jarPath = new URI( LogiGSKService.class.getProtectionDomain().getCodeSource().getLocation().getPath()) .getPath(); commandLine.addArgument(jarPath, false); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(1); executor.execute(commandLine, new DefaultExecuteResultHandler()); } catch (URISyntaxException ex) { Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex); } } }); openEntry.setShortcut('O'); mainMenu.add(openEntry); mainMenu.add(new Separator()); MenuItem aboutEntry = new MenuItem("About", new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final MenuItem entry = (MenuItem) e.getSource(); JOptionPane.showMessageDialog(null, "<HTML>LogiGSK V1.0</HTML>", "LogiGSK", JOptionPane.INFORMATION_MESSAGE); entry.setCallback(callbackAbout); } }); openEntry.setShortcut('A'); mainMenu.add(aboutEntry); /*} else { System.err.println("System tray is null!"); }*/ } }
From source file:info.pancancer.arch3.worker.WorkerRunnable.java
@Override public void run() { int max = maxRuns; try {//from w ww . j a v a 2 s.c om // the VM UUID log.info(" WORKER VM UUID provided as: '" + vmUuid + "'"); // write to // TODO: Add some sort of "local debug" mode so that developers working on their local // workstation can declare the queue if it doesn't exist. Normally, the results queue is // created by the Coordinator. resultsChannel = Utilities.setupExchange(settings, this.resultsQueueName); while (max > 0 || this.endless) { log.debug(max + " remaining jobs will be executed"); log.info(" WORKER IS PREPARING TO PULL JOB FROM QUEUE " + this.jobQueueName); if (!endless) { max--; } // jobChannel needs to be created inside the loop because it is closed inside the loop, and it is closed inside this loop to // prevent pre-fetching. Channel jobChannel = Utilities.setupQueue(settings, this.jobQueueName); if (jobChannel == null) { throw new NullPointerException("jobChannel is null for queue: " + this.jobQueueName + ". Something bad must have happened while trying to set up the queue connections. Please ensure that your configuration is correct."); } QueueingConsumer consumer = new QueueingConsumer(jobChannel); jobChannel.basicConsume(this.jobQueueName, false, consumer); QueueingConsumer.Delivery delivery = consumer.nextDelivery(); log.info(vmUuid + " received " + delivery.getEnvelope().toString()); if (delivery.getBody() != null) { String message = new String(delivery.getBody(), StandardCharsets.UTF_8); if (message.trim().length() > 0) { log.info(" [x] Received JOBS REQUEST '" + message + "' @ " + vmUuid); Job job = new Job().fromJSON(message); Status status = new Status(vmUuid, job.getUuid(), StatusState.RUNNING, Utilities.JOB_MESSAGE_TYPE, "job is starting", this.networkAddress); status.setStderr(""); status.setStdout(""); String statusJSON = status.toJSON(); log.info(" WORKER LAUNCHING JOB"); // greedy acknowledge, it will be easier to deal with lost jobs than zombie workers in hostile OpenStack // environments log.info(vmUuid + " acknowledges " + delivery.getEnvelope().toString()); jobChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); // we need to close the channel IMMEDIATELY to complete the ACK. jobChannel.close(); // Close the connection object as well, or the main thread may not exit because of still-open-and-in-use resources. jobChannel.getConnection().close(); WorkflowResult workflowResult = new WorkflowResult(); if (testMode) { workflowResult.setWorkflowStdout("everything is awesome"); workflowResult.setExitCode(0); } else { String seqwareEngine = settings.getString(Constants.WORKER_SEQWARE_ENGINE, Constants.SEQWARE_WHITESTAR_ENGINE); String seqwareSettingsFile = settings.getString(Constants.WORKER_SEQWARE_SETTINGS_FILE); String dockerImage = settings.getString(Constants.WORKER_SEQWARE_DOCKER_IMAGE_NAME); workflowResult = launchJob(statusJSON, job, seqwareEngine, seqwareSettingsFile, dockerImage); } status = new Status(vmUuid, job.getUuid(), workflowResult.getExitCode() == 0 ? StatusState.SUCCESS : StatusState.FAILED, Utilities.JOB_MESSAGE_TYPE, "job is finished", networkAddress); status.setStderr(workflowResult.getWorkflowStdErr()); status.setStdout(workflowResult.getWorkflowStdout()); statusJSON = status.toJSON(); log.info(" WORKER FINISHING JOB"); finishJob(statusJSON); } else { log.info(NO_MESSAGE_FROM_QUEUE_MESSAGE); } // we need to close the channel *conditionally* if (jobChannel.isOpen()) { jobChannel.close(); } // Close the connection object as well, or the main thread may not exit because of still-open-and-in-use resources. if (jobChannel.getConnection().isOpen()) { jobChannel.getConnection().close(); } } else { log.info(NO_MESSAGE_FROM_QUEUE_MESSAGE); } if (endless) { log.info("attempting to reset workspace"); DefaultExecutor executor = new DefaultExecutor(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); // attempt a cleanup CommandLine cli = new CommandLine("sudo"); List<String> args = new ArrayList<>(Arrays.asList("rm", "-rf", "/datastore/*")); cli.addArguments(args.toArray(new String[args.size()])); executor.execute(cli, resultHandler); // Use the result handler for non-blocking call, so this way we should be able to get updates of // stdout and stderr while the command is running. resultHandler.waitFor(); log.info("exit code for cleanup: " + resultHandler.getExitValue()); } } log.info(" \n\n\nWORKER FOR VM UUID HAS FINISHED!!!: '" + vmUuid + "'\n\n"); // turns out this is needed when multiple threads are reading from the same // queue otherwise you end up with multiple unacknowledged messages being undeliverable to other workers!!! if (resultsChannel != null && resultsChannel.isOpen()) { resultsChannel.close(); resultsChannel.getConnection().close(); } log.debug("result channel open: " + resultsChannel.isOpen()); log.debug("result channel connection open: " + resultsChannel.getConnection().isOpen()); } catch (Exception ex) { log.error(ex.getMessage(), ex); } }
From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java
private DefaultExecuteResultHandler executeFFmpeg(final CommandLine command, final int timeoutSeconds, final PumpStreamHandler streamHandler) throws IOException { final ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutSeconds * 1000); final Executor executor = new DefaultExecutor(); executor.setWatchdog(watchdog);/*from w ww. j ava 2 s. c o m*/ if (streamHandler != null) { executor.setStreamHandler(streamHandler); } final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); executor.execute(command, resultHandler); return resultHandler; }
From source file:io.selendroid.standalone.android.impl.AbstractDevice.java
private void startLogging() { logoutput = new ByteArrayOutputStream(); DefaultExecutor exec = new DefaultExecutor(); exec.setStreamHandler(new PumpStreamHandler(logoutput)); CommandLine command = adbCommand("logcat", "ResourceType:S", "dalvikvm:S", "Trace:S", "SurfaceFlinger:S", "StrictMode:S", "ExchangeService:S", "SVGAndroid:S", "skia:S", "LoaderManager:S", "ActivityThread:S", "-v", "time"); log.info("starting logcat:"); log.fine(command.toString());/*w ww.jav a2 s . c om*/ try { exec.execute(command, new DefaultExecuteResultHandler()); logcatWatchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); exec.setWatchdog(logcatWatchdog); } catch (IOException e) { log.log(Level.SEVERE, e.getMessage(), e); } }