List of usage examples for org.apache.commons.exec Executor setExitValue
void setExitValue(final int value);
From source file:com.base.exec.TutorialTest.java
/** * Simulate printing a PDF document.//from w w w .j av a 2s.c o m * * @param file * the file to print * @param printJobTimeout * the printJobTimeout (ms) before the watchdog terminates the * print process * @param printInBackground * printing done in the background or blocking * @return a print result handler (implementing a future) * @throws IOException * the test failed */ public PrintResultHandler print(final File file, final long printJobTimeout, final boolean printInBackground) throws IOException { int exitValue; ExecuteWatchdog watchdog = null; PrintResultHandler resultHandler; // build up the command line to using a 'java.io.File' final Map<String, File> map = new HashMap<String, File>(); map.put("file", file); final CommandLine commandLine = new CommandLine(acroRd32Script); // commandLine.addArgument("/p"); // commandLine.addArgument("/h"); // commandLine.addArgument("${file}"); // commandLine.setSubstitutionMap(map); // // create the executor and consider the exitValue '1' as success final Executor executor = new DefaultExecutor(); executor.setExitValue(0); // create a watchdog if requested if (printJobTimeout > 0) { watchdog = new ExecuteWatchdog(printJobTimeout); executor.setWatchdog(watchdog); } // pass a "ExecuteResultHandler" when doing background printing if (printInBackground) { System.out.println("[print] Executing non-blocking print job ..."); resultHandler = new PrintResultHandler(watchdog); executor.execute(commandLine, resultHandler); } else { System.out.println("[print] Executing blocking print job ..."); exitValue = executor.execute(commandLine); resultHandler = new PrintResultHandler(exitValue); } return resultHandler; }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.CalibreHtmlToMobiConverter.java
@Override public File convertToMobi(File htmlFile) { logger.debug("Enter convertToMobi()..."); if (htmlFile == null) { logger.error("Document is null, aborting..."); System.exit(1);//from w ww. ja v a 2s .c o m } CommandLine cmdLine; if (execPath != null) { // Run the configured calibre ebook-convert executable logger.info("Calibre ebook-convert will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Calibre ebook-convert will be run within the PATH variable."); cmdLine = new CommandLine(command); } // cli command: ebook-convert input_file.html output_file.mobi --mobi-file-type=new // Run configuration cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString()); String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString(); Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename); logger.debug("Mobi output file: " + tempMobiFilepath.toAbsolutePath().toString()); cmdLine.addArgument(tempMobiFilepath.toAbsolutePath().toString()); // Output will be in format "KF8" only, old format does not allow external CSS files cmdLine.addArgument("--mobi-file-type=new"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter writer = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8")); ExecuteStreamHandler calibreStreamHandler = new PumpStreamHandler(writerOutputStream, System.err); executor.setStreamHandler(calibreStreamHandler); logger.debug("Launching calibres ebook-convert:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("calibres ebook-convert failed to execute:"); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("calibre ebook-converts 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 \"ebook-convert\"")) { logger.error("calibres ebook-convert could not be run! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("calibre ebook-converts execution got interrupted: "); logger.error(e.getMessage(), e); } String output = ""; try { output += writer.getBuffer().toString(); writer.close(); } catch (IOException e) { logger.error("Error reading calibre ebook-converts output from buffer:"); logger.error(e.getMessage(), e); } logger.debug("Calibre ebook-convert output: \n" + output); return tempMobiFilepath.toFile(); }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.AmazonHtmlToMobiConverter.java
@Override public File convertToMobi(File htmlFile) { logger.debug("Enter convertToMobi()..."); if (htmlFile == null) { logger.error("Document is null, aborting..."); System.exit(1);// w ww . j a v a 2 s . c o m } CommandLine cmdLine; if (execPath != null) { // Run the configured kindlegen executable logger.info("Kindlegen will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Kindlegen will be run within the PATH variable."); cmdLine = new CommandLine(command); } // Run configuration cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString()); cmdLine.addArgument("-c0"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter stdoutWriter = new StringWriter(); StringWriter stderrWriter = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(stdoutWriter, Charset.forName("UTF-8")); WriterOutputStream writerErrorStream = new WriterOutputStream(stderrWriter, Charset.forName("UTF-8")); ExecuteStreamHandler kindlegenStreamHandler = new PumpStreamHandler(writerOutputStream, writerErrorStream); executor.setStreamHandler(kindlegenStreamHandler); logger.debug("Launching kindlegen:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("Kindlegen failed to execute:"); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("Kindlegen 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 \"kindlegen\"")) { logger.error("Kindlegen could not be run! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("Kindlegen's execution got interrupted: "); logger.error(e.getMessage(), e); } try { String stderrOutput = stderrWriter.getBuffer().toString(); stderrWriter.close(); if (stderrOutput.isEmpty() == false) { logger.error("Kindlegen logged some errors:"); logger.error(stderrOutput); } } catch (IOException e) { logger.error("Error closing kindlegen's stderr buffer"); logger.error(e.getMessage(), e); } String output = ""; try { output += stdoutWriter.getBuffer().toString(); stdoutWriter.close(); } catch (IOException e) { logger.error("Error closing kindlegen's stdout buffer:"); logger.error(e.getMessage(), e); } logger.debug("Kindlegen output: \n" + output); String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString(); logger.debug("Moving Kindlegen output file: " + mobiFilename); Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename); return tempMobiFilepath.toFile(); }
From source file:de.yaio.services.webshot.server.controller.WebshotProvider.java
protected WebShotResultHandler runCommand(final String command, final String[] params, final long jobTimeout) throws IOException { int exitValue; boolean inBackground = false; ExecuteWatchdog watchdog = null;/*from w w w .j ava2s. com*/ WebShotResultHandler resultHandler; // build up the command line to using a 'java.io.File' final CommandLine commandLine = new CommandLine(command); commandLine.addArguments(params); if (LOGGER.isDebugEnabled()) { LOGGER.debug("start command " + command + " with params" + new ReflectionToStringBuilder(params, ToStringStyle.SHORT_PREFIX_STYLE).toString()); } // create the executor and consider the exitValue '1' as success final Executor executor = new DefaultExecutor(); executor.setExitValue(0); // create a watchdog if requested if (jobTimeout > 0) { watchdog = new ExecuteWatchdog(jobTimeout); executor.setWatchdog(watchdog); } if (inBackground) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[WebShot] Executing non-blocking WebShot job ..."); } resultHandler = new WebShotResultHandler(watchdog); executor.execute(commandLine, resultHandler); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[WebShot] Executing blocking WebShot job ..."); } exitValue = executor.execute(commandLine); resultHandler = new WebShotResultHandler(exitValue); } return resultHandler; }
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;//from w ww. j ava2 s .c om 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:ch.ivyteam.ivy.maven.engine.EngineControl.java
/** * Run a short living engine command where we expect a process failure as the engine invokes <code>System.exit(-1)</code>. * @param statusCmd // w w w. j a v a 2s .c o m * @return the output of the engine command. */ private String executeSynch(CommandLine statusCmd) { String engineOutput = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, System.err); Executor executor = createEngineExecutor(); executor.setStreamHandler(streamHandler); executor.setExitValue(-1); try { executor.execute(statusCmd); } catch (IOException ex) { // expected! } finally { engineOutput = outputStream.toString(); IOUtils.closeQuietly(outputStream); } return engineOutput; }
From source file:com.adaptris.core.services.system.DefaultCommandBuilder.java
public Executor configure(Executor exe) { if (!isEmpty(getWorkingDirectory())) { File wd = new File(getWorkingDirectory()); exe.setWorkingDirectory(wd);//from w w w . ja v a2s .co m } exe.setExitValue(successExitValue()); return exe; }
From source file:gr.upatras.ece.nam.baker.impl.InstalledBunLifecycleMgmt.java
public int executeSystemCommand(String cmdStr) { logger.info(" ================> Execute :" + cmdStr); CommandLine cmdLine = CommandLine.parse(cmdStr); final Executor executor = new DefaultExecutor(); // create the executor and consider the exitValue '0' as success executor.setExitValue(0); ByteArrayOutputStream out = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(out); executor.setStreamHandler(streamHandler); int exitValue = -1; try {// w ww.j a va 2 s . c o m exitValue = executor.execute(cmdLine); logger.info(" ================> EXIT (" + exitValue + ") FROM :" + cmdStr); } catch (ExecuteException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } logger.info("out>" + out); return exitValue; }
From source file:it.drwolf.ridire.index.cwb.CWBCollocatesExtractor.java
private File tabulate() throws IOException { EnvironmentUtils.addVariableToEnvironment(EnvironmentUtils.getProcEnvironment(), "LC_ALL=C"); File tmpAwk = File.createTempFile("ridireAWK", ".awk"); String awk = this.createAWKString(); FileUtils.writeStringToFile(tmpAwk, awk); File tmpTabulate = File.createTempFile("ridireTAB", ".tab"); String tabulate = this.createTabulateString(tmpAwk, tmpTabulate); File tempSh = File.createTempFile("ridireSH", ".sh"); FileUtils.writeStringToFile(tempSh, tabulate); tempSh.setExecutable(true);// w ww .ja va2 s .c o m Executor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBCollocatesExtractor.CWB_COLLOCATES_EXTRACTOR_TIMEOUT); executor.setWatchdog(watchdog); CommandLine commandLine = new CommandLine(this.cqpExecutable); commandLine.addArgument("-f").addArgument(tempSh.getAbsolutePath()).addArgument("-D") .addArgument(this.cqpCorpusName).addArgument("-r").addArgument(this.cqpRegistry); executor.execute(commandLine); FileUtils.deleteQuietly(tmpAwk); FileUtils.deleteQuietly(tempSh); return tmpTabulate; }
From source file:it.drwolf.ridire.index.cwb.CWBPatternSearcher.java
private Integer getCQPQueryResultsSize(File queryFile, String cqpSizeQuery) throws ExecuteException, IOException { EnvironmentUtils.addVariableToEnvironment(EnvironmentUtils.getProcEnvironment(), "LC_ALL=C"); Executor executor = new DefaultExecutor(); File tempSize = File.createTempFile("ridireSZ", ".size"); File tempSh = File.createTempFile("ridireSH", ".sh"); CommandLine commandLine = new CommandLine(this.cqpExecutable); commandLine.addArgument("-f").addArgument(queryFile.getAbsolutePath()).addArgument("-D") .addArgument(this.cqpCorpusName).addArgument("-r").addArgument(this.cqpRegistry); String commLineString = commandLine.toString() + " > " + tempSize.getAbsolutePath(); FileUtils.writeStringToFile(tempSh, commLineString); tempSh.setExecutable(true);/*from ww w. j a va2 s . co m*/ executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBPatternSearcher.TIMEOUT); executor.setWatchdog(watchdog); commandLine = new CommandLine(tempSh.getAbsolutePath()); executor.execute(commandLine); Integer size = 0; List<String> lines = FileUtils.readLines(tempSize); if (lines.size() > 0) { size = Integer.parseInt(lines.get(0).trim()); } FileUtils.deleteQuietly(tempSh); FileUtils.deleteQuietly(tempSize); return size; }