List of usage examples for org.apache.commons.exec DefaultExecutor DefaultExecutor
public DefaultExecutor()
From source file:org.jbpm.process.workitem.exec.ExecWorkItemHandler.java
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { String command = (String) workItem.getParameter("Command"); CommandLine commandLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); try {/*from ww w .j a v a 2 s . c om*/ executor.execute(commandLine); manager.completeWorkItem(workItem.getId(), null); } catch (Throwable t) { t.printStackTrace(); manager.abortWorkItem(workItem.getId()); } }
From source file:org.jcronjob.agent.AgentProcessor.java
@Override public Response execute(Request request) throws TException { if (!this.password.equalsIgnoreCase(request.getPassword())) { return errorPasswordResponse(request); }/*from w w w . j ava 2 s . c o m*/ String command = request.getParams().get("command") + EXITCODE_SCRIPT; String pid = request.getParams().get("pid"); logger.info("[cronjob]:execute:{},pid:{}", command, pid); File shellFile = CommandUtils.createShellFile(command, pid); Integer exitValue = 1; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Response response = Response.response(request); try { CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath()); DefaultExecutor executor = new DefaultExecutor(); ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream); executor.setStreamHandler(stream); response.setStartTime(new Date().getTime()); exitValue = executor.execute(commandLine); exitValue = exitValue == null ? 0 : exitValue; } catch (Exception e) { if (e instanceof ExecuteException) { exitValue = ((ExecuteException) e).getExitValue(); } else { exitValue = CronJob.StatusCode.ERROR_EXEC.getValue(); } if (exitValue == CronJob.StatusCode.KILL.getValue()) { logger.info("[cronjob]:job has be killed!at pid :{}", request.getParams().get("pid")); } else { logger.info("[cronjob]:job execute error:{}", e.getCause().getMessage()); } } finally { if (outputStream != null) { String text = outputStream.toString(); if (notEmpty(text)) { try { response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY))); response.setExitCode(Integer.parseInt( text.substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim())); } catch (IndexOutOfBoundsException e) { response.setMessage(text); response.setExitCode(exitValue); } catch (NumberFormatException e) { response.setExitCode(exitValue); } } else { response.setExitCode(exitValue); } try { outputStream.close(); } catch (Exception e) { logger.error("[cronjob]:error:{}", e); } } else { response.setExitCode(exitValue); } response.setSuccess(response.getExitCode() == CronJob.StatusCode.SUCCESS_EXIT.getValue()).end(); if (shellFile != null) { shellFile.delete();// } } logger.info("[cronjob]:execute result:{}", response.toString()); return response; }
From source file:org.jfastcgi.client.FastCGIHandler.java
public void startProcess(final String cmd) throws IOException { final DefaultExecutor pe = new DefaultExecutor(); processExecutor = pe;//from ww w . ja va 2 s . c o m pe.setWatchdog(new ExecuteWatchdog(60000)); processExecutor.setStreamHandler(new ExecuteStreamHandler() { private final Set<StreamLogger> loggers = new HashSet<StreamLogger>(); public void stop() throws IOException { } public void start() throws IOException { } public void setProcessOutputStream(final InputStream is) throws IOException { loggers.add(new StreamLogger(is, LoggerFactory.getLogger(FastCGIHandler.class.getName() + ".externalprocess.stdout"))); } public void setProcessInputStream(final OutputStream os) throws IOException { } public void setProcessErrorStream(final InputStream is) throws IOException { loggers.add(new StreamLogger(is, LoggerFactory.getLogger(FastCGIHandler.class.getName() + ".externalprocess.stderr"))); } }); getLog().info("Starting external process : " + cmd); pe.execute(CommandLine.parse(cmd), new DefaultExecuteResultHandler() { @Override public void onProcessFailed(final ExecuteException e) { super.onProcessFailed(e); getLog().error("while running process", e); } @Override public void onProcessComplete(final int exitValue) { getLog().info(String.format("external process exited with code %s : %s", exitValue, cmd)); } }); }
From source file:org.jlab.clara.std.services.DataManager.java
private void stageInputFile(FilePaths files, EngineData output) { Path stagePath = FileUtils.getParent(files.stagedInputFile); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {//from w ww . j a v a 2 s . c o m FileUtils.createDirectories(stagePath); CommandLine cmdLine = new CommandLine("cp"); cmdLine.addArgument(files.inputFile.toString()); cmdLine.addArgument(files.stagedInputFile.toString()); DefaultExecutor executor = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(cmdLine); System.out.printf("%s service: input file '%s' copied to '%s'%n", NAME, files.inputFile, stagePath); returnFilePaths(output, files); } catch (ExecuteException e) { ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim()); } catch (IOException e) { ServiceUtils.setError(output, "could not complete request: " + e.getMessage()); } }
From source file:org.jlab.clara.std.services.DataManager.java
private void removeStagedInputFile(FilePaths files, EngineData output) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {//from ww w . j a v a2 s .co m CommandLine cmdLine = new CommandLine("rm"); cmdLine.addArgument(files.stagedInputFile.toString()); DefaultExecutor executor = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(cmdLine); System.out.printf("%s service: staged input file %s removed%n", NAME, files.stagedInputFile); returnFilePaths(output, files); } catch (ExecuteException e) { ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim()); } catch (IOException e) { ServiceUtils.setError(output, "could not complete request: " + e.getMessage()); } }
From source file:org.jlab.clara.std.services.DataManager.java
private void saveOutputFile(FilePaths files, EngineData output) { Path outputPath = FileUtils.getParent(files.outputFile); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {//from w ww . j ava2s . com FileUtils.createDirectories(outputPath); CommandLine cmdLine = new CommandLine("mv"); // cmdLine.addArgument(files.stagedOutputFile.toString()); // cmdLine.addArgument(files.outputFile.toString()); // modified 09.12.18. Stage back multiple output files. vg Files.list(directoryPaths.stagePath).forEach(name -> { name.startsWith(files.stagedOutputFile.toString()); cmdLine.addArgument(name.toString()); }); cmdLine.addArgument(outputPath.toString()); // vg DefaultExecutor executor = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(cmdLine); System.out.printf("%s service: output file '%s' saved to '%s'%n", NAME, files.stagedOutputFile, outputPath); returnFilePaths(output, files); } catch (ExecuteException e) { ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim()); } catch (IOException e) { ServiceUtils.setError(output, "could not complete request: " + e.getMessage()); } }
From source file:org.kercoin.magrit.core.build.BuildTask.java
private int build(ByteArrayOutputStream stdout, PrintStream printOut) throws IOException { String command = findCommand(); printOut.println(String.format("Starting build with command '%s'", command)); CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executable = new DefaultExecutor(); executable.setWorkingDirectory(repository.getDirectory().getParentFile()); executable.setStreamHandler(new PumpStreamHandler(stdout)); return executable.execute(cmdLine); }
From source file:org.kercoin.magrit.core.build.BuildTask.java
private void gnomeNotifySend(int exitCode, boolean success) { try {/*from ww w .j a va 2 s.c o m*/ String message = ""; if (success) { message = String.format("notify-send \"Magrit\" \"Build successful\""); } else { message = String.format("notify-send \"Magrit\" \"Build failed %s\"", exitCode); } new DefaultExecutor().execute(CommandLine.parse(message)); } catch (ExecuteException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.kgi.mybatis.scala.generator.GenerateDaoMojo.java
public void execute() throws MojoExecutionException { String scaladocParamFileName = project.getBuild().getOutputDirectory() + File.separator + "myb-doclet.txt"; try {// w w w . jav a 2s. co m File f = outputDirectory; getLog().info("writing generated files to directory:" + outputDirectory.getAbsolutePath()); if (!f.exists()) { f.mkdirs(); } File sourcesDir = new File(project.getBasedir(), "src" + File.separator + "main"); getLog().info("sources located in:" + sourcesDir.getAbsolutePath()); Collection<File> sourceFiles = FileUtils.listFiles(sourcesDir, new String[] { "scala", "java" }, true); PrintWriter scaladocParamFileWriter = new PrintWriter(new FileWriter(scaladocParamFileName)); scaladocParamFileWriter.println("-d"); scaladocParamFileWriter.println("src"); scaladocParamFileWriter.println("-doc-generator"); scaladocParamFileWriter.println("org.kgi.mybatis.scala.generator.doclet.MyBatisMappingDoclet"); for (File sourceFile : sourceFiles) { scaladocParamFileWriter.println(sourceFile.getAbsolutePath()); } scaladocParamFileWriter.flush(); scaladocParamFileWriter.close(); DependencyNode depTree = dependencyGraphBuilder.buildDependencyGraph(project, new ArtifactFilter() { public boolean include(Artifact artifact) { return "jar".equals(artifact.getType()); } }); List deps = collectDependencies(depTree); Iterator depIterator = deps.iterator(); StringBuilder cpBuilder = new StringBuilder(); String docletPath = null; while (depIterator.hasNext()) { Artifact dep = (Artifact) depIterator.next(); String path = System.getProperty("user.home") + File.separator + ".m2" + File.separator + "repository" + File.separator + dep.getGroupId().replace('.', File.separatorChar) + File.separator + dep.getArtifactId() + File.separator + dep.getVersion() + File.separator + dep.getArtifactId() + "-" + dep.getVersion() + "." + dep.getType(); if (cpBuilder.length() > 0) { cpBuilder.append(File.pathSeparator); } cpBuilder.append(path); if ("mybatis-scala-gen-doclet".equals(dep.getArtifactId())) { docletPath = path; } } CommandLine cmdl = new CommandLine("scaladoc"); cmdl.addArgument("-Dmyb-gen-destination=" + outputDirectory.getAbsolutePath()); cmdl.addArgument("-Dmyb-gen-destination-package=" + destinationPackage); cmdl.addArgument("-classpath"); cmdl.addArgument(cpBuilder.toString()); cmdl.addArgument("-toolcp"); cmdl.addArgument(docletPath); cmdl.addArgument("@" + scaladocParamFileName); getLog().info("generation command:\n" + cmdl.toString()); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); executor.execute(cmdl); } catch (Exception e) { getLog().error(e); throw new MojoExecutionException("Problems generating DAO sources" + scaladocParamFileName); } }
From source file:org.kitodo.imagemanagement.ConvertRunner.java
/** * Executes the ImageMagick command using Apache Commons Exec. * * @param commandLine//from ww w . j a v a 2 s .c om * command line to execute * @throws IOException * if I/O fails */ void run(IMOperation commandLine) throws IOException { Executor executor = new DefaultExecutor(); OutputStream outAndErr = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(outAndErr)); long timeoutMillis = 1000 * KitodoConfig.getIntParameter(ParameterImageManagement.TIMEOUT_SEC, DEFAULT_TIMEOUT_MINS); executor.setWatchdog(new ExecuteWatchdog(timeoutMillis)); CommandLine command; try { String sshHosts = KitodoConfig.getParameter(ParameterImageManagement.SSH_HOST); command = new CommandLine("ssh"); String[] hosts = sshHosts.split(","); String host = hosts[RANDOMNESS_GENERATOR.nextInt(hosts.length)]; command.addArgument(host, false); command.addArgument(convertCommand + ' ' + commandLine.toString(), false); } catch (NoSuchElementException e) { logger.trace("SSH not configured.", e); command = new CommandLine(convertCommand); command.addArguments(commandLine.toString()); } try { logger.debug("Executing: {}", command); logger.trace("Timeout: {} mins", timeoutMillis / 60000d); executor.execute(command); logger.debug("Command output:{}{}", System.lineSeparator(), outAndErr.toString()); } catch (IOException | RuntimeException e) { logger.error("Command output:{}{}", System.lineSeparator(), outAndErr.toString()); throw e; } }