List of usage examples for org.apache.commons.exec CommandLine parse
public static CommandLine parse(final String line)
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 + ""); }// ww w.j a v a2 s . c o m 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.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 www . j a va 2 s . com 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:it.drwolf.ridire.session.async.Mapper.java
private StringWithEncoding createPlainTextResource(File f, CrawledResource cr, EntityManager entityManager) throws SAXException, TikaException, IOException, TransformerConfigurationException, InterruptedException {/*from w w w .j a va2 s.com*/ File resourceDir = new File(FilenameUtils.getFullPath(f.getCanonicalPath().replaceAll("__\\d+", "")) + JobMapperMonitor.RESOURCESDIR); String alchemyKey = entityManager.find(Parameter.class, Parameter.ALCHEMY_KEY.getKey()).getValue(); String readabilityKey = entityManager.find(Parameter.class, Parameter.READABILITY_KEY.getKey()).getValue(); String resourceFileName = cr.getDigest() + ".gz"; File resourceFile = new File(resourceDir, resourceFileName); StringWithEncoding rawContentAndEncoding = null; String contentType = cr.getContentType(); // long t1 = System.currentTimeMillis(); if (contentType != null && contentType.contains("application/msword")) { rawContentAndEncoding = this.transformDOC2HTML(resourceFile, entityManager); } if (contentType != null && contentType.contains("application/rtf")) { rawContentAndEncoding = this.transformRTF2HTML(resourceFile, entityManager); } if (contentType != null && contentType.contains("text/plain")) { // txt -> html -> txt is for txt cleaning rawContentAndEncoding = this.transformTXT2HTML(resourceFile, entityManager); } if (contentType != null && contentType.contains("pdf")) { rawContentAndEncoding = this.transformPDF2HTML(resourceFile, entityManager); } if (contentType != null && contentType.contains("html")) { rawContentAndEncoding = this.getGuessedEncodingAndSetRawContentFromGZFile(resourceFile); } // long t2 = System.currentTimeMillis(); // System.out.println("Transformation: " + (t2 - t1)); if (rawContentAndEncoding != null) { if (rawContentAndEncoding.getEncoding() == null) { rawContentAndEncoding = new StringWithEncoding(rawContentAndEncoding.getString(), "UTF8"); } // t1 = System.currentTimeMillis(); String cleanText = this.replaceUnsupportedChars(rawContentAndEncoding.getString()); rawContentAndEncoding = new StringWithEncoding(cleanText, rawContentAndEncoding.getEncoding()); File tmpFile = File.createTempFile("ridire", null); FileUtils.writeStringToFile(tmpFile, rawContentAndEncoding.getString(), "UTF-8"); String ridireCleanerJar = entityManager .find(CommandParameter.class, CommandParameter.RIDIRE_CLEANER_EXECUTABLE_KEY).getCommandValue(); String host = entityManager.find(Parameter.class, Parameter.READABILITY_HOSTAPP.getKey()).getValue(); CommandLine commandLine = CommandLine .parse("java -Xmx128m -Djava.io.tmpdir=" + this.tempDir + " -jar " + ridireCleanerJar); commandLine.addArgument("-f"); commandLine.addArgument(tmpFile.getPath()); commandLine.addArgument("-e"); commandLine.addArgument("UTF-8"); commandLine.addArgument("-h"); commandLine.addArgument(host); commandLine.addArgument("-k"); commandLine.addArgument(alchemyKey); commandLine.addArgument("-r"); commandLine.addArgument(readabilityKey); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.READABILITY_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 = executor.execute(commandLine); if (exitValue == 0) { rawContentAndEncoding = new StringWithEncoding(baosStdOut.toString(), "UTF-8"); // TODO filter real errors rawContentAndEncoding.setCleaner(baosStdErr.toString().trim()); } FileUtils.deleteQuietly(tmpFile); } return rawContentAndEncoding; }
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);/*from ww w . j a va 2 s.c o m*/ return (outputStream.toString()); }
From source file:info.pancancer.arch3.containerProvisioner.ContainerProvisionerThreads.java
/** * run the reaper//from w w w . j a va2 s . com * * @param settings * @param ipAddress * specify an ip address (otherwise cleanup only failed deployments) * @throws JsonIOException * @throws IOException */ private static void runReaper(HierarchicalINIConfiguration settings, String ipAddress, String vmName) throws IOException { String param = settings.getString(Constants.PROVISION_YOUXIA_REAPER); CommandLine parse = CommandLine.parse("dummy " + (param == null ? "" : param)); List<String> arguments = new ArrayList<>(); arguments.addAll(Arrays.asList(parse.getArguments())); arguments.add("--kill-list"); // create a json file with the one targetted ip address Gson gson = new Gson(); // we can't use the full set of database records because unlike Amazon, OpenStack reuses private ip addresses (very quickly too) // String[] successfulVMAddresses = db.getSuccessfulVMAddresses(); String[] successfulVMAddresses = new String[] {}; if (ipAddress != null) { successfulVMAddresses = new String[] { ipAddress, vmName }; } LOG.info("Kill list contains: " + Arrays.asList(successfulVMAddresses)); Path createTempFile = Files.createTempFile("target", "json"); try (BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(createTempFile.toFile()), StandardCharsets.UTF_8))) { gson.toJson(successfulVMAddresses, bw); } arguments.add(createTempFile.toAbsolutePath().toString()); String[] toArray = arguments.toArray(new String[arguments.size()]); LOG.info("Running youxia reaper with following parameters:" + Arrays.toString(toArray)); // need to make sure reaper and deployer do not overlap try { Reaper.main(toArray); } catch (Exception e) { LOG.error("Youxia reaper threw the following exception", e); } }
From source file:com.virtualparadigm.packman.processor.JPackageManagerBU.java
public static boolean autorun(File autorunDir) { logger.info("PackageManager::autorun()"); boolean status = true; if (autorunDir != null && autorunDir.isDirectory()) { File[] autorunFiles = autorunDir.listFiles(); Arrays.sort(autorunFiles); String fileExtension = null; DefaultExecutor cmdExecutor = new DefaultExecutor(); for (File autorunFile : autorunFiles) { if (!autorunFile.isDirectory()) { try { fileExtension = FilenameUtils.getExtension(autorunFile.getAbsolutePath()); if (fileExtension != null) { if (fileExtension.equalsIgnoreCase("bat") || fileExtension.equalsIgnoreCase("sh")) { logger.info(" executing autorun file: " + autorunFile.getAbsolutePath()); cmdExecutor.execute(CommandLine.parse(autorunFile.getAbsolutePath())); } else if (fileExtension.equalsIgnoreCase("sql") || fileExtension.equalsIgnoreCase("ddl")) { logger.info(" executing autorun file: " + autorunFile.getAbsolutePath()); } else if (fileExtension.equalsIgnoreCase("jar")) { logger.info(" executing autorun file: " + autorunFile.getAbsolutePath()); }//from ww w. jav a 2s . c o m } } catch (Exception e) { logger.error("", e); e.printStackTrace(); } } } } return status; }
From source file:com.virtualparadigm.packman.processor.JPackageManager.java
public static boolean autorun(File autorunDir, Map<String, String> environmentVariableMap) { logger.info("PackageManager::autorun()"); boolean status = true; if (autorunDir != null && autorunDir.isDirectory()) { File[] autorunFiles = autorunDir.listFiles(); Arrays.sort(autorunFiles); String fileExtension = null; DefaultExecutor cmdExecutor = new DefaultExecutor(); // String sqlScriptFilePath = null; // Reader sqlScriptReader = null; // Properties sqlScriptProperties = null; for (File autorunFile : autorunFiles) { if (!autorunFile.isDirectory()) { try { fileExtension = FilenameUtils.getExtension(autorunFile.getAbsolutePath()); if (fileExtension != null) { if (fileExtension.equalsIgnoreCase("bat")) { logger.info(" executing autorun batch script: " + autorunFile.getAbsolutePath()); logger.info(" executing autorun environment: " + EnvironmentUtils.toStrings(environmentVariableMap)); cmdExecutor.execute(CommandLine.parse(autorunFile.getAbsolutePath()), environmentVariableMap); } else if (fileExtension.equalsIgnoreCase("sh")) { Set<PosixFilePermission> permissionSet = new HashSet<PosixFilePermission>(); permissionSet.add(PosixFilePermission.OWNER_READ); permissionSet.add(PosixFilePermission.OWNER_WRITE); permissionSet.add(PosixFilePermission.OWNER_EXECUTE); permissionSet.add(PosixFilePermission.OTHERS_READ); permissionSet.add(PosixFilePermission.OTHERS_WRITE); permissionSet.add(PosixFilePermission.OTHERS_EXECUTE); permissionSet.add(PosixFilePermission.GROUP_READ); permissionSet.add(PosixFilePermission.GROUP_WRITE); permissionSet.add(PosixFilePermission.GROUP_EXECUTE); Files.setPosixFilePermissions(Paths.get(autorunFile.toURI()), permissionSet); logger.info(" executing autorun shell script: " + autorunFile.getAbsolutePath()); logger.info(" executing autorun environment: " + EnvironmentUtils.toStrings(environmentVariableMap)); cmdExecutor.execute(CommandLine.parse(autorunFile.getAbsolutePath()), environmentVariableMap); } else if (fileExtension.equalsIgnoreCase("sql") || fileExtension.equalsIgnoreCase("ddl")) { logger.info(" executing autorun file: " + autorunFile.getAbsolutePath()); // look for properties file named same as script file for connection properties // sqlScriptFilePath = autorunFile.getAbsolutePath(); // sqlScriptProperties = PropertyLoader.loadProperties(sqlScriptFilePath.substring(0, sqlScriptFilePath.length()-3) + "properties"); // sqlScriptReader = new FileReader(autorunFile.getAbsolutePath()); } else if (fileExtension.equalsIgnoreCase("jar")) { logger.info(" executing autorun file: " + autorunFile.getAbsolutePath()); }// ww w . j av a 2s . c o m } } catch (Exception e) { logger.error("", e); e.printStackTrace(); } } } } return status; }
From source file:com.datastax.driver.core.CCMBridge.java
private String execute(String command, Object... args) { String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir; Closer closer = Closer.create();/*from w ww. ja va 2 s . c o m*/ // 10 minutes timeout ExecuteWatchdog watchDog = new ExecuteWatchdog(TimeUnit.MINUTES.toMillis(10)); StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); closer.register(pw); try { logger.trace("Executing: " + fullCommand); CommandLine cli = CommandLine.parse(fullCommand); Executor executor = new DefaultExecutor(); LogOutputStream outStream = new LogOutputStream() { @Override protected void processLine(String line, int logLevel) { String out = "ccmout> " + line; logger.debug(out); pw.println(out); } }; LogOutputStream errStream = new LogOutputStream() { @Override protected void processLine(String line, int logLevel) { String err = "ccmerr> " + line; logger.error(err); pw.println(err); } }; closer.register(outStream); closer.register(errStream); ExecuteStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream); executor.setStreamHandler(streamHandler); executor.setWatchdog(watchDog); int retValue = executor.execute(cli, ENVIRONMENT_MAP); if (retValue != 0) { logger.error("Non-zero exit code ({}) returned from executing ccm command: {}", retValue, fullCommand); pw.flush(); throw new CCMException( String.format("Non-zero exit code (%s) returned from executing ccm command: %s", retValue, fullCommand), sw.toString()); } } catch (IOException e) { if (watchDog.killedProcess()) logger.error("The command {} was killed after 10 minutes", fullCommand); pw.flush(); throw new CCMException(String.format("The command %s failed to execute", fullCommand), sw.toString(), e); } finally { try { closer.close(); } catch (IOException e) { Throwables.propagate(e); } } return sw.toString(); }
From source file:com.sds.acube.ndisc.mts.xserver.XNDiscServer.java
/** * Console clear //from ww w .ja v a2 s .c o m */ private static void clearConsoleOutput() { try { String os = System.getProperty("os.name").toLowerCase(); String ostype = (os.contains("windows")) ? "W" : "U"; if (ostype.equals("W")) { CommandLine cmdLine = CommandLine.parse("cls"); DefaultExecutor executor = new DefaultExecutor(); executor.execute(cmdLine); System.out.printf("%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n", new Object[0]); } else { CommandLine cmdLine = CommandLine.parse("clear"); DefaultExecutor executor = new DefaultExecutor(); executor.execute(cmdLine); System.out.print(CLEAR_TERMINAL_ANSI_CMD); System.out.flush(); } } catch (IOException e) { } }
From source file:com.virtualparadigm.packman.processor.JPackageManagerOld.java
public static boolean autorun(File autorunDir) { logger.info("PackageManager::autorun()"); boolean status = true; if (autorunDir != null && autorunDir.isDirectory()) { File[] autorunFiles = autorunDir.listFiles(); Arrays.sort(autorunFiles); String fileExtension = null; DefaultExecutor cmdExecutor = new DefaultExecutor(); // String sqlScriptFilePath = null; // Reader sqlScriptReader = null; // Properties sqlScriptProperties = null; for (File autorunFile : autorunFiles) { if (!autorunFile.isDirectory()) { try { fileExtension = FilenameUtils.getExtension(autorunFile.getAbsolutePath()); if (fileExtension != null) { if (fileExtension.equalsIgnoreCase("bat") || fileExtension.equalsIgnoreCase("sh")) { logger.info(" executing autorun file: " + autorunFile.getAbsolutePath()); cmdExecutor.execute(CommandLine.parse(autorunFile.getAbsolutePath())); } else if (fileExtension.equalsIgnoreCase("sql") || fileExtension.equalsIgnoreCase("ddl")) { logger.info(" executing autorun file: " + autorunFile.getAbsolutePath()); // look for properties file named same as script file for connection properties // sqlScriptFilePath = autorunFile.getAbsolutePath(); // sqlScriptProperties = PropertyLoader.loadProperties(sqlScriptFilePath.substring(0, sqlScriptFilePath.length()-3) + "properties"); // sqlScriptReader = new FileReader(autorunFile.getAbsolutePath()); } else if (fileExtension.equalsIgnoreCase("jar")) { logger.info(" executing autorun file: " + autorunFile.getAbsolutePath()); }/* w w w . j a va 2 s. c om*/ } } catch (Exception e) { logger.error("", e); e.printStackTrace(); } } } } return status; }