List of usage examples for org.apache.commons.cli ParseException getMessage
public String getMessage()
From source file:com.act.analysis.surfactant.AnalysisDriver.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*from ww w.j a v a 2 s. c o m*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } Set<String> seenOutputIds = new HashSet<>(); TSVWriter<String, String> tsvWriter = null; if (cl.hasOption(OPTION_OUTPUT_FILE)) { File outputFile = new File(cl.getOptionValue(OPTION_OUTPUT_FILE)); List<Map<String, String>> oldResults = null; if (outputFile.exists()) { System.err.format( "Output file already exists, reading old results and skipping processed molecules.\n"); TSVParser outputParser = new TSVParser(); outputParser.parse(outputFile); oldResults = outputParser.getResults(); for (Map<String, String> row : oldResults) { // TODO: verify that the last row was written cleanly/completely. seenOutputIds.add(row.get("id")); } } List<String> header = new ArrayList<>(); header.add("name"); header.add("id"); header.add("inchi"); header.add("label"); for (SurfactantAnalysis.FEATURES f : SurfactantAnalysis.FEATURES.values()) { header.add(f.toString()); } // TODO: make this API more auto-closable friendly. tsvWriter = new TSVWriter<>(header); tsvWriter.open(outputFile); if (oldResults != null) { System.out.format("Re-writing %d existing result rows\n", oldResults.size()); tsvWriter.append(oldResults); } } try { Map<SurfactantAnalysis.FEATURES, Double> analysisFeatures; LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE)); if (cl.hasOption(OPTION_INCHI)) { analysisFeatures = SurfactantAnalysis.performAnalysis(cl.getOptionValue(OPTION_INCHI), cl.hasOption(OPTION_DISPLAY)); Map<String, String> tsvFeatures = new HashMap<>(); // Convert features to strings to avoid some weird formatting issues. It's ugly, but it works. for (Map.Entry<SurfactantAnalysis.FEATURES, Double> entry : analysisFeatures.entrySet()) { tsvFeatures.put(entry.getKey().toString(), String.format("%.6f", entry.getValue())); } tsvFeatures.put("name", "direct-inchi-input"); if (tsvWriter != null) { tsvWriter.append(tsvFeatures); } } else if (cl.hasOption(OPTION_INPUT_FILE)) { TSVParser parser = new TSVParser(); parser.parse(new File(cl.getOptionValue(OPTION_INPUT_FILE))); int i = 0; List<Map<String, String>> inputRows = parser.getResults(); for (Map<String, String> row : inputRows) { i++; // Just for warning messages. if (!row.containsKey("name") || !row.containsKey("id") || !row.containsKey("inchi")) { System.err.format( "WARNING: TSV rows must contain at least name, id, and inchi, skipping row %d\n", i); continue; } if (seenOutputIds.contains(row.get("id"))) { System.out.format("Skipping input row with id already in output: %s\n", row.get("id")); continue; } System.out.format("Analysis for chemical %s\n", row.get("name")); try { analysisFeatures = SurfactantAnalysis.performAnalysis(row.get("inchi"), false); } catch (Exception e) { // Ignore exceptions for now. Sometimes the regression analysis or Chemaxon processing chokes unexpectedly. System.err.format("ERROR caught exception while processing '%s':\n", row.get("name")); System.err.format("%s\n", e.getMessage()); e.printStackTrace(System.err); System.err.println("Skipping..."); continue; } System.out.format("--- Done analysis for chemical %s\n", row.get("name")); // This is a duplicate of the OPTION_INCHI block code, but it's inside of a tight loop, so... Map<String, String> tsvFeatures = new HashMap<>(); for (Map.Entry<SurfactantAnalysis.FEATURES, Double> entry : analysisFeatures.entrySet()) { tsvFeatures.put(entry.getKey().toString(), String.format("%.6f", entry.getValue())); } tsvFeatures.put("name", row.get("name")); tsvFeatures.put("id", row.get("id")); tsvFeatures.put("inchi", row.get("inchi")); tsvFeatures.put("label", row.containsKey("label") ? row.get("label") : "?"); if (tsvWriter != null) { tsvWriter.append(tsvFeatures); // Flush every time in case we crash or get interrupted. The features must flow! tsvWriter.flush(); } } } else { throw new RuntimeException("Must specify inchi or input file"); } } finally { if (tsvWriter != null) { tsvWriter.close(); } } }
From source file:com.hurence.logisland.plugin.PluginManager.java
public static void main(String... args) throws Exception { System.out.println(BannerLoader.loadBanner()); String logislandHome = new File( new File(PluginManager.class.getProtectionDomain().getCodeSource().getLocation().getPath()) .getParent()).getParent(); System.out.println("Using Logisland home: " + logislandHome); Options options = new Options(); OptionGroup mainGroup = new OptionGroup() .addOption(OptionBuilder.withDescription( "Install a component. It can be either a logisland plugin or a kafka connect module.") .withArgName("artifact").hasArgs(1).withLongOpt("install").create("i")) .addOption(OptionBuilder.withDescription( "Removes a component. It can be either a logisland plugin or a kafka connect module.") .withArgName("artifact").hasArgs(1).withLongOpt("remove").create("r")) .addOption(OptionBuilder.withDescription("List installed components.").withLongOpt("list") .create("l")); mainGroup.setRequired(true);//from w w w. ja va2s . c o m options.addOptionGroup(mainGroup); options.addOption(OptionBuilder.withDescription("Print this help.").withLongOpt("help").create("h")); try { CommandLine commandLine = new PosixParser().parse(options, args); System.out.println(commandLine.getArgList()); if (commandLine.hasOption("l")) { listPlugins(); } else if (commandLine.hasOption("i")) { installPlugin(commandLine.getOptionValue("i"), logislandHome); } else if (commandLine.hasOption("r")) { removePlugin(commandLine.getOptionValue("r")); } else { printUsage(options); } } catch (ParseException e) { if (!options.hasOption("h")) { System.err.println(e.getMessage()); System.out.println(); } printUsage(options); } }
From source file:net.mybox.mybox.ServerAdmin.java
/** * Handle command line args/*ww w . ja va 2 s .c om*/ * @param args */ public static void main(String[] args) { Options options = new Options(); options.addOption("c", "config", true, "configuration file"); // options.addOption("d", "database", true, "accounts database file"); options.addOption("a", "apphome", true, "application home directory"); options.addOption("h", "help", false, "show help screen"); options.addOption("V", "version", false, "print the Mybox version"); CommandLineParser line = new GnuParser(); CommandLine cmd = null; try { cmd = line.parse(options, args); } catch (ParseException exp) { System.err.println(exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ServerAdmin.class.getName(), options); return; } if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Client.class.getName(), options); return; } if (cmd.hasOption("V")) { Client.printMessage("version " + Common.appVersion); return; } if (cmd.hasOption("a")) { String appHomeDir = cmd.getOptionValue("a"); try { Common.updatePaths(appHomeDir); } catch (FileNotFoundException e) { Client.printErrorExit(e.getMessage()); } Server.updatePaths(); } String configFile = Server.defaultConfigFile; // String accountsDBfile = Server.defaultAccountsDbFile; if (cmd.hasOption("c")) { configFile = cmd.getOptionValue("c"); } File fileCheck = new File(configFile); if (!fileCheck.isFile()) Server.printErrorExit("Config not found: " + configFile + "\nPlease run ServerSetup"); // if (cmd.hasOption("d")){ // accountsDBfile = cmd.getOptionValue("d"); // } // // fileCheck = new File(accountsDBfile); // if (!fileCheck.isFile()) // Server.printErrorExit("Error account database not found: " + accountsDBfile); ServerAdmin server = new ServerAdmin(configFile); }
From source file:ch.epfl.leb.sass.commandline.CommandLineInterface.java
/** * Shows help, launches the interpreter and executes scripts according to input args. * @param args input arguments/*w w w. j a v a2 s . c o m*/ */ public static void main(String args[]) { // parse input arguments CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException ex) { System.err.println("Parsing of arguments failed. Reason: " + ex.getMessage()); System.err.println("Use -help for usage."); System.exit(1); } // decide how do we make the interpreter available based on options Interpreter interpreter = null; // show help and exit if (line.hasOption("help")) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java -jar <jar-name>", options, true); System.exit(0); // launch interpreter inside current terminal } else if (line.hasOption("interpreter")) { // assign in, out and err streams to the interpreter interpreter = new Interpreter(new InputStreamReader(System.in), System.out, System.err, true); interpreter.setShowResults(true); // if a script was given, execute it before giving access to user if (line.hasOption("script")) { try { interpreter.source(line.getOptionValue("script")); } catch (IOException ex) { Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE, "IOException while executing shell script.", ex); } catch (EvalError ex) { Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE, "EvalError while executing shell script.", ex); } } // give access to user new Thread(interpreter).start(); // only execute script and exit } else if (line.hasOption("script")) { interpreter = new Interpreter(); try { interpreter.source(line.getOptionValue("script")); System.exit(0); } catch (IOException ex) { Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE, "IOException while executing shell script.", ex); System.exit(1); } catch (EvalError ex) { Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE, "EvalError while executing shell script.", ex); System.exit(1); } // Launches the RPC server with the model contained in the file whose // filename was passed by argument. } else if (line.hasOption("rpc_server")) { IJPluginModel model = new IJPluginModel(); File file = new File(line.getOptionValue("rpc_server")); try { FileInputStream stream = new FileInputStream(file); model = IJPluginModel.read(stream); } catch (FileNotFoundException ex) { System.out.println("Error: " + file.getName() + " not found."); System.exit(1); } catch (Exception ex) { ex.printStackTrace(); } // Check whether a port number was specified. if (line.hasOption("port")) { try { port = Integer.valueOf(line.getOptionValue("port")); System.out.println("Using port: " + String.valueOf(port)); } catch (java.lang.NumberFormatException ex) { System.out.println("Error: the port number argument is not a number."); System.exit(1); } } else { System.out.println("No port number provided. Using default port: " + String.valueOf(port)); } RPCServer server = new RPCServer(model, port); System.out.println("Starting RPC server..."); server.serve(); } else if (line.hasOption("port") & !line.hasOption("rpc_server")) { System.out.println("Error: Port number provided without requesting the RPC server. Exiting..."); System.exit(1); // if System.console() returns null, it means we were launched by // double-clicking the .jar, so launch own BeanShellConsole // if System.console() returns null, it means we were launched by // double-clicking the .jar, so launch own ConsoleFrame } else if (System.console() == null) { BeanShellConsole cframe = new BeanShellConsole("SASS BeanShell Prompt"); interpreter = cframe.getInterpreter(); cframe.setVisible(true); System.setOut(cframe.getInterpreter().getOut()); System.setErr(cframe.getInterpreter().getErr()); new Thread(cframe.getInterpreter()).start(); // otherwise, show help } else { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java -jar <jar-name>", options, true); System.exit(0); } if (interpreter != null) { printWelcomeText(interpreter.getOut()); } }
From source file:de.uni_koblenz.west.splendid.tools.NQuadSourceAggregator.java
public static void main(String[] args) { try {/* w ww . jav a 2 s.c o m*/ // parse the command line arguments CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(OPTIONS, args); // print help message if (cmd.hasOption("h") || cmd.hasOption("help")) { new HelpFormatter().printHelp(USAGE, OPTIONS); System.exit(0); } // get input files (from option -i or all remaining parameters) String[] inputFiles = cmd.getOptionValues("i"); if (inputFiles == null) inputFiles = cmd.getArgs(); if (inputFiles.length == 0) { System.out.println("need at least one input file."); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE); System.exit(1); } String outputFile = cmd.getOptionValue("o"); // process all input files new NQuadSourceAggregator().process(outputFile, inputFiles); } catch (ParseException exp) { // print parse error and display usage message System.out.println(exp.getMessage()); new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE, OPTIONS); } }
From source file:com.bigdata.dastor.tools.SSTableExport.java
/** * Given arguments specifying an SSTable, and optionally an output file, * export the contents of the SSTable to JSON. * //from w ww . ja v a 2 s . c o m * @param args command lines arguments * @throws IOException on failure to open/read/write files or output streams */ public static void main(String[] args) throws IOException { String usage = String.format("Usage: %s <sstable> [-k key [-k key [...]] -x key [-x key [...]]]%n", SSTableExport.class.getName()); CommandLineParser parser = new PosixParser(); try { cmd = parser.parse(options, args); } catch (ParseException e1) { System.err.println(e1.getMessage()); System.err.println(usage); System.exit(1); } if (cmd.getArgs().length != 1) { System.err.println("You must supply exactly one sstable"); System.err.println(usage); System.exit(1); } String[] keys = cmd.getOptionValues(KEY_OPTION); String[] excludes = cmd.getOptionValues(EXCLUDEKEY_OPTION); String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath(); if (cmd.hasOption(ENUMERATEKEYS_OPTION)) enumeratekeys(ssTableFileName, System.out); else { if ((keys != null) && (keys.length > 0)) export(ssTableFileName, System.out, keys, excludes); else export(ssTableFileName, excludes); } System.exit(0); }
From source file:com.controlj.experiment.bulktrend.trendclient.Main.java
public static void main(String args[]) { Options options = setupCLOptions();/* www . j a v a 2 s .c o m*/ CommandLineParser parser = new GnuParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException e) { System.err.println("Command line parsing failed: " + e.getMessage()); System.exit(-1); } if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("trendclient", options); printConfigHelp(); System.exit(0); } // dir option - read config files File baseDir = new File(""); if (line.hasOption(PARAM_DIR)) { baseDir = new File(line.getOptionValue(PARAM_DIR)); } Properties props = getProperties(baseDir); String server = getProperty(props, PROP_SERVER); String parserName = getProperty(props, PROP_PARSER); String handlerName = getProperty(props, PROP_HANDLER); String user = getProperty(props, PROP_USER); String pw = getProperty(props, PROP_PASSWORD); TrendClient tc = new TrendClient(server, getIDs(baseDir), user, pw, handlerName, parserName); String defaultDigitsString = props.getProperty(PROP_DIGITS); if (defaultDigitsString != null) { try { tc.setDefaultDigits(Integer.parseInt(defaultDigitsString)); } catch (NumberFormatException e) { System.err.println("Invalid valid for property " + PROP_DIGITS + ":" + defaultDigitsString); } } //testfile if (line.hasOption(PARAM_TESTFILE)) { String fileName = line.getOptionValue(PARAM_TESTFILE); if (fileName == null) { fileName = "response.dump"; } try { tc.setAlternateInput(new FileInputStream(new File(fileName))); System.out.println("Reading trends from file: " + fileName); } catch (FileNotFoundException e) { System.err.println("Error, " + PARAM_TESTFILE + " '" + fileName + "' not found"); } } else { System.out.println("Reading trends from " + server); System.out.println("Parser=" + parserName); System.out.println("Handler=" + handlerName); } // Start/End Date start = parseDateOption(PARAM_START, line); Date end = parseDateOption(PARAM_END, line); if (start == null) { start = TrendClient.getYesterday().getTime(); } if (end == null) { end = TrendClient.getYesterday().getTime(); } tc.setStart(start); tc.setEnd(end); System.out.println("From " + start + " to " + end); // nozip if (line.hasOption(PARAM_NOZIP)) { tc.setZip(false); } tc.go(); }
From source file:co.turnus.analysis.buffers.MpcBoundedSchedulingCliLauncher.java
public static void main(String[] args) { try {/* ww w . jav a 2s . com*/ CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(cliOptions, args); Configuration config = parseCommandLine(cmd); // init models AnalysisActivator.init(); // set logger verbosity if (config.getBoolean(VERBOSE, false)) { TurnusLogger.setLevel(TurnusLevel.ALL); } File tDir = new File(config.getString(TRACE_PROJECT)); TraceProject project = TraceProject.load(tDir); MpcBoundedScheduling mpc = new MpcBoundedScheduling(project); mpc.setConfiguration(config); BufferMinimizationData data = mpc.run(); TurnusLogger.info("Storing results..."); File outPath = new File(config.getString(OUTPUT_PATH)); // store the analysis report String uuid = UUID.randomUUID().toString(); File rFile = new File(outPath, uuid + "." + TurnusExtension.REPORT); Report report = DataFactory.eINSTANCE.createReport(); report.setDate(new Date()); report.setComment("Report with only Bounded Buffer Scheduling results analysis"); report.getDataSet().add(data); EcoreHelper.storeEObject(report, new ResourceSetImpl(), rFile); TurnusLogger.info("TURNUS report stored in " + rFile); // store formatted reports String xlsName = config.getString(XLS, ""); if (!xlsName.isEmpty()) { File xlsFile = new File(outPath, xlsName + ".xls"); new XlsBufferMinimizationDataWriter().write(data, xlsFile); TurnusLogger.info("XLS report stored in " + xlsFile); } String bxdfName = config.getString(BXDF, ""); if (!bxdfName.isEmpty()) { File bxdfFile = new File(outPath, bxdfName + ".bxdf"); new XmlBufferMinimizationDataWriter().write(data, bxdfFile); TurnusLogger.info("BXDF files (one for each configuration) " + "stored in " + outPath); } TurnusLogger.info("Analysis Done!"); } catch (ParseException e) { TurnusLogger.error(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(AlgorithmicBottlenecksCliLauncher.class.getSimpleName(), cliOptions); } catch (Exception e) { TurnusLogger.error(e.getMessage()); } }
From source file:com.cws.esolutions.security.main.UserManagementUtility.java
public static final void main(final String[] args) { final String methodName = UserManagementUtility.CNAME + "#main(final String[] args)"; if (DEBUG) {//w w w. jav a 2 s . c om DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", (Object) args); } if (args.length == 0) { HelpFormatter usage = new HelpFormatter(); usage.printHelp(UserManagementUtility.CNAME, options, true); return; } try { CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse(options, args); if (DEBUG) { DEBUGGER.debug("CommandLineParser parser: {}", parser); DEBUGGER.debug("CommandLine commandLine: {}", commandLine); DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions()); DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList()); } if ((commandLine.hasOption("configFile")) && (!(StringUtils.isBlank(commandLine.getOptionValue("configFile"))))) { SecurityServiceInitializer.initializeService(commandLine.getOptionValue("configFile"), UserManagementUtility.LOG_CONFIG, true); } else { SecurityServiceInitializer.initializeService(UserManagementUtility.SEC_CONFIG, UserManagementUtility.LOG_CONFIG, true); } AccountControlResponse response = null; final UserAccount userAccount = new UserAccount(); final RequestHostInfo reqInfo = new RequestHostInfo(); final SecurityConfigurationData secConfigData = UserManagementUtility.svcBean.getConfigData(); final SecurityConfig secConfig = secConfigData.getSecurityConfig(); try { reqInfo.setHostAddress(InetAddress.getLocalHost().getHostAddress()); reqInfo.setHostName(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException uhx) { reqInfo.setHostAddress("127.0.0.1"); reqInfo.setHostName("localhost"); } if (DEBUG) { DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData); DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig); DEBUGGER.debug("RequestHostInfo reqInfo: {}", reqInfo); } AccountControlRequest request = new AccountControlRequest(); request.setApplicationId(secConfig.getApplicationId()); request.setApplicationName(secConfig.getApplicationName()); request.setHostInfo(reqInfo); request.setRequestor(secConfig.getSvcAccount()); if (DEBUG) { DEBUGGER.debug("AccountControlRequest request: {}", request); } if (commandLine.hasOption("search")) { if (StringUtils.isEmpty(commandLine.getOptionValue("search"))) { throw new ParseException("No entry option was provided. Cannot continue."); } userAccount.setEmailAddr(commandLine.getOptionValue("search")); if (DEBUG) { DEBUGGER.debug("UserAccount userAccount: {}", userAccount); } request.setUserAccount(userAccount); if (DEBUG) { DEBUGGER.debug("AccountControlRequest: {}", request); } response = processor.searchAccounts(request); } else if (commandLine.hasOption("load")) { if (StringUtils.isEmpty(commandLine.getOptionValue("load"))) { throw new ParseException("No entry option was provided. Cannot continue."); } userAccount.setGuid(commandLine.getOptionValue("load")); request.setUserAccount(userAccount); if (DEBUG) { DEBUGGER.debug("AccountControlRequest: {}", request); } response = processor.loadUserAccount(request); } if (DEBUG) { DEBUGGER.debug("AccountControlResponse response: {}", response); } if ((response != null) && (response.getRequestStatus() == SecurityRequestStatus.SUCCESS)) { UserAccount account = response.getUserAccount(); if (DEBUG) { DEBUGGER.debug("UserAccount: {}", account); } System.out.println(account); } } catch (ParseException px) { ERROR_RECORDER.error(px.getMessage(), px); System.err.println("An error occurred during processing: " + px.getMessage()); } catch (SecurityException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); System.err.println("An error occurred during processing: " + sx.getMessage()); } catch (SecurityServiceException ssx) { ERROR_RECORDER.error(ssx.getMessage(), ssx); System.err.println("An error occurred during processing: " + ssx.getMessage()); } }
From source file:com.jbrisbin.groovy.mqdsl.RabbitMQDsl.java
public static void main(String[] argv) { // Parse command line arguments CommandLine args = null;// w w w .j ava2 s . c o m try { Parser p = new BasicParser(); args = p.parse(cliOpts, argv); } catch (ParseException e) { log.error(e.getMessage(), e); } // Check for help if (args.hasOption('?')) { printUsage(); return; } // Runtime properties Properties props = System.getProperties(); // Check for ~/.rabbitmqrc File userSettings = new File(System.getProperty("user.home"), ".rabbitmqrc"); if (userSettings.exists()) { try { props.load(new FileInputStream(userSettings)); } catch (IOException e) { log.error(e.getMessage(), e); } } // Load Groovy builder file StringBuffer script = new StringBuffer(); BufferedInputStream in = null; String filename = "<STDIN>"; if (args.hasOption("f")) { filename = args.getOptionValue("f"); try { in = new BufferedInputStream(new FileInputStream(filename)); } catch (FileNotFoundException e) { log.error(e.getMessage(), e); } } else { in = new BufferedInputStream(System.in); } // Read script if (null != in) { byte[] buff = new byte[4096]; try { for (int read = in.read(buff); read > -1;) { script.append(new String(buff, 0, read)); read = in.read(buff); } } catch (IOException e) { log.error(e.getMessage(), e); } } else { System.err.println("No script file to evaluate..."); } PrintStream stdout = System.out; PrintStream out = null; if (args.hasOption("o")) { try { out = new PrintStream(new FileOutputStream(args.getOptionValue("o")), true); System.setOut(out); } catch (FileNotFoundException e) { log.error(e.getMessage(), e); } } String[] includes = (System.getenv().containsKey("MQDSL_INCLUDE") ? System.getenv("MQDSL_INCLUDE").split(String.valueOf(File.pathSeparatorChar)) : new String[] { System.getenv("HOME") + File.separator + ".mqdsl.d" }); try { // Setup RabbitMQ String username = (args.hasOption("U") ? args.getOptionValue("U") : props.getProperty("mq.user", "guest")); String password = (args.hasOption("P") ? args.getOptionValue("P") : props.getProperty("mq.password", "guest")); String virtualHost = (args.hasOption("v") ? args.getOptionValue("v") : props.getProperty("mq.virtualhost", "/")); String host = (args.hasOption("h") ? args.getOptionValue("h") : props.getProperty("mq.host", "localhost")); int port = Integer.parseInt( args.hasOption("p") ? args.getOptionValue("p") : props.getProperty("mq.port", "5672")); CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host); connectionFactory.setPort(port); connectionFactory.setUsername(username); connectionFactory.setPassword(password); if (null != virtualHost) { connectionFactory.setVirtualHost(virtualHost); } // The DSL builder RabbitMQBuilder builder = new RabbitMQBuilder(); builder.setConnectionFactory(connectionFactory); // Our execution environment Binding binding = new Binding(args.getArgs()); binding.setVariable("mq", builder); String fileBaseName = filename.replaceAll("\\.groovy$", ""); binding.setVariable("log", LoggerFactory.getLogger(fileBaseName.substring(fileBaseName.lastIndexOf("/") + 1))); if (null != out) { binding.setVariable("out", out); } // Include helper files GroovyShell shell = new GroovyShell(binding); for (String inc : includes) { File f = new File(inc); if (f.isDirectory()) { File[] files = f.listFiles(new FilenameFilter() { @Override public boolean accept(File file, String s) { return s.endsWith(".groovy"); } }); for (File incFile : files) { run(incFile, shell, binding); } } else { run(f, shell, binding); } } run(script.toString(), shell, binding); while (builder.isActive()) { try { Thread.sleep(500); } catch (InterruptedException e) { log.error(e.getMessage(), e); } } if (null != out) { out.close(); System.setOut(stdout); } } finally { System.exit(0); } }