List of usage examples for org.apache.commons.exec ShutdownHookProcessDestroyer ShutdownHookProcessDestroyer
public ShutdownHookProcessDestroyer()
From source file:io.takari.maven.testing.executor.ForkedLauncher.java
public int run(String[] cliArgs, Map<String, String> envVars, File multiModuleProjectDirectory, File workingDirectory, File logFile) throws IOException, LauncherException { String javaHome;// ww w .j a v a 2s . c om if (envVars == null || envVars.get("JAVA_HOME") == null) { javaHome = System.getProperty("java.home"); } else { javaHome = envVars.get("JAVA_HOME"); } File executable = new File(javaHome, Os.isFamily(Os.FAMILY_WINDOWS) ? "bin/javaw.exe" : "bin/java"); CommandLine cli = new CommandLine(executable); cli.addArgument("-classpath").addArgument(classworldsJar.getAbsolutePath()); cli.addArgument("-Dclassworlds.conf=" + new File(mavenHome, "bin/m2.conf").getAbsolutePath()); cli.addArgument("-Dmaven.home=" + mavenHome.getAbsolutePath()); cli.addArgument("-Dmaven.multiModuleProjectDirectory=" + multiModuleProjectDirectory.getAbsolutePath()); cli.addArgument("org.codehaus.plexus.classworlds.launcher.Launcher"); cli.addArguments(args.toArray(new String[args.size()])); if (extensions != null && !extensions.isEmpty()) { cli.addArgument("-Dmaven.ext.class.path=" + toPath(extensions)); } cli.addArguments(cliArgs); Map<String, String> env = new HashMap<>(); if (mavenHome != null) { env.put("M2_HOME", mavenHome.getAbsolutePath()); } if (envVars != null) { env.putAll(envVars); } if (envVars == null || envVars.get("JAVA_HOME") == null) { env.put("JAVA_HOME", System.getProperty("java.home")); } DefaultExecutor executor = new DefaultExecutor(); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); executor.setWorkingDirectory(workingDirectory.getAbsoluteFile()); try (OutputStream log = new FileOutputStream(logFile)) { PrintStream out = new PrintStream(log); out.format("Maven Executor implementation: %s\n", getClass().getName()); out.format("Maven home: %s\n", mavenHome); out.format("Build work directory: %s\n", workingDirectory); out.format("Environment: %s\n", env); out.format("Command line: %s\n\n", cli.toString()); out.flush(); PumpStreamHandler streamHandler = new PumpStreamHandler(log); executor.setStreamHandler(streamHandler); return executor.execute(cli, env); // this throws ExecuteException if process return code != 0 } catch (ExecuteException e) { throw new LauncherException("Failed to run Maven: " + e.getMessage() + "\n" + cli, e); } }
From source file:com.thinkbiganalytics.spark.shell.MultiUserProcessManager.java
/** * Calls kinit to request a new Kerberos ticket if the previous one is about to expire. */// ww w .j a va 2 s. co m private void refreshKerberosTicket() { // Determine if a new ticket is needed if (kerberos == null || kerberos.getInitInterval() <= 0 || kerberosNextInit > DateTimeUtils.currentTimeMillis()) { return; } // Build executor final Executor executor = new DefaultExecutor(); final ShutdownHookProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer(); executor.setProcessDestroyer(processDestroyer); final Logger outputLogger = LoggerFactory.getLogger(getClass().getName() + ".kinit"); final LoggerOutputStream outputStream = new LoggerOutputStream(outputLogger); final PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); final ExecuteWatchdog watchdog = new ExecuteWatchdog(TimeUnit.SECONDS.toMillis(kerberos.getInitTimeout())); executor.setWatchdog(watchdog); // Run kinit to acquire a new ticket final CommandLine command = new CommandLine("kinit").addArgument("-kt") .addArgument(kerberos.getKeytabLocation()).addArgument(kerberos.getKerberosPrincipal()); log.debug("Acquiring a new Kerberos ticket with command: {}", command); int exitCode; try { exitCode = executor.execute(command); } catch (final IOException e) { log.error("Failed to execute kinit", e); exitCode = -1; } // Record next time to acquire ticket if (!executor.isFailure(exitCode)) { kerberosNextInit = DateTimeUtils.currentTimeMillis() + TimeUnit.SECONDS.toMillis(kerberos.getInitInterval()); } else { if (watchdog.killedProcess()) { log.error("Failed to acquire a Kerberos ticket within the allotted time: {}", kerberos.getInitTimeout()); } else { log.error("Kinit exited with non-zero status: {}", exitCode); } kerberosNextInit = DateTimeUtils.currentTimeMillis() + TimeUnit.SECONDS.toMillis(kerberos.getRetryInterval()); throw new IllegalStateException("Failed to acquire a Kerberos ticket"); } }
From source file:com.github.stephenc.mongodb.maven.StartMongoMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { if (skip) {/*w w w . j a v a 2 s. c om*/ 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.theoryinpractise.clojure.AbstractClojureCompilerMojo.java
protected void callClojureWith(ExecutionMode executionMode, File[] sourceDirectory, File outputDirectory, List<String> compileClasspathElements, String mainClass, String[] clojureArgs) throws MojoExecutionException { outputDirectory.mkdirs();//from www . j a va 2s . c om String classpath = manifestClasspath(sourceDirectory, outputDirectory, compileClasspathElements); final String javaExecutable = getJavaExecutable(); getLog().debug("Java exectuable used: " + javaExecutable); getLog().debug("Clojure manifest classpath: " + classpath); CommandLine cl = null; if (ExecutionMode.INTERACTIVE == executionMode && SystemUtils.IS_OS_WINDOWS && spawnInteractiveConsoleOnWindows) { Scanner sc = new Scanner(windowsConsole); Pattern pattern = Pattern.compile("\"[^\"]*\"|'[^']*'|[\\w'/]+"); cl = new CommandLine(sc.findInLine(pattern)); String param; while ((param = sc.findInLine(pattern)) != null) { cl.addArgument(param); } cl.addArgument(javaExecutable); } else { cl = new CommandLine(javaExecutable); } if (vmargs != null) { cl.addArguments(vmargs, false); } cl.addArgument("-Dclojure.compile.path=" + escapeFilePath(outputDirectory), false); if (warnOnReflection) cl.addArgument("-Dclojure.compile.warn-on-reflection=true"); cl.addArguments(clojureOptions, false); cl.addArgument("-jar"); File jar; if (prependClasses != null && prependClasses.size() > 0) { jar = createJar(classpath, prependClasses.get(0)); cl.addArgument(jar.getAbsolutePath(), false); List<String> allButFirst = prependClasses.subList(1, prependClasses.size()); cl.addArguments(allButFirst.toArray(new String[allButFirst.size()])); cl.addArgument(mainClass); } else { jar = createJar(classpath, mainClass); cl.addArgument(jar.getAbsolutePath(), false); } if (clojureArgs != null) { cl.addArguments(clojureArgs, false); } getLog().debug("Command line: " + cl.toString()); Executor exec = new DefaultExecutor(); Map<String, String> env = new HashMap<String, String>(System.getenv()); // env.put("path", ";"); // env.put("path", System.getProperty("java.home")); ExecuteStreamHandler handler = new PumpStreamHandler(System.out, System.err, System.in); exec.setStreamHandler(handler); exec.setWorkingDirectory(getWorkingDirectory()); ShutdownHookProcessDestroyer destroyer = new ShutdownHookProcessDestroyer(); exec.setProcessDestroyer(destroyer); int status; try { status = exec.execute(cl, env); } catch (ExecuteException e) { status = e.getExitValue(); } catch (IOException e) { status = 1; } if (status != 0) { throw new MojoExecutionException("Clojure failed."); } }
From source file:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java
/** * This calls a TIBCO binary.//from w w w .ja va 2 s .c o m * * @param binary, the TIBCO binary file to execute * @param tras, the TRA files associated with the TIBCO binary * @param arguments, command-line arguments * @param workingDir, working directory from where the binary is launched * @param errorMsg, error message to display in case of a failure * @param fork, if true the chiild process will be detached from the caller * * @throws IOException * @throws MojoExecutionException */ protected int launchTIBCOBinary(File binary, List<File> tras, ArrayList<String> arguments, File workingDir, String errorMsg, boolean fork, boolean synchronous) throws IOException, MojoExecutionException { Integer result = 0; if (tras == null) { // no value specified as Mojo parameter, we use the .tra in the same directory as the binary String traPathFileName = binary.getAbsolutePath(); traPathFileName = FilenameUtils.removeExtension(traPathFileName); traPathFileName += ".tra"; tras = new ArrayList<File>(); tras.add(new File(traPathFileName)); } HashMap<File, File> trasMap = new HashMap<File, File>(); for (File tra : tras) { // copy of ".tra" file in the working directory File tmpTRAFile = new File(directory, tra.getName()); trasMap.put(tra, tmpTRAFile); copyFile(tra, tmpTRAFile); } for (File tra : trasMap.keySet()) { if (trasMap.containsKey(tibcoDesignerTRAPath) && ((tibcoBuildEARUseDesignerTRA && tra == tibcoBuildEARTRAPath) || (tibcoBuildLibraryUseDesignerTRA && tra == tibcoBuildLibraryTRAPath))) { if (tras.size() > 1) { ReplaceRegExp replaceRegExp = new ReplaceRegExp(); replaceRegExp.setFile(trasMap.get(tra)); replaceRegExp.setMatch("tibco.include.tra (.*/designer.tra)"); replaceRegExp.setReplace( "tibco.include.tra " + trasMap.get(tibcoDesignerTRAPath).toString().replace('\\', '/')); replaceRegExp.setByLine(true); replaceRegExp.execute(); } } if (tra == tibcoBuildEARTRAPath || tra == tibcoDesignerTRAPath || tra == tibcoBWEngineTRAPath) { // FIXME: should check more properly // append user.home at the end to force the use of custom Designer5.prefs PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(trasMap.get(tra), true))); out.println(""); out.println("java.property.user.home=" + directory.getAbsolutePath().replace("\\", "/")); out.close(); } } CommandLine cmdLine = new CommandLine(binary); for (String argument : arguments) { cmdLine.addArgument(argument); } getLog().debug("launchTIBCOBinary command line : " + cmdLine.toString()); getLog().debug("working dir : " + workingDir); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(workingDir); if (timeOut > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut * 1000); executor.setWatchdog(watchdog); } executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); ByteArrayOutputStream stdOutAndErr = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(stdOutAndErr)); if (fork) { CommandLauncher commandLauncher = CommandLauncherFactory.createVMLauncher(); commandLauncher.exec(cmdLine, null, workingDir); } else { try { if (synchronous) { result = executor.execute(cmdLine); } else { executor.execute(cmdLine, new DefaultExecuteResultHandler()); } } catch (ExecuteException e) { // TODO : grer erreurs des excutables (ventuellement parser les erreurs classiques) getLog().info(cmdLine.toString()); getLog().info(stdOutAndErr.toString()); getLog().info(result.toString()); throw new MojoExecutionException(errorMsg, e); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } return result; }
From source file:org.apache.camel.component.exec.impl.DefaultExecCommandExecutor.java
protected DefaultExecutor prepareDefaultExecutor(ExecCommand execCommand) { DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(null);//from w w w . j a v a 2s. c o m if (execCommand.getWorkingDir() != null) { executor.setWorkingDirectory(new File(execCommand.getWorkingDir()).getAbsoluteFile()); } if (execCommand.getTimeout() != ExecEndpoint.NO_TIMEOUT) { executor.setWatchdog(new ExecuteWatchdog(execCommand.getTimeout())); } executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); return executor; }
From source file:org.codehaus.mojo.cassandra.CleanupCassandraMojo.java
/** * {@inheritDoc}//from ww w.ja v a2 s . c o m */ public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping cassandra: cassandra.skip==true"); return; } try { Map environment = createEnvironmentVars(); CommandLine commandLine = newNodetoolCommandLine("cleanup"); Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(cassandraDir); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); try { getLog().debug("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in)); exec.execute(commandLine, environment); getLog().info("Cleanup triggered."); } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } } catch (IOException e) { throw new MojoExecutionException(e.getLocalizedMessage(), e); } }
From source file:org.codehaus.mojo.cassandra.CompactCassandraMojo.java
/** * {@inheritDoc}/* w ww . ja v a2 s . c o m*/ */ public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping cassandra: cassandra.skip==true"); return; } try { Map environment = createEnvironmentVars(); CommandLine commandLine = newNodetoolCommandLine("compact"); Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(cassandraDir); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); try { getLog().debug("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in)); exec.execute(commandLine, environment); getLog().info("Compact triggered."); } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } } catch (IOException e) { throw new MojoExecutionException(e.getLocalizedMessage(), e); } }
From source file:org.codehaus.mojo.cassandra.FlushCassandraMojo.java
/** * {@inheritDoc}/*from w w w.j a v a2 s . com*/ */ public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping cassandra: cassandra.skip==true"); return; } try { Map environment = createEnvironmentVars(); CommandLine commandLine = newNodetoolCommandLine("flush"); Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(cassandraDir); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); try { getLog().debug("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in)); exec.execute(commandLine, environment); getLog().info("Flush triggered."); } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } } catch (IOException e) { throw new MojoExecutionException(e.getLocalizedMessage(), e); } }
From source file:org.codehaus.mojo.cassandra.RepairCassandraMojo.java
/** * {@inheritDoc}/*from w w w. j a v a 2 s. co m*/ */ public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping cassandra: cassandra.skip==true"); return; } try { Map environment = createEnvironmentVars(); CommandLine commandLine = newNodetoolCommandLine("repair"); Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(cassandraDir); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); try { getLog().debug("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in)); exec.execute(commandLine, environment); getLog().info("Repair triggered."); } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } } catch (IOException e) { throw new MojoExecutionException(e.getLocalizedMessage(), e); } }