List of usage examples for org.apache.commons.exec CommandLine CommandLine
public CommandLine(final CommandLine other)
From source file:it.sonarlint.cli.tools.CommandExecutor.java
public int execute(String[] args, @Nullable Path workingDir, Map<String, String> addEnv) throws IOException { if (!Files.isExecutable(file)) { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(file, perms); }//from w w w . j av a2 s.c om ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); CommandLine cmd = new CommandLine(file.toFile()); cmd.addArguments(args); DefaultExecutor exec = new DefaultExecutor(); exec.setWatchdog(watchdog); exec.setStreamHandler(createStreamHandler()); exec.setExitValues(null); if (workingDir != null) { exec.setWorkingDirectory(workingDir.toFile()); } in.close(); LOG.info("Executing: {}", cmd.toString()); Map<String, String> env = new HashMap<>(System.getenv()); env.putAll(addEnv); return exec.execute(cmd, env); }
From source file:de.slackspace.wfail2ban.firewall.impl.DefaultFirewallManager.java
private void deleteFirewallRule(int ruleNumber, String filterName) { CommandLine cmdLine = new CommandLine("cmd.exe"); cmdLine.addArgument("/C"); cmdLine.addArgument(System.getenv("WINDIR") + "\\system32\\netsh.exe"); cmdLine.addArgument("advfirewall"); cmdLine.addArgument("firewall"); cmdLine.addArgument("delete"); cmdLine.addArgument("rule"); cmdLine.addArgument(createFinalRuleName(ruleNumber, filterName)); DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog);// w w w .j a va 2 s . c o m try { executor.execute(cmdLine); if (logger.isDebugEnabled()) { logger.debug("Deleted firewall rule " + createFinalRuleName(ruleNumber, filterName)); } } catch (ExecuteException e) { logger.error("Could not delete firewall rule. Error was: ", e); } catch (IOException e) { logger.error("Could not delete firewall rule. Error was: ", e); } }
From source file:com.adaptris.core.services.system.DefaultCommandBuilder.java
public CommandLine createCommandLine(AdaptrisMessage msg) { CommandLine commandLine = new CommandLine(getExecutablePath()); for (CommandArgument argument : getArguments()) { commandLine.addArgument(argument.retrieveValue(msg), quoteHandling()); }// ww w.j a v a 2 s . c o m return commandLine; }
From source file:eu.creatingfuture.propeller.blocklyprop.propeller.PropellerLoad.java
protected boolean loadIntoRam(String executable, File ramFile, String comPort) { try {/*w ww . j a va 2s .c om*/ Map map = new HashMap(); map.put("ramFile", ramFile); CommandLine cmdLine = new CommandLine(executable); cmdLine.addArgument("-r"); if (comPort != null) { cmdLine.addArgument("-p").addArgument(comPort); } cmdLine.addArgument("${ramFile}"); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); //executor.setExitValues(new int[]{451, 301}); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); try { exitValue = executor.execute(cmdLine); } catch (ExecuteException ee) { exitValue = ee.getExitValue(); logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue); success = false; return false; } finally { output = outputStream.toString(); } success = true; return true; } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); success = false; return false; } }
From source file:io.takari.maven.plugins.compile.javac.CompilerJavacLauncher.java
private void compile(File options, File output, final Map<File, Resource<File>> sources) throws IOException { new CompilerConfiguration(getSourceEncoding(), getCompilerOptions(), sources.keySet()).write(options); // use the same JVM as the one used to run Maven (the "java.home" one) String executable = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; if (File.separatorChar == '\\') { executable = executable + ".exe"; }// ww w. j a v a 2s .com CommandLine cli = new CommandLine(executable); // jvm options cli.addArguments(new String[] { "-cp", jar.getAbsolutePath() }); if (meminitial != null) { cli.addArgument("-Xms" + meminitial); } if (maxmem != null) { cli.addArgument("-Xmx" + maxmem); } // main class and program arguments cli.addArgument(CompilerJavacForked.class.getName()); cli.addArgument(options.getAbsolutePath(), false); cli.addArgument(output.getAbsolutePath(), false); DefaultExecutor executor = new DefaultExecutor(); // ExecuteWatchdog watchdog = null; // if (forkedProcessTimeoutInSeconds > 0) { // watchdog = new ExecuteWatchdog(forkedProcessTimeoutInSeconds * 1000L); // executor.setWatchdog(watchdog); // } // best effort to avoid orphaned child process executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); executor.setWorkingDirectory(basedir); log.debug("External java process command line:\n {}", cli); try { executor.execute(cli); // this throws ExecuteException if process return code != 0 } catch (ExecuteException e) { if (!log.isDebugEnabled()) { log.info("External java process command line:\n {}", cli); } throw e; } final Map<File, Output<File>> outputs = new HashMap<File, Output<File>>(); CompilerOutput.process(output, new CompilerOutputProcessor() { @Override public void processOutput(File inputFile, File outputFile) { outputs.put(outputFile, context.processOutput(outputFile)); } @Override public void addMessage(String path, int line, int column, String message, MessageSeverity kind) { if (".".equals(path)) { context.addPomMessage(message, kind, null); } else { File file = new File(path); Resource<File> resource = sources.get(file); if (resource == null) { resource = outputs.get(file); } if (resource != null) { if (isShowWarnings() || kind != MessageSeverity.WARNING) { resource.addMessage(line, column, message, kind, null); } } else { log.warn("Unexpected java resource {}", file); } } } @Override public void addLogMessage(String message) { log.warn(message); } }); }
From source file:com.sonar.scanner.api.it.tools.CommandExecutor.java
public int execute(String[] args, Map<String, String> env, @Nullable Path workingDir) throws IOException { if (!Files.isExecutable(file)) { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(file, perms); }//w w w . ja va 2s. co m watchdog = new ExecuteWatchdog(TIMEOUT); CommandLine cmd = new CommandLine(file.toFile()); cmd.addArguments(args, false); DefaultExecutor exec = new DefaultExecutor(); exec.setWatchdog(watchdog); exec.setStreamHandler(createStreamHandler()); exec.setExitValues(null); if (workingDir != null) { exec.setWorkingDirectory(workingDir.toFile()); } in.close(); LOG.info("Executing: {}", cmd.toString()); return exec.execute(cmd, env); }
From source file:com.boulmier.machinelearning.jobexecutor.job.Job.java
private CommandLine generateCommandLine(Request req) { StringBuilder argumentBuilder; this.executableName = req.getExcutableNameAsString(); this.cl = new CommandLine("cat"); for (Map.Entry<Property<String, String>, String> entry : req) { if (RequestProperty.isNull(entry.getKey())) { argumentBuilder = new StringBuilder().append(entry.getKey().getB()).append(" ") .append(entry.getValue()); this.cl.addArgument(argumentBuilder.toString()); }//from ww w.j ava 2s . c o m if (RequestProperty.ARGS == entry.getKey()) { argumentBuilder = new StringBuilder().append(entry.getValue()); this.cl.addArgument(argumentBuilder.toString()); } } return cl; }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.latex2html.PandocLatexToHtmlConverter.java
@Override public Document convert(File tex, String title) { logger.debug("Start convert() with file " + tex.toPath().toAbsolutePath().toString() + ", title: " + title); CommandLine cmdLine;/*w w w. java 2 s . co m*/ if (execPath != null) { // Run the configured pandoc executable logger.info("Pandoc will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Pandoc will be run within the PATH variable."); cmdLine = new CommandLine("pandoc"); } cmdLine.addArgument("--from=latex"); cmdLine.addArgument("--to=html5"); cmdLine.addArgument("--asciimathml"); // With this option, pandoc does not render latex formulas cmdLine.addArgument("${file}"); HashMap<String, Path> map = new HashMap<String, Path>(); map.put("file", Paths.get(tex.toURI())); cmdLine.setSubstitutionMap(map); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); // max execution time 1 minute Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter writer = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8")); ExecuteStreamHandler pandocStreamHandler = new PumpStreamHandler(writerOutputStream, System.err); executor.setStreamHandler(pandocStreamHandler); logger.debug("Launching pandoc:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("Pandoc's execution failed, exiting..."); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("Pandoc execution's exit value: " + exitValue); ExecuteException executeException = resultHandler.getException(); if (executeException != null && executeException.getCause() != null) { String exceptionKlass = executeException.getCause().getClass().getCanonicalName(); String exceptionMessage = executeException.getCause().getMessage(); if (exceptionKlass.endsWith("IOException") || exceptionMessage.contains("Cannot run program \"pandoc\"")) { logger.error("Pandoc could not be found! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("pandoc conversion thread got interrupted, exiting..."); logger.error(e.getMessage(), e); System.exit(1); } // add html document structure to output // pandoc returns no document markup (html, head, body) // therefore we have to use a template String htmlOutput = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + // set title "<title>" + title + "</title>\n" + // include css "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"></link>\n" + "</head>\n" + "<body>"; try { htmlOutput += writer.getBuffer().toString(); writer.close(); } catch (IOException e) { logger.error("Error reading html result from StringBuffer..."); logger.error(e.getMessage(), e); System.exit(1); } // Close tags in template htmlOutput += "</body>\n" + "</html>"; // output loading as JDOM Document SAXBuilder sax = new SAXBuilder(); Document document = null; try { document = sax.build(new StringReader(htmlOutput)); } catch (JDOMException e) { logger.error("JDOM Parsing error"); logger.error(e.getMessage(), e); System.exit(1); } catch (IOException e) { logger.error("Error reading from String..."); logger.error(e.getMessage(), e); System.exit(1); } return document; }
From source file:de.woq.osgi.java.itestsupport.ContainerRunner.java
public synchronized void start() throws Exception { started.set(true);//from w ww . ja va 2 s. c o m Runnable runner = new Runnable() { @Override public void run() { try { String command = getContainerCommand(); String script = findContainerDirectory() + "/bin/" + command; LOGGER.info("Using Container start command [{}] with profile [{}].", command, profile); LOGGER.info("Start script is [{}].", script); CommandLine cl = new CommandLine(script).addArguments(profile); executor.execute(cl, new ExecuteResultHandler() { @Override public void onProcessComplete(int exitValue) { latch.countDown(); } @Override public void onProcessFailed(ExecuteException e) { latch.countDown(); } }); } catch (Exception e) { e.printStackTrace(); } } }; new Thread(runner).start(); }
From source file:its.tools.CommandExecutor.java
public void execute(String[] args, @Nullable Path workingDir) throws IOException { if (!Files.isExecutable(file)) { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(file, perms); }/* w ww. ja v a 2 s. c om*/ watchdog = new ExecuteWatchdog(TIMEOUT); CommandLine cmd = new CommandLine(file.toFile()); cmd.addArguments(args); DefaultExecutor exec = new DefaultExecutor(); exec.setWatchdog(watchdog); exec.setStreamHandler(createStreamHandler()); exec.setExitValues(null); if (workingDir != null) { exec.setWorkingDirectory(workingDir.toFile()); } in.close(); LOG.info("Executing: {}", cmd.toString()); exec.execute(cmd, new ResultHander()); }