List of usage examples for org.apache.commons.exec DefaultExecuteResultHandler getExitValue
public int getExitValue()
From source file:com.github.stephenc.mongodb.maven.StartMongoMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { if (skip) {/*from ww w. ja va 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:com.jredrain.startup.AgentProcessor.java
@Override public Response execute(final Request request) throws TException { if (!this.password.equalsIgnoreCase(request.getPassword())) { return errorPasswordResponse(request); }// w ww. java 2 s.com 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:gov.nasa.jpl.magicdraw.projectUsageIntegrity.graph.SSCAEProjectUsageGraph.java
public BufferedImageFile convertDOTFile(@Nonnull File pugDOT, @Nonnull DOTImageFormat dotImageFormat) throws IIOException, IOException, InterruptedException { String dotCommand = ProjectUsageIntegrityPlugin.getInstance().getDOTexecutablePath(); if (null == dotCommand) return null; File pugTemp = pugDOT.getParentFile(); File pugImage = new File(pugTemp.getAbsoluteFile() + File.separator + project.getID() + "." + DOTImageFormatName.get(dotImageFormat)); if (pugImage.exists()) { pluginLog.info(String.format("%s - convertDOTFile - deleting previous image for '%s' : '%s'", pluginName, project.getName(), pugImage.getName())); pugImage.delete();//from w w w . j av a 2 s .co m } CommandLine cmdLine = new CommandLine(dotCommand); cmdLine.addArgument("-Tpng"); cmdLine.addArgument("-o"); cmdLine.addArgument(pugImage.getName()); cmdLine.addArgument(pugDOT.getName()); pluginLog.info(String.format("%s - convertDOTgraph - converting gv to image for '%s'", pluginName, project.getName())); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); // consider '0' exit value as success. Executor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setWatchdog(watchdog); executor.setWorkingDirectory(pugTemp); executor.execute(cmdLine, resultHandler); resultHandler.waitFor(); if (!executor.isFailure(resultHandler.getExitValue())) { pluginLog.info(String.format("%s - convertDOTgraph - reading image for '%s' from: '%s'", pluginName, project.getName(), pugImage.getName())); BufferedImageFile imageFile = new BufferedImageFile(pugImage); pluginLog.info( String.format("%s - convertDOTgraph - got image for '%s'", pluginName, project.getName())); return imageFile; } return null; }
From source file:gov.nasa.jpl.magicdraw.projectUsageIntegrity.graph.SSCAEProjectUsageGraph.java
/** * @param pugDOT gv file/*from www . j ava 2 s.com*/ * @return true if the graphviz application was opened successfully for the gv file. * @throws IIOException * @throws IOException * @throws InterruptedException */ public boolean openDOTFileWithGraphViz(@Nonnull File pugDOT) throws IIOException, IOException, InterruptedException { String graphvizApp = ProjectUsageIntegrityPlugin.getInstance().getGraphvizApplicationPath(); if (null == graphvizApp) return false; File pugTemp = pugDOT.getParentFile(); CommandLine cmdLine; switch (SSCAEProjectUsageIntegrityOptions.getCurrentPlatform()) { case LINUX: cmdLine = new CommandLine(graphvizApp); break; case MACOSX: cmdLine = new CommandLine("/usr/bin/open"); cmdLine.addArgument("-a"); cmdLine.addArgument(graphvizApp); break; case WINDOWS: cmdLine = new CommandLine("cmd"); cmdLine.addArgument("/c"); cmdLine.addArgument("start"); cmdLine.addArgument(graphvizApp); break; default: return false; } cmdLine.addArgument(pugDOT.getName()); pluginLog.info(String.format("%s - openDOTFileWithGraphViz - opening DOT file for project: '%s'", pluginName, project.getName())); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); // consider '0' exit value as success. Executor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setWatchdog(watchdog); executor.setWorkingDirectory(pugTemp); executor.execute(cmdLine, resultHandler); resultHandler.waitFor(); if (executor.isFailure(resultHandler.getExitValue())) { pluginLog.error(String.format( "%s - openDOTFileWithGraphViz - error while opening DOT file for project '%s' from: '%s'", pluginName, project.getName(), pugDOT.getAbsolutePath()), resultHandler.getException()); return false; } pluginLog.info(String.format("%s - openDOTFileWithGraphViz - opened DOT file for project '%s' from: '%s'", pluginName, project.getName(), pugDOT.getAbsolutePath())); return true; }
From source file:net.test.aliyun.z7.Zip7Object.java
public static int extract(final String extToosHome, final String extractFile, final String toDir) throws Throwable { String cmdLine = String.format("%s\\7z.exe x \"%s\" -aoa -y \"-o%s\"", extToosHome, extractFile, toDir); CommandLine commandline = CommandLine.parse(cmdLine); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); DefaultExecutor executor = new DefaultExecutor(); int extValue = -1; try {//from ww w .j a v a2s. co m executor.execute(commandline, resultHandler); resultHandler.waitFor(300 * 1000); extValue = resultHandler.getExitValue(); if (extValue == 0) { new File(extractFile).delete(); } } catch (Exception e) { // } finally { if (extValue != 0) { FileUtils.deleteDir(new File(toDir)); return extValue; } } // Iterator<File> itFile = FileUtils.iterateFiles(new File(toDir), FileFilterUtils.fileFileFilter(), FileFilterUtils.directoryFileFilter()); while (itFile.hasNext()) { File it = itFile.next(); if (it.isDirectory()) continue; for (String com : compression) { if (StringUtils.endsWithIgnoreCase(it.getName(), com)) { String itPath = it.getAbsolutePath(); String subToDir = itPath.substring(0, itPath.length() - com.length()); extract(extToosHome, itPath, subToDir); } } } return 0; }
From source file:org.apache.bigtop.itest.hive.HiveHelper.java
public static Map<String, String> execCommand(CommandLine commandline, Map<String, String> envVars) { System.out.println("Executing command:"); System.out.println(commandline.toString()); Map<String, String> env = null; Map<String, String> entry = new HashMap<String, String>(); try {//w w w. j ava 2s.com env = EnvironmentUtils.getProcEnvironment(); } catch (IOException e1) { // TODO Auto-generated catch block LOG.debug("Failed to get process environment: " + e1.getMessage()); e1.printStackTrace(); } if (envVars != null) { for (String key : envVars.keySet()) { env.put(key, envVars.get(key)); } } DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 10000); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); try { executor.execute(commandline, env, resultHandler); } catch (ExecuteException e) { // TODO Auto-generated catch block LOG.debug("Failed to execute command with exit value: " + String.valueOf(resultHandler.getExitValue())); LOG.debug("outputStream: " + outputStream.toString()); entry.put("exitValue", String.valueOf(resultHandler.getExitValue())); entry.put("outputStream", outputStream.toString() + e.getMessage()); e.printStackTrace(); return entry; } catch (IOException e) { // TODO Auto-generated catch block LOG.debug("Failed to execute command with exit value: " + String.valueOf(resultHandler.getExitValue())); LOG.debug("outputStream: " + outputStream.toString()); entry.put("exitValue", String.valueOf(resultHandler.getExitValue())); entry.put("outputStream", outputStream.toString() + e.getMessage()); e.printStackTrace(); return entry; } try { resultHandler.waitFor(); /*System.out.println("Command output: "+outputStream.toString());*/ entry.put("exitValue", String.valueOf(resultHandler.getExitValue())); entry.put("outputStream", outputStream.toString()); return entry; } catch (InterruptedException e) { // TODO Auto-generated catch block /*System.out.println("Command output: "+outputStream.toString());*/ LOG.debug("exitValue: " + String.valueOf(resultHandler.getExitValue())); LOG.debug("outputStream: " + outputStream.toString()); entry.put("exitValue", String.valueOf(resultHandler.getExitValue())); entry.put("outputStream", outputStream.toString()); e.printStackTrace(); return entry; } }
From source file:org.apache.geode.examples.replicated.ReplicatedTest.java
/** * Given a script file name, runs the script and return the exit code. * If exitCode != 0 extract and prints exception. * @param scriptName/* w w w.j ava2s . com*/ * @return <code>int</code> with exitCode * @throws IOException * @throws InterruptedException */ private int executeScript(String scriptName) throws IOException, InterruptedException { final int exitCode; DefaultExecuteResultHandler resultHandler = shell.execute(scriptName, scriptTimeout, environment, testFolder.getRoot()); processRunning = true; resultHandler.waitFor(); logger.finest(String.format("Executing %s...", scriptName)); exitCode = resultHandler.getExitValue(); // extract and log exception if any happened if (exitCode != 0) { ExecuteException executeException = resultHandler.getException(); logger.log(Level.SEVERE, executeException.getMessage(), executeException); } return exitCode; }
From source file:org.eclipse.smarthome.io.net.exec.ExecUtil.java
/** * <p>//from w w w .ja v a 2 s. c om * Executes <code>commandLine</code>. Sometimes (especially observed on * MacOS) the commandLine isn't executed properly. In that cases another * exec-method is to be used. To accomplish this please use the special * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this * delimiter it is split into a String[] array and the special exec-method * is used. * </p> * <p> * A possible {@link IOException} gets logged but no further processing is * done. * </p> * * @param commandLine * the command line to execute * @param timeout * timeout for execution in milliseconds * @return response data from executed command line */ public static String executeCommandLineAndWaitResponse(String commandLine, int timeout) { String retval = null; CommandLine cmdLine = null; if (commandLine.contains(CMD_LINE_DELIMITER)) { String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER); cmdLine = new CommandLine(cmdArray[0]); for (int i = 1; i < cmdArray.length; i++) { cmdLine.addArgument(cmdArray[i], false); } } else { cmdLine = CommandLine.parse(commandLine); } DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); Executor executor = new DefaultExecutor(); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(stdout); executor.setExitValue(1); executor.setStreamHandler(streamHandler); executor.setWatchdog(watchdog); try { executor.execute(cmdLine, resultHandler); logger.debug("executed commandLine '{}'", commandLine); } catch (ExecuteException e) { logger.error("couldn't execute commandLine '" + commandLine + "'", e); } catch (IOException e) { logger.error("couldn't execute commandLine '" + commandLine + "'", e); } // some time later the result handler callback was invoked so we // can safely request the exit code try { resultHandler.waitFor(); int exitCode = resultHandler.getExitValue(); retval = StringUtils.chomp(stdout.toString()); logger.debug("exit code '{}', result '{}'", exitCode, retval); } catch (InterruptedException e) { logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e); } return retval; }
From source file:org.fuin.esmp.EventStoreStartMojo.java
private List<String> waitForHttpServer(final DefaultExecuteResultHandler resultHandler, final ByteArrayOutputStream bos) throws MojoExecutionException { // Wait for result int wait = 0; while ((wait++ < maxWaitCycles) && !resultHandler.hasResult() && !bos.toString().contains(upMessage)) { sleep(sleepMs);//w ww .j ava 2s. com } if (bos.toString().contains(upMessage)) { // Success return asList(bos.toString()); } // Failure final List<String> messages = asList(bos.toString()); logError(messages); // Exception if (resultHandler.hasResult()) { throw new MojoExecutionException("Error starting the server. Exit code=" + resultHandler.getExitValue(), resultHandler.getException()); } // Timeout throw new MojoExecutionException("Waited too long for the server to start!"); }
From source file:org.jberet.support.io.OsCommandBatchlet.java
/** * {@inheritDoc}/* w w w.j a v a2 s .c o m*/ * <p> * This method runs the OS command. * If the command completes successfully, its process exit code is returned. * If there is exception while running the OS command, which may be * caused by timeout, the command being stopped, or other errors, the process * exit code is set as the step exit status, and the exception is thrown. * * @return the OS command process exit code * * @throws Exception upon errors */ @Override public String process() throws Exception { final DefaultExecutor executor = new DefaultExecutor(); final CommandLine commandLineObj; if (commandLine != null) { commandLineObj = CommandLine.parse(commandLine); } else { if (commandArray == null) { throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, null, "commandArray"); } else if (commandArray.isEmpty()) { throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, commandArray.toString(), "commandArray"); } commandLineObj = new CommandLine(commandArray.get(0)); final int len = commandArray.size(); if (len > 1) { for (int i = 1; i < len; i++) { commandLineObj.addArgument(commandArray.get(i)); } } } if (workingDir != null) { executor.setWorkingDirectory(workingDir); } if (streamHandler != null) { executor.setStreamHandler((ExecuteStreamHandler) streamHandler.newInstance()); } SupportLogger.LOGGER.runCommand(commandLineObj.getExecutable(), Arrays.toString(commandLineObj.getArguments()), executor.getWorkingDirectory().getAbsolutePath()); if (commandOkExitValues != null) { executor.setExitValues(commandOkExitValues); } watchdog = new ExecuteWatchdog( timeoutSeconds > 0 ? timeoutSeconds * 1000 : ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); executor.execute(commandLineObj, environment, resultHandler); resultHandler.waitFor(); final ExecuteException exception = resultHandler.getException(); if (exception != null) { stepContext.setExitStatus(String.valueOf(resultHandler.getExitValue())); if (!isStopped) { throw exception; } else { SupportLogger.LOGGER.warn("", exception); } } return String.valueOf(resultHandler.getExitValue()); }