List of usage examples for org.apache.commons.exec DefaultExecutor execute
public int execute(final CommandLine command) throws ExecuteException, IOException
From source file:com.github.badamowicz.maven.ojdeploy.plugin.executor.OjdeployExecutor.java
/** * Actually execute the ojdeploy command which has been prepared before. * // w w w . jav a2s .c o m * @throws IOException if execution of external process failed. */ private void exec() throws IOException { FileOutputStream fos = null; PumpStreamHandler pStreamHandler = null; DefaultExecutor executor = null; int exitVal = -1; LOG.info("Start executing ojdeploy now with command:"); LOG.info(getCmdLine()); fos = new FileOutputStream(new File(getProps().getProperty("ojdeploy.build.log.file"))); pStreamHandler = new PumpStreamHandler(fos); executor = new DefaultExecutor(); executor.setStreamHandler(pStreamHandler); executor.setExitValue(Integer.valueOf(getProps().getProperty("exit.value"))); exitVal = executor.execute(getCmdLine()); fos.flush(); fos.close(); LOG.info("Finished executing ojdeploy with exit value: " + exitVal); }
From source file:com.jaeksoft.searchlib.ocr.OcrManager.java
private final int run(CommandLine cmdLine, int secTimeOut, Integer expectedExitValue, StringBuilder returnedText) throws IOException, SearchLibException { DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {/*from ww w .ja v a 2s . c o m*/ Logging.info("LOG OCR: " + cmdLine); PumpStreamHandler streamHandler = new PumpStreamHandler(baos); executor.setStreamHandler(streamHandler); if (expectedExitValue != null) executor.setExitValue(expectedExitValue); ExecuteWatchdog watchdog = new ExecuteWatchdog(secTimeOut * 1000); executor.setWatchdog(watchdog); int ev = executor.execute(cmdLine); if (expectedExitValue != null) if (ev != expectedExitValue) throw new SearchLibException("Bad exit value (" + ev + ") "); if (returnedText != null) returnedText.append(baos.toString("UTF-8")); return ev; } finally { if (baos != null) IOUtils.closeQuietly(baos); } }
From source file:edu.cornell.med.icb.goby.modes.RunParallelMode.java
public void execute() throws IOException { final Slice slices[] = new Slice[numParts]; File file = new File(input); if (!(file.isFile() && file.exists() && file.canRead())) { System.err.println("Input file cannot be read: " + input); System.exit(1);/*ww w . jav a2 s.c o m*/ } int i = 0; for (final Slice slice : slices) { slices[i++] = new Slice(); } final long fileLength = file.length(); final long sliceLength = fileLength / numParts; long currentOffset = 0; for (final Slice slice : slices) { slice.startOffset = currentOffset; slice.endOffset = currentOffset + sliceLength; currentOffset = slice.endOffset; } final ObjectOpenHashSet<String> allOutputs = new ObjectOpenHashSet<String>(); final ObjectOpenHashSet<String> allFastq = new ObjectOpenHashSet<String>(); final DoInParallel loop = new DoInParallel(numParts) { IsDone done = new IsDone(); @Override public void action(final DoInParallel forDataAccess, final String inputBasename, final int loopIndex) { try { CompactToFastaMode ctfm = new CompactToFastaMode(); ctfm.setInputFilename(input); ctfm.setOutputFormat(CompactToFastaMode.OutputFormat.FASTQ); ctfm.setStartPosition(slices[loopIndex].startOffset); ctfm.setEndPosition(slices[loopIndex].endOffset); String s = FilenameUtils.getBaseName(FilenameUtils.removeExtension(input)) + "-" + Integer.toString(loopIndex); String fastqFilename = s + "-input.fq"; allFastq.add(fastqFilename); File tmp1 = new File(s + "-tmp"); tmp1.deleteOnExit(); File output = new File(s + "-out"); output.deleteOnExit(); ctfm.setOutputFilename(fastqFilename); LOG.info(String.format("Extracting FASTQ for slice [%d-%d] loopIndex=%d %n", slices[loopIndex].startOffset, slices[loopIndex].endOffset, loopIndex)); ctfm.execute(); if (loopIndex > 0) { while (!done.isDone()) { // wait a bit to give the first thread the time to load the database and establish shared memory pool // System.out.println("sleep 5 thread "+loopIndex); sleep(5); } System.out.println("Thread " + loopIndex + " can now start."); } final Map<String, String> replacements = new HashMap<String, String>(); final String outputFilename = output.getName(); replacements.put("%read.fastq%", fastqFilename); replacements.put("%tmp1%", tmp1.getName()); replacements.put("%output%", outputFilename); final String transformedCommand = transform(processPartCommand, replacements); final DefaultExecutor executor = new DefaultExecutor(); OutputStream logStream = null; try { logStream = new LoggingOutputStream(getClass(), Level.INFO, ""); executor.setStreamHandler( new PumpStreamHandler(new StreamSignal(done, "scanning", logStream))); final CommandLine parse = CommandLine.parse(transformedCommand, replacements); LOG.info("About to execute: " + parse); final int exitValue = executor.execute(parse); LOG.info("Exit value = " + exitValue); if (new File(outputFilename + ".header").exists()) { // found output alignment: System.out.println("found output file: " + outputFilename); allOutputs.add(outputFilename + ".header"); } else { System.out.println("Warning: did not find output alignment: " + outputFilename); } } finally { IOUtils.closeQuietly(logStream); // remove the fastq file new File(fastqFilename).delete(); } } catch (IOException e) { LOG.error("Error processing index " + loopIndex + ", " + inputBasename, e); } } }; String[] parts = new String[numParts]; for (int j = 0; j < numParts; j++) { parts[j] = Integer.toString(j); } try { loop.execute(true, parts); } catch (Exception e) { System.err.println("An error occurred executing a parallel command: "); e.printStackTrace(); } System.out.printf("Preparing to concatenate %d outputs..%n", allOutputs.size()); final ConcatenateAlignmentMode concat = new ConcatenateAlignmentMode(); concat.setInputFileNames(allOutputs.toArray(new String[allOutputs.size()])); concat.setOutputFilename(output); concat.setAdjustQueryIndices(false); concat.setAdjustSampleIndices(false); concat.execute(); }
From source file:io.vertx.config.vault.utils.VaultProcess.java
private void init() { String line = executable.getAbsolutePath() + " init -key-shares=1 -key-threshold=1 " + CA_CERT_ARG; System.out.println(">> " + line); CommandLine parse = CommandLine.parse(line); DefaultExecutor executor = new DefaultExecutor(); PumpStreamHandler pump = new PumpStreamHandler(new VaultOutputStream().addExtractor(l -> { if (l.contains("Unseal Key 1:")) { unseal = l.replace("Unseal Key 1: ", "").trim(); } else if (l.contains("Initial Root Token:")) { token = l.replace("Initial Root Token: ", "").trim(); }// ww w.ja v a2 s .c o m }), System.err); ExecuteWatchdog watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchDog); executor.setStreamHandler(pump); try { executor.execute(parse); } catch (IOException e) { throw new RuntimeException(e); } // await().until(() -> token != null); // await().until(() -> unseal != null); System.out.println("Vault Server initialized (but sealed)"); System.out.println("Root token: " + token); System.out.println("Unseal key: " + unseal); }
From source file:Logi.GSeries.Service.LogiGSKService.java
public String execToString(String command) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine commandline = CommandLine.parse(command); DefaultExecutor exec = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); exec.execute(commandline); return (outputStream.toString()); }
From source file:edu.stolaf.cs.wmrserver.TransformProcessor.java
private File compile(SubnodeConfiguration languageConf, String transformTypeString, File srcTransformFile, File jobTransformDir) throws CompilationException, IOException { // Determine correct compiler, returning if none specified String compiler = languageConf.getString("compiler-" + transformTypeString, ""); if (compiler.isEmpty()) compiler = languageConf.getString("compiler", ""); if (compiler.isEmpty()) return srcTransformFile; // Determine destination filename File compiledTransformFile = new File(jobTransformDir, "compiled-job-" + transformTypeString); // Create map to replace ${wmr:...} variables. // NOTE: Commons Configuration's built-in interpolator does not work here // for some reason. File jobTempDir = getJobTempDir(); Hashtable<String, String> variableMap = new Hashtable<String, String>(); File libDir = getLibraryDirectory(languageConf); variableMap.put("wmr:lib.dir", (libDir != null) ? libDir.toString() : ""); variableMap.put("wmr:src.dir", relativizeFile(srcTransformFile.getParentFile(), jobTempDir).toString()); variableMap.put("wmr:src.file", relativizeFile(srcTransformFile, jobTempDir).toString()); variableMap.put("wmr:dest.dir", relativizeFile(jobTransformDir, jobTempDir).toString()); variableMap.put("wmr:dest.file", relativizeFile(compiledTransformFile, jobTempDir).toString()); // Replace variables in compiler string compiler = StrSubstitutor.replace(compiler, variableMap); // Run the compiler CommandLine compilerCommand = CommandLine.parse(compiler); DefaultExecutor exec = new DefaultExecutor(); ExecuteWatchdog dog = new ExecuteWatchdog(60000); // 1 minute ByteArrayOutputStream output = new ByteArrayOutputStream(); PumpStreamHandler pump = new PumpStreamHandler(output); exec.setWorkingDirectory(jobTempDir); exec.setWatchdog(dog);/*from w w w . jav a 2 s . c o m*/ exec.setStreamHandler(pump); exec.setExitValues(null); // Can't get the exit code if it throws exception int exitStatus = -1; try { exitStatus = exec.execute(compilerCommand); } catch (IOException ex) { // NOTE: Exit status is still -1 in this case, since exception was thrown throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus, new String(output.toByteArray())); } // Check for successful exit if (exitStatus != 0) throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus, new String(output.toByteArray())); // Check that output exists and is readable, and make it executable if (!compiledTransformFile.isFile()) throw new CompilationException( "Compiler did not output a " + transformTypeString + " executable (or it was not a regular file).", exitStatus, new String(output.toByteArray())); if (!compiledTransformFile.canRead()) throw new IOException(StringUtils.capitalize(transformTypeString) + " executable output from compiler was not readable: " + compiledTransformFile.toString()); if (!compiledTransformFile.canExecute()) compiledTransformFile.setExecutable(true, false); return compiledTransformFile; }
From source file:modules.GeneralNativeCommandModule.java
protected KeyValueResult extractNative(String command, String options, Path path) throws NativeExecutionException { if (command == null || command.equals("")) { System.err.println("command null at GeneralNativeCommandModule.extractNative()"); return null; }/*from w w w . j av a 2 s . c o m*/ CommandLine commandLine = new CommandLine(command); if (options != null && !options.equals("")) { String[] args = options.split(" "); commandLine.addArguments(args); } if (path != null) { commandLine.addArgument(path.toAbsolutePath().toString(), false); } DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig(); executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout)); if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) { executor.setWorkingDirectory(getConfig().workingDirectory); } try { // System.out.println(commandLine); executor.execute(commandLine); } catch (ExecuteException xs) { NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } n.executionResult = outputStream.toString(); n.exitCode = xs.getExitValue(); throw n; } catch (IOException xs) { // System.out.println(commandLine); NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } n.executionResult = outputStream.toString(); throw n; } KeyValueResult t = new KeyValueResult("GeneralNativeCommandResults"); t.add("fullOutput", outputStream.toString().trim()); return t; }
From source file:modules.NativeProcessIterativeDaemonModule.java
protected String extractNative(String command, String options, Path path) throws NativeExecutionException { if (command == null || command.equals("")) { System.err.println("command null at GeneralNativeCommandModule.extractNative()"); return null; }/*w ww. java 2s . co m*/ CommandLine commandLine = new CommandLine(command); if (options != null && !options.equals("")) { String[] args = options.split(" "); commandLine.addArguments(args); } if (path != null) { commandLine.addArgument(path.toAbsolutePath().toString(), false); } DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig(); executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout)); if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) { executor.setWorkingDirectory(getConfig().workingDirectory); } try { // System.out.println("Now execute " + commandLine); executor.execute(commandLine); } catch (ExecuteException xs) { NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } n.executionResult = outputStream.toString(); n.exitCode = xs.getExitValue(); throw n; } catch (IOException xs) { NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } n.executionResult = outputStream.toString(); throw n; } return outputStream.toString().trim(); }
From source file:it.drwolf.ridire.index.cwb.CWBFrequencyList.java
private String getFrequencyList(boolean deleteFLFile, List<String> semDescription, List<String> funDescription, int quantityP, String type, Integer threshold, boolean sorted) { CommandLine commandLine = CommandLine.parse(this.cwbscanExecutable); commandLine.addArgument("-q"); if (threshold != null && threshold > 0) { commandLine.addArgument("-f"); commandLine.addArgument(threshold + ""); }/*from w w w. j a v a 2 s . c om*/ commandLine.addArgument("-r").addArgument(this.cqpRegistry); commandLine.addArgument("-C"); commandLine.addArgument(this.cqpCorpusName); if (type.equals("forma")) { commandLine.addArgument("word+0"); } else if (type.equals("PoS")) { commandLine.addArgument("pos+0"); } else if (type.equals("easypos")) { commandLine.addArgument("easypos+0"); } else if (type.equals("lemma")) { commandLine.addArgument("lemma+0"); } else if (type.equals("PoS-forma")) { commandLine.addArgument("pos+0"); commandLine.addArgument("word+0"); } else if (type.equals("PoS-lemma")) { commandLine.addArgument("pos+0"); commandLine.addArgument("lemma+0"); } String semFuncParam = ""; if (funDescription != null && funDescription.size() > 0 && funDescription.get(0) != null && funDescription.get(0).trim().length() > 0 || semDescription != null && semDescription.size() > 0 && semDescription.get(0) != null && semDescription.get(0).trim().length() > 0) { semFuncParam = "?"; if (funDescription != null && funDescription.size() > 0 && funDescription.get(0) != null && funDescription.get(0).trim().length() > 0) { String fd = StringUtils.join(funDescription, "\\|"); semFuncParam += "text_functional=/\\(" + fd + "\\)/ "; } if (semDescription != null && semDescription.size() > 0 && semDescription.get(0) != null && semDescription.get(0).trim().length() > 0) { String sd = StringUtils.join(semDescription, "\\|"); semFuncParam += "text_semantic=/\\(" + sd + "\\)/ "; } commandLine.addArgument(semFuncParam); } if (sorted) { commandLine.addArgument("|"); commandLine.addArgument("sort"); commandLine.addArgument("-nr"); commandLine.addArgument("-k"); commandLine.addArgument("1"); } if (quantityP > 0) { commandLine.addArgument("|"); commandLine.addArgument("head"); commandLine.addArgument("-" + quantityP); } File flTempFile = null; try { flTempFile = File.createTempFile("ridireFL", null); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } commandLine.addArgument(" > "); commandLine.addArgument(flTempFile.getAbsolutePath()); String c = commandLine.toString(); try { File tempSh = File.createTempFile("ridireSH", ".sh"); FileUtils.writeStringToFile(tempSh, c); tempSh.setExecutable(true); commandLine = CommandLine.parse(tempSh.getAbsolutePath()); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBFrequencyList.TIMEOUT); executor.setWatchdog(watchdog); ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024); ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream(1024); ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, baosStdErr, null); executor.setStreamHandler(executeStreamHandler); int exitValue = 0; exitValue = executor.execute(commandLine); FileUtils.deleteQuietly(tempSh); if (exitValue == 0) { StrTokenizer strTokenizer = new StrTokenizer(); this.frequencyList = new ArrayList<FrequencyItem>(); List<String> lines = FileUtils.readLines(flTempFile); for (String line : lines) { strTokenizer.reset(line); String[] tokens = strTokenizer.getTokenArray(); if (tokens.length == 2) { FrequencyItem frequencyItem = new FrequencyItem(tokens[1], Integer.parseInt(tokens[0].trim())); this.frequencyList.add(frequencyItem); } else if (tokens.length == 3) { FrequencyItem frequencyItem = new FrequencyItem(tokens[2], tokens[1], Integer.parseInt(tokens[0].trim())); this.frequencyList.add(frequencyItem); } } if (deleteFLFile) { FileUtils.deleteQuietly(flTempFile); } } } catch (ExecuteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return flTempFile.getAbsolutePath(); }
From source file:edu.kit.dama.dataworkflow.impl.LocalExecutionHandler.java
/** * Execute the user application. This method will start a new process running * the prepared user application locally. The method will return as soon as * the application has terminated. An asnychronous monitoring task my check * whether the process is still running or not via {@link #getTaskStatus(edu.kit.dama.mdm.dataworkflow.DataWorkflowTask) * } This method will check the runningIndicator file '.RUNNING', which only * exists as long as the application is running. * * @param pTask The task whose application should be executed. * * @throws DataWorkflowProcessingException If either the startup or the * processing fails for any reason, or if the user application returns an exit * code != 0./*from w ww . j a v a 2 s .c o m*/ */ @Override public void startUserApplication(DataWorkflowTask pTask) throws DataWorkflowProcessingException { //simply start the process...monitoring will be connected later File runningIndicator = getRunningIndicator(pTask); FileOutputStream fout = null; FileOutputStream ferr = null; File executablePath; try { executablePath = DataWorkflowHelper.getTaskMainExecutable(pTask); File executionBasePath = DataWorkflowHelper.getExecutionBasePath(pTask); File workingDirectory = DataWorkflowHelper.getTaskWorkingDirectory(executionBasePath); File tempDirectory = DataWorkflowHelper.getTaskTempDirectory(executionBasePath); File inputDirectory = DataWorkflowHelper.getTaskInputDirectory(executionBasePath); File outputDirectory = DataWorkflowHelper.getTaskOutputDirectory(executionBasePath); if (!executablePath.canExecute()) { LOGGER.debug("Executable at location {} seems not to be executable. Taking care of this..."); if (executablePath.setExecutable(true)) { LOGGER.debug("Executable was successfully set to be executable."); } else { LOGGER.warn("Failed to set executable to be executable. Trying to continue."); } } String cmdLineString = executablePath.getAbsolutePath() + " " + pTask.getConfiguration().getApplicationArguments() + " " + pTask.getApplicationArguments(); LOGGER.debug("Building up command array from string '{}'", cmdLineString); CommandLine cmdLine = CommandLine.parse(cmdLineString); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); Map<String, String> env = new HashMap<>(); env.put("WORKING_DIR", workingDirectory.getAbsolutePath()); env.put("TEMP_DIR", tempDirectory.getAbsolutePath()); env.put("INPUT_DIR", inputDirectory.getAbsolutePath()); env.put("OUTPUT_DIR", outputDirectory.getAbsolutePath()); fout = new FileOutputStream(new File(tempDirectory, "stdout.log")); ferr = new FileOutputStream(new File(tempDirectory, "stderr.log")); LOGGER.debug("Setting stream handler for stdout and stderr."); executor.setStreamHandler(new PumpStreamHandler(fout, ferr)); LOGGER.debug("Creating .RUNNING file for monitoring."); FileUtils.touch(runningIndicator); LOGGER.debug("Executing process."); int exitCode = executor.execute(cmdLine); if (exitCode != 0) { throw new DataWorkflowProcessingException( "Execution returned exit code " + exitCode + ". See logfiles for details."); } else { LOGGER.debug("Process successfully finished with exit code {}", exitCode); } } catch (IOException | UnsupportedOperatingSystemException e) { throw new DataWorkflowProcessingException("Failed to start executable for task " + pTask.getId(), e); } finally { LOGGER.debug("Removing running indicator file {}", runningIndicator); FileUtils.deleteQuietly(runningIndicator); if (fout != null) { try { fout.close(); } catch (IOException ex) { } } if (ferr != null) { try { ferr.close(); } catch (IOException ex) { } } } }