List of usage examples for org.apache.commons.cli DefaultParser DefaultParser
DefaultParser
From source file:com.blackducksoftware.tools.notifiers.email.EmailNotifierUtility.java
static int process(String[] args) { System.out.println("Email Notifier for Black Duck Suite"); CommandLineParser parser = new DefaultParser(); options.addOption("h", "help", false, "show help."); Option protexProjectNameOption = new Option(NotifierConstants.CL_PROTEX_PROJECT_NAME, true, "Name of Project (required)"); protexProjectNameOption.setRequired(true); options.addOption(protexProjectNameOption); Option configFileOption = new Option("config", true, "Location of configuration file (required)"); configFileOption.setRequired(true);//from w ww . j a v a2s .com options.addOption(configFileOption); Option templateFileOption = new Option("template", true, "Location of email template file (optional)"); templateFileOption.setRequired(false); options.addOption(templateFileOption); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { help(); return 0; } String projectName = null; File configFile = null; String templateFileLocation = null; if (cmd.hasOption(NotifierConstants.CL_PROTEX_PROJECT_NAME)) { projectName = cmd.getOptionValue(NotifierConstants.CL_PROTEX_PROJECT_NAME); log.info("Project name: " + projectName); } else { log.error("Must specify project name!"); help(); return -1; } // Config File if (cmd.hasOption(NotifierConstants.CL_CONFIG)) { String configFilePath = cmd.getOptionValue(NotifierConstants.CL_CONFIG); log.info("Config file location: " + configFilePath); configFile = new File(configFilePath); if (!configFile.exists()) { log.error("Configuration file does not exist at location: " + configFile); return -1; } } else { log.error("Must specify configuration file!"); help(); return -1; } if (cmd.hasOption(NotifierConstants.CL_TEMPLATE_FILE)) { templateFileLocation = cmd.getOptionValue(NotifierConstants.CL_TEMPLATE_FILE); log.info("Template file location: " + templateFileLocation); } // Configuration manager EmailNotifierUtilityConfig emailConfig = new EmailNotifierUtilityConfig(configFile); // Call the processor try { CFEmailNotifier emailer = new CFEmailNotifier(emailConfig); if (!emailer.isConfigured()) { throw new NotifierException("Email Configuration not properly configured."); } // Make sure the template is parsed now // If user did not specify template file, use default resource // package. if (templateFileLocation == null) { templateFileLocation = ClassLoader .getSystemResource(NotifierConstants.PROTEX_EMAIL_SUCCESS_TEMPLATE).getFile(); } emailer.configureContentMap(templateFileLocation); IHandler notificationHandler = new EmailHandler(emailConfig, emailer); ProtexServerWrapper<ProtexProjectPojo> psw = new ProtexServerWrapper<>(emailConfig.getServerBean(), emailConfig, true); NotifierProcessor enp = new NotifierProcessor(emailConfig, psw, notificationHandler, emailer.getEmailContentMap(), projectName, projectName); enp.process(); } catch (Exception e) { log.error("Fatal error: " + e.getMessage()); } log.info("Exiting."); return 0; } catch (ParseException e) { log.error("Unable to parse command line arguments: " + e.getMessage()); help(); return -1; } }
From source file:gobblin.runtime.cli.CliOptions.java
/** * Parse command line arguments and return a {@link java.util.Properties} object for the gobblin job found. * @param caller Class of the calling main method. Used for error logs. * @param args Command line arguments./*from w ww .j av a 2 s. c o m*/ * @return Instance of {@link Properties} for the Gobblin job to run. * @throws IOException */ public static Properties parseArgs(Class<?> caller, String[] args) throws IOException { try { // Parse command-line options CommandLine cmd = new DefaultParser().parse(options(), args); if (cmd.hasOption(HELP_OPTION.getOpt())) { printUsage(caller); System.exit(0); } if (!cmd.hasOption(SYS_CONFIG_OPTION.getLongOpt()) || !cmd.hasOption(JOB_CONFIG_OPTION.getLongOpt())) { printUsage(caller); System.exit(1); } // Load system and job configuration properties Properties sysConfig = JobConfigurationUtils .fileToProperties(cmd.getOptionValue(SYS_CONFIG_OPTION.getLongOpt())); Properties jobConfig = JobConfigurationUtils .fileToProperties(cmd.getOptionValue(JOB_CONFIG_OPTION.getLongOpt())); return JobConfigurationUtils.combineSysAndJobProperties(sysConfig, jobConfig); } catch (ParseException | ConfigurationException e) { throw new IOException(e); } }
From source file:com.amertkara.multiplerunners.subcommands.parser.ParserCommand.java
/** * Initiates the sub-command/*ww w . ja v a2s. co m*/ */ @PostConstruct public void init() { options = new Options(); parser = new DefaultParser(); formatter = new HelpFormatter(); final Option fileOption = Option.builder("f").argName("file").hasArg().desc("File to be parsed").build(); options.addOption(fileOption); }
From source file:com.amertkara.multiplerunners.subcommands.analyzer.AnalyzerCommand.java
/** * Initiates the sub-command//from w w w . j a v a 2 s . co m */ @PostConstruct public void init() { options = new Options(); parser = new DefaultParser(); formatter = new HelpFormatter(); final Option fileOption = Option.builder("f").argName("file").hasArg().desc("File to be analyzed").build(); options.addOption(fileOption); }
From source file:com.emc.ecs.sync.cli.CliTest.java
@Test public void testCliConfigParsing() throws Exception { String db = "foo:bar", filters = "", rest = ""; String source = "", target = "", xml = ""; LogLevel log = LogLevel.silent;// w w w.ja va2 s . c om String[] args = { "--help", "--version", "--no-rest-server", "--rest-only", "--db-connect-string", db, "--filters", filters, "--rest-endpoint", rest, "--source", source, "--target", target, "--xml-config", xml, "--log-level", log.toString(), }; ConfigWrapper<CliConfig> wrapper = ConfigUtil.wrapperFor(CliConfig.class); CommandLine commandLine = new DefaultParser().parse(wrapper.getOptions(), args); CliConfig cliConfig = wrapper.parse(commandLine); Assert.assertTrue(cliConfig.isHelp()); Assert.assertTrue(cliConfig.isVersion()); Assert.assertFalse(cliConfig.isRestEnabled()); Assert.assertTrue(cliConfig.isRestOnly()); Assert.assertEquals(db, cliConfig.getDbConnectString()); Assert.assertEquals(filters, cliConfig.getFilters()); Assert.assertEquals(rest, cliConfig.getRestEndpoint()); Assert.assertEquals(source, cliConfig.getSource()); Assert.assertEquals(target, cliConfig.getTarget()); Assert.assertEquals(xml, cliConfig.getXmlConfig()); Assert.assertEquals(log, cliConfig.getLogLevel()); }
From source file:com.twentyn.bioreactor.sensors.Sensor.java
public static void main(String[] args) { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/* w w 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) { LOGGER.error(String.format("Argument parsing failed: %s\n", e.getMessage())); HELP_FORMATTER.printHelp(Sensor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(Sensor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } SensorType sensorType = null; try { sensorType = SensorType.valueOf(cl.getOptionValue(OPTION_TYPE)); LOGGER.debug("Sensor Type %s was choosen", sensorType); } catch (IllegalArgumentException e) { LOGGER.error("Illegal value for Sensor Type. Note: it is case-sensitive."); HELP_FORMATTER.printHelp(Sensor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } SensorData sensorData = null; switch (sensorType) { case PH: sensorData = new PHSensorData(); break; case DO: sensorData = new DOSensorData(); break; case TEMP: sensorData = new TempSensorData(); break; } Integer deviceAddress = Integer.parseInt(cl.getOptionValue(OPTION_ADDRESS)); String deviceName = cl.getOptionValue(OPTION_NAME); String sensorReadingPath = cl.getOptionValue(OPTION_READING_PATH, DEFAULT_READING_PATH); Sensor sensor = new Sensor(sensorData, deviceName); sensor.setup(deviceAddress, sensorReadingPath); sensor.run(); }
From source file:de.topobyte.utilities.apache.commons.cli.TestBasic.java
License:asdf
@Test public void test() throws ParseException { Options options = new Options(); OptionHelper.addL(options, "foo", true, true, "an option"); OptionHelper.addL(options, "bar", true, true, "another option"); String[] arguments = new String[] { "-foo", "asdf", "-bar", "test" }; CommandLine line = new DefaultParser().parse(options, arguments); StringOption foo = ArgumentHelper.getString(line, "foo"); StringOption bar = ArgumentHelper.getString(line, "bar"); assertTrue(foo.hasValue());//from www. jav a 2s . c o m assertTrue(bar.hasValue()); assertEquals("asdf", foo.getValue()); assertEquals("test", bar.getValue()); }
From source file:com.left8.evs.utilities.Console.java
public Console(String[] args, Config config) throws ParseException { this.args = args; this.config = config; setOptions();//from w w w .j av a 2s. c o m CommandLineParser parser = new DefaultParser(); cmd = parser.parse(options, this.args); }
From source file:at.salzburgresearch.vgi.vgianalyticsframework.activityanalysis.application.VgiAnalysis.java
public static void launch(Options options, String[] args) { CommandLineParser parser = new DefaultParser(); CommandLine cmd = null;//from w ww .ja va 2 s . com try (ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( "classpath:/application-context-vgi-pipeline.xml")) { cmd = parser.parse(options, args); File settingsFile = null; File polygonFile = null; boolean batchProcessing = false; if (cmd.hasOption('h')) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java -jar vgi-activity-1.0.jar [OPTION]...", options); return; } if (cmd.hasOption('s')) { settingsFile = new File(cmd.getOptionValue('s')); if (!settingsFile.exists()) { log.warn("Setting file does not exist! (" + settingsFile.getAbsolutePath() + ")"); settingsFile = null; } } else { settingsFile = null; log.warn("No setting file specified! Use option -s to specify a settings XML file"); System.exit(0); } if (cmd.hasOption('p')) { polygonFile = new File(cmd.getOptionValue('p')); if (polygonFile.exists()) { batchProcessing = true; } else { log.warn("Polygon file does not exist!"); } } else { polygonFile = null; } WKTReader wktReader = new WKTReader(); IVgiPipeline pipeline = ((IVgiPipeline) ctx.getBean("vgiPipeline")); IVgiPipelineSettings settings = ((IVgiPipelineSettings) ctx.getBean("vgiPipelineSettings")); if (!settings.loadSettings(settingsFile)) { System.exit(1); } if (batchProcessing) { if (settings.getFilterPolygonList() == null) { settings.setFilterPolygonList(new ArrayList<VgiPolygon>()); } try { BufferedReader fileReader = new BufferedReader(new FileReader(polygonFile)); String line = ""; while ((line = fileReader.readLine()) != null) { String[] split = line.split(";"); try { settings.getFilterPolygonList() .add(new VgiPolygon((Polygon) wktReader.read(split[0]), split[1])); } catch (ParseException e) { log.warn("Cannot parse geometry!! (" + split[0] + ")"); continue; } } fileReader.close(); } catch (Exception e) { e.printStackTrace(); } } if (settings.getFilterPolygonList() == null) { pipeline.start(); } else { log.info(settings.getFilterPolygonList().size() + " filter polygons found!"); for (VgiPolygon polygon : settings.getFilterPolygonList()) { settings.setCurrentPolygon(polygon); log.info("Start analysis... " + settings.getCurrentPolygon().getLabel()); pipeline.start(); } } } catch (Exception e) { HelpFormatter helpFormatter = new HelpFormatter(); if (e.getMessage() != null) { log.error(e.getMessage() + '\n'); } else { log.error("Unknown error", e); } helpFormatter.printHelp("java -jar vgi-activity-1.0.jar [OPTION]...", options); } }
From source file:gobblin.compaction.CliOptions.java
/** * Parse command line arguments and return a {@link java.util.Properties} object for the Gobblin job found. * @param caller Class of the calling main method. Used for error logs. * @param args Command line arguments./*ww w .j ava 2s . c om*/ * @param conf Hadoop configuration object * @return Instance of {@link Properties} for the Gobblin job to run. * @throws IOException */ public static Properties parseArgs(Class<?> caller, String[] args, Configuration conf) throws IOException { try { // Parse command-line options if (conf != null) { args = new GenericOptionsParser(conf, args).getCommandLine().getArgs(); } CommandLine cmd = new DefaultParser().parse(options(), args); if (cmd.hasOption(HELP_OPTION.getOpt())) { printUsage(caller); System.exit(0); } String jobConfigLocation = JOB_CONFIG_OPTION.getLongOpt(); if (!cmd.hasOption(jobConfigLocation)) { printUsage(caller); System.exit(1); } // Load job configuration properties Properties jobConfig; if (conf == null) { jobConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(jobConfigLocation)); } else { jobConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(jobConfigLocation), conf); JobConfigurationUtils.putConfigurationIntoProperties(conf, jobConfig); } return jobConfig; } catch (ParseException | ConfigurationException e) { throw new IOException(e); } }