Example usage for org.apache.commons.cli BasicParser BasicParser

List of usage examples for org.apache.commons.cli BasicParser BasicParser

Introduction

In this page you can find the example usage for org.apache.commons.cli BasicParser BasicParser.

Prototype

BasicParser

Source Link

Usage

From source file:com.cloudera.impala.util.ImpalaJdbcClient.java

/**
 * Parses command line options//from w w  w . java 2s.  co  m
 */
private static ClientExecOptions parseOptions(String[] args) throws ParseException {
    Options options = new Options();
    options.addOption("i", true, "host:port of target machine impalad is listening on");
    options.addOption("c", true, "Full connection string to use. Overrides host/port value");
    options.addOption("t", true, "SASL/NOSASL, whether to use SASL transport or not");
    options.addOption("q", true, "Query String");
    options.addOption("help", false, "Help");

    BasicParser optionParser = new BasicParser();
    CommandLine cmdArgs = optionParser.parse(options, args);

    String transportOption = cmdArgs.getOptionValue("t");
    if (transportOption == null) {
        LOG.error("Must specify '-t' option, whether to use SASL transport or not.");
        LOG.error("Using the wrong type of transport will cause the program to hang.");
        LOG.error("Usage: " + options.toString());
        System.exit(1);
    }
    if (!transportOption.equalsIgnoreCase("SASL") && !transportOption.equalsIgnoreCase("NOSASL")) {
        LOG.error("Invalid argument " + transportOption + " to '-t' option.");
        LOG.error("Usage: " + options.toString());
        System.exit(1);
    }
    boolean useSasl = transportOption.equalsIgnoreCase("SASL");

    String connStr = cmdArgs.getOptionValue("c", null);

    // If the user didn't specify a custom connection string, build a connection
    // string using HiveServer 2 JDBC driver and no security.
    if (connStr == null) {
        String hostPort = cmdArgs.getOptionValue("i", "localhost:21050");
        connStr = "jdbc:hive2://" + hostPort + "/";
    }
    // Append appropriate auth option to connection string.
    if (useSasl) {
        connStr = connStr + SASL_AUTH_SPEC;
    } else {
        connStr = connStr + NOSASL_AUTH_SPEC;
    }

    String query = cmdArgs.getOptionValue("q");
    if (query == null) {
        LOG.error("Must specify a query to execute.");
        LOG.error("Usage: " + options.toString());
        System.exit(1);
    }

    return new ClientExecOptions(connStr, query);
}

From source file:com.boundary.sdk.event.snmp.MIBCompiler.java

/**
 * Handles all the options passed to the command line.
 * //from  w w w  .  j  ava 2 s  .  c  o  m
 * @param args Command line arguments
 */
@SuppressWarnings("static-access")
public void parseCommandLineOptions(String[] args) {

    for (String s : args) {
        LOG.debug(s);
    }

    helpOption = OptionBuilder.withDescription("Display help information").withLongOpt("help").create("h");
    licenseOption = OptionBuilder.withArgName("license").hasArgs().withValueSeparator(' ').withDescription(
            "The license key string you received with the purchase a SNMP4J-SMI license or its evaluation."
                    + "You may provide leave empty, but then you may not use any MIB modules of the \"enterprise\" OID subtree.")
            .withLongOpt("license").create("l");
    mibDirOption = OptionBuilder.withArgName("mib_path").hasArg()
            .withDescription("Path to single MIB, ZIP file of MIB(s), or a directory of MIBs to compile.")
            .withLongOpt("mib-path").create("m");
    silentOption = OptionBuilder.withDescription("Quiet mode, suppress normal output.").withLongOpt("quiet")
            .create("q");
    repoDirOption = OptionBuilder.withArgName("repository_dir").hasArg()
            .withDescription("An empty directory where the " + commandName
                    + "can read and store compiled MIB modules persistently. "
                    + "Directory must not contain any plain text (i.e., uncompiled) MIB files.")
            .withLongOpt("repository-dir").create("r");
    strictCompileOption = OptionBuilder.withArgName("lenient|standard").hasArg()
            .withDescription("Strictness defines the number of syntax checks done on the sources.")
            .withLongOpt("compiler-strict").create("s");
    updateExisting = OptionBuilder.withDescription("Update existing MIBs in repository")
            .withLongOpt("update-existing").create("u");

    options.addOption(repoDirOption);
    options.addOption(mibDirOption);
    options.addOption(licenseOption);
    options.addOption(helpOption);
    options.addOption(strictCompileOption);
    options.addOption(silentOption);

    try {
        CommandLineParser parser = new BasicParser();
        cmd = parser.parse(options, args);

        if (cmd.hasOption("h") == true && cmd.hasOption("q") == false) {
            usage();
        }
    } catch (Exception e) {
        usage();
    }
}

From source file:hws.core.JobClient.java

public void run(String[] args) throws Exception {
    //final String command = args[0];
    //final int n = Integer.valueOf(args[1]);
    //final Path jarPath = new Path(args[2]);
    Options options = new Options();
    /*options.addOption(OptionBuilder.withLongOpt("jar")
                           .withDescription( "Jar path" )
                           .hasArg()/*from   w  ww .ja va2  s .  co m*/
                           .withArgName("JarPath")
                           .create());
    options.addOption(OptionBuilder.withLongOpt("scheduler")
                           .withDescription( "Scheduler class name" )
                           .hasArg()
                           .withArgName("ClassName")
                           .create());
    */options.addOption(OptionBuilder.withLongOpt("zk-servers")
            .withDescription("List of the ZooKeeper servers").hasArgs().withArgName("zkAddrs").create("zks"));
    //options.addOption("l", "list", false, "list modules");
    options.addOption(OptionBuilder.withLongOpt("load").withDescription("load new modules").hasArgs()
            .withArgName("XMLFiles").create());
    /*options.addOption(OptionBuilder.withLongOpt( "remove" )
                           .withDescription( "remove modules" )
                           .hasArgs()
                           .withArgName("ModuleNames")
                           .create("rm"));
    */CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);

    //Path jarPath = null;
    //String schedulerClassName = null;
    String[] xmlFileNames = null;
    //String []moduleNames = null;
    String zksArgs = "";
    String[] zkServers = null;
    if (cmd.hasOption("zks")) {
        zksArgs = "-zks";
        zkServers = cmd.getOptionValues("zks");
        for (String zks : zkServers) {
            zksArgs += " " + zks;
        }
    }

    //Logger setup
    //FSDataOutputStream writer = FileSystem.get(conf).create(new Path("hdfs:///hws/apps/"+appIdStr+"/logs/jobClient.log"));
    //Logger.addOutputStream(writer);

    /*if(cmd.hasOption("l")){
       LOG.warn("Argument --list (-l) is not supported yet.");
    }
    if(cmd.hasOption("jar")){
       jarPath = new Path(cmd.getOptionValue("jar")); 
    }
    if(cmd.hasOption("scheduler")){
       schedulerClassName = cmd.getOptionValue("scheduler");
    }*/
    if (cmd.hasOption("load")) {
        xmlFileNames = cmd.getOptionValues("load");
    } /*else if(cmd.hasOption("rm")){
        moduleNames = cmd.getOptionValues("rm");
      }*/

    //LOG.info("Jar-Path "+jarPath);
    if (xmlFileNames != null) {
        String paths = "";
        for (String path : xmlFileNames) {
            paths += path + "; ";
        }
        LOG.info("Load XMLs: " + paths);
    }
    /*if(moduleNames!=null){
       String modules = "";
       for(String module: moduleNames){
          modules += module+"; ";
       }
       LOG.info("remove: "+modules);
    }*/
    // Create yarnClient
    YarnConfiguration conf = new YarnConfiguration();
    YarnClient yarnClient = YarnClient.createYarnClient();
    yarnClient.init(conf);
    yarnClient.start();

    // Create application via yarnClient
    YarnClientApplication app = yarnClient.createApplication();

    System.out.println("LOG Path: " + ApplicationConstants.LOG_DIR_EXPANSION_VAR);
    // Set up the container launch context for the application master
    ContainerLaunchContext amContainer = Records.newRecord(ContainerLaunchContext.class);

    ApplicationSubmissionContext appContext = app.getApplicationSubmissionContext();
    ApplicationId appId = appContext.getApplicationId();

    ZkClient zk = new ZkClient(zkServers[0]); //TODO select a ZooKeeper server
    if (!zk.exists("/hadoop-watershed")) {
        zk.createPersistent("/hadoop-watershed", "");
    }
    zk.createPersistent("/hadoop-watershed/" + appId.toString(), "");

    FileSystem fs = FileSystem.get(conf);

    LOG.info("Collecting files to upload");
    fs.mkdirs(new Path("hdfs:///hws/apps/" + appId.toString()));
    fs.mkdirs(new Path("hdfs:///hws/apps/" + appId.toString() + "/logs"));

    ModulePipeline modulePipeline = ModulePipeline.fromXMLFiles(xmlFileNames);
    LOG.info("Uploading files to HDFS");
    for (String path : modulePipeline.files()) {
        uploadFile(fs, new File(path), appId);
    }
    LOG.info("Upload finished");

    String modulePipelineJson = Json.dumps(modulePipeline);
    String modulePipelineBase64 = Base64.encodeBase64String(StringUtils.getBytesUtf8(modulePipelineJson))
            .replaceAll("\\s", "");
    LOG.info("ModulePipeline: " + modulePipelineJson);
    //LOG.info("ModulePipeline: "+modulePipelineBase64);
    amContainer.setCommands(Collections.singletonList("$JAVA_HOME/bin/java" + " -Xmx256M"
            + " hws.core.JobMaster" + " -aid " + appId.toString() + " --load " + modulePipelineBase64 + " "
            + zksArgs + " 1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stdout" + " 2>"
            + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stderr"));

    // Setup jar for ApplicationMaster
    //LocalResource appMasterJar = Records.newRecord(LocalResource.class);
    //setupAppMasterJar(jarPath, appMasterJar);
    //amContainer.setLocalResources(Collections.singletonMap("hws.jar", appMasterJar));

    LOG.info("Listing files for YARN-Watershed");
    RemoteIterator<LocatedFileStatus> filesIterator = fs.listFiles(new Path("hdfs:///hws/bin/"), false);
    Map<String, LocalResource> resources = new HashMap<String, LocalResource>();
    LOG.info("Files setup as resource");
    while (filesIterator.hasNext()) {
        LocatedFileStatus fileStatus = filesIterator.next();
        // Setup jar for ApplicationMaster
        LocalResource containerJar = Records.newRecord(LocalResource.class);
        ContainerUtils.setupContainerJar(fs, fileStatus.getPath(), containerJar);
        resources.put(fileStatus.getPath().getName(), containerJar);
    }
    LOG.info("container resource setup");
    amContainer.setLocalResources(resources);

    fs.close(); //closing FileSystem interface

    // Setup CLASSPATH for ApplicationMaster
    Map<String, String> appMasterEnv = new HashMap<String, String>();
    ContainerUtils.setupContainerEnv(appMasterEnv, conf);
    amContainer.setEnvironment(appMasterEnv);

    // Set up resource type requirements for ApplicationMaster
    Resource capability = Records.newRecord(Resource.class);
    capability.setMemory(256);
    capability.setVirtualCores(1);

    // Finally, set-up ApplicationSubmissionContext for the application
    //ApplicationSubmissionContext appContext = 
    //app.getApplicationSubmissionContext();
    appContext.setApplicationName("Hadoop-Watershed"); // application name
    appContext.setAMContainerSpec(amContainer);
    appContext.setResource(capability);
    appContext.setQueue("default"); // queue 

    // Submit application
    LOG.info("Submitting application " + appId);
    yarnClient.submitApplication(appContext);

    LOG.info("Waiting for containers to finish");
    zk.waitUntilExists("/hadoop-watershed/" + appId.toString() + "/done", TimeUnit.MILLISECONDS, 250);
    ApplicationReport appReport = yarnClient.getApplicationReport(appId);
    YarnApplicationState appState = appReport.getYarnApplicationState();
    while (appState != YarnApplicationState.FINISHED && appState != YarnApplicationState.KILLED
            && appState != YarnApplicationState.FAILED) {
        Thread.sleep(100);
        appReport = yarnClient.getApplicationReport(appId);
        appState = appReport.getYarnApplicationState();
    }

    System.out.println("Application " + appId + " finished with" + " state " + appState + " at "
            + appReport.getFinishTime());

    System.out.println("deleting " + appId.toString() + " znode");
    zk.deleteRecursive("/hadoop-watershed/" + appId.toString()); //TODO remove app folder from ZooKeeper
}

From source file:com.asakusafw.compiler.bootstrap.AllBatchCompilerDriver.java

private static boolean start(String[] args) throws Exception {
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(OPTIONS, args);
    String output = cmd.getOptionValue(OPT_OUTPUT.getOpt());
    String scanPath = cmd.getOptionValue(OPT_SCANPATH.getOpt());
    String packageName = cmd.getOptionValue(OPT_PACKAGE.getOpt());
    String hadoopWork = cmd.getOptionValue(OPT_HADOOPWORK.getOpt());
    String compilerWork = cmd.getOptionValue(OPT_COMPILERWORK.getOpt());
    String link = cmd.getOptionValue(OPT_LINK.getOpt());
    String plugin = cmd.getOptionValue(OPT_PLUGIN.getOpt());
    boolean skipError = cmd.hasOption(OPT_SKIPERROR.getOpt());
    String include = cmd.getOptionValue(OPT_INCLUDE.getOpt());
    String exclude = cmd.getOptionValue(OPT_EXCLUDE.getOpt());

    File outputDirectory = new File(output);
    Location hadoopWorkLocation = Location.fromPath(hadoopWork, '/');
    File compilerWorkDirectory = new File(compilerWork);
    List<File> linkingResources = extractEmbedResources(link);
    List<URL> pluginLocations = extractPluginPath(plugin);
    ClassNamePattern includePattern = ClassNamePattern.parse(include, true);
    ClassNamePattern excludePattern = ClassNamePattern.parse(exclude, false);
    Set<String> errorBatches = new HashSet<>();
    boolean succeeded = true;
    try {/*from   w  w w .j  a  va  2 s  .  c  o m*/
        ResourceRepository scanner = getScanner(new File(scanPath));
        try (Cursor cursor = scanner.createCursor()) {
            while (cursor.next()) {
                Location location = cursor.getLocation();
                Class<? extends BatchDescription> batchDescription = getBatchDescription(location,
                        includePattern, excludePattern);
                if (batchDescription == null) {
                    continue;
                }
                boolean singleSucceeded = BatchCompilerDriver.compile(outputDirectory, batchDescription,
                        packageName, hadoopWorkLocation, compilerWorkDirectory, linkingResources,
                        pluginLocations);
                succeeded &= singleSucceeded;
                if (singleSucceeded == false) {
                    errorBatches.add(toClassName(location));
                    if (skipError == false) {
                        break;
                    }
                }
            }
        }
    } catch (Exception e) {
        LOG.error(MessageFormat.format(
                Messages.getString("AllBatchCompilerDriver.errorFailedToSearchForBatchClass"), //$NON-NLS-1$
                scanPath), e);
    }
    if (succeeded) {
        LOG.info(Messages.getString("AllBatchCompilerDriver.infoCompleteBatchClass")); //$NON-NLS-1$
    } else {
        LOG.error(MessageFormat.format(
                Messages.getString("AllBatchCompilerDriver.errorFailedToCompileBatchClass"), //$NON-NLS-1$
                errorBatches));
    }

    return succeeded;
}

From source file:io.github.agentsoz.abmjadex.super_central.ABMSimStarter.java

private static void parsingArguments(String[] args, Options options) {
    //flags/*w ww  .j  a v  a 2 s.c o  m*/
    boolean isRunningCO = true;
    boolean isForced = false; //Overwrite any existing CO xml file
    boolean isRunningSC = true;
    boolean isLogToConsole = false;
    Level logLevel = Level.INFO;

    Properties prop = null;
    CommandLine line = null;
    BasicParser parser = new BasicParser();
    ArrayList<String> argsList = new ArrayList<String>();

    //Initialize argsList with args
    for (int i = 0; i < args.length; i++) {
        argsList.add(args[i]);
    }

    //Update 04/17/2013
    String[] specificArgs = packageOptionSpecific(args);

    try {
        // parse the command line arguments
        //line = parser.parse(options, args );
        //Update 04/17/2013
        line = parser.parse(options, specificArgs);

        //Commandline required -prop argument to be filled with valid properties file location
        if (line.hasOption(HELP)) {
            //Remove app specific arguments from total arguments
            int helpIndex = argsList.indexOf("-" + HELP);
            if (helpIndex == -1)
                helpIndex = argsList.indexOf("-" + HELP_LONG);
            argsList.remove(helpIndex);

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Jadex-ABMS", options);
        }

        if (line.hasOption(PROP)) {
            //Remove app specific arguments from total arguments
            int propIndex = argsList.indexOf("-" + PROP);
            if (propIndex == -1)
                propIndex = argsList.indexOf("-" + PROP_LONG);
            argsList.remove(propIndex + 1);
            argsList.remove(propIndex);

            String propertiesLoc = line.getOptionValue(PROP).replace("\\", "/").replace("\\\\", "/");
            prop = new Properties();

            try {
                prop.load(new FileInputStream(propertiesLoc));
                //Parsing options value into local flags------------------------
                if (line.hasOption(MODE)) {
                    String mode = line.getOptionValue(MODE);
                    if (mode.equalsIgnoreCase(CO_ONLY)) {
                        isRunningSC = false;
                    } else if (mode.equalsIgnoreCase(SC_CO)) {
                        //Default value is to run an SC and a CO
                    } else if (mode.equalsIgnoreCase(SC_ONLY)) {
                        isRunningCO = false;
                    } else {
                        throw new ParseException("Wrong argument for -mode.");
                    }

                    //Remove app specific arguments from total arguments
                    int modeIndex = argsList.indexOf("-" + MODE);
                    argsList.remove(modeIndex + 1);
                    argsList.remove(modeIndex);
                }

                if (line.hasOption(FORCED)) {
                    isForced = true;
                    //Remove app specific arguments from total arguments
                    int modeIndex = argsList.indexOf("-" + FORCED);
                    if (modeIndex == -1)
                        modeIndex = argsList.indexOf("-" + FORCED_LONG);
                    argsList.remove(modeIndex);
                }

                if (line.hasOption(GUI)) {
                    String guiMode = line.getOptionValue(GUI);
                    if (!guiMode.equalsIgnoreCase("true") && !guiMode.equalsIgnoreCase("false"))
                        throw new ParseException("Wrong argument for -gui.");
                } else {
                    argsList.add("-" + GUI);
                    int guiIndex = argsList.indexOf("-" + GUI);
                    argsList.add(guiIndex + 1, "false");
                }

                if (line.hasOption(LOG_CONSOLE)) {
                    isLogToConsole = true;
                    //Remove app specific arguments from total arguments
                    int logCIndex = argsList.indexOf("-" + LOG_CONSOLE);
                    argsList.remove(logCIndex);
                }

                if (line.hasOption(LOG_LVL)) {
                    String level = line.getOptionValue(LOG_LVL);
                    if (level.equalsIgnoreCase("INFO")) {
                        logLevel = Level.INFO;
                    } else if (level.equalsIgnoreCase("ALL")) {
                        logLevel = Level.ALL;
                    } else if (level.equalsIgnoreCase("CONFIG")) {
                        logLevel = Level.CONFIG;
                    } else if (level.equalsIgnoreCase("FINE")) {
                        logLevel = Level.FINE;
                    } else if (level.equalsIgnoreCase("FINER")) {
                        logLevel = Level.FINER;
                    } else if (level.equalsIgnoreCase("FINEST")) {
                        logLevel = Level.FINEST;
                    } else if (level.equalsIgnoreCase("OFF")) {
                        logLevel = Level.OFF;
                    } else if (level.equalsIgnoreCase("SEVERE")) {
                        logLevel = Level.SEVERE;
                    } else if (level.equalsIgnoreCase("WARNING")) {
                        logLevel = Level.WARNING;
                    } else {
                        throw new ParseException("argument for loglvl unknown");
                    }
                    //Remove app specific arguments from total arguments
                    int logLvlIndex = argsList.indexOf("-" + LOG_LVL);
                    argsList.remove(logLvlIndex + 1);
                    argsList.remove(logLvlIndex);
                }

                //Setup logger
                try {
                    ABMBDILoggerSetter.initialized(prop, isLogToConsole, logLevel);
                    ABMBDILoggerSetter.setup(LOGGER);
                } catch (IOException e) {
                    e.printStackTrace();
                    LOGGER.severe(e.getMessage());
                    throw new RuntimeException("Problems with creating logfile");
                }

                //Translate argsList into array------------------------------
                String[] newargs = new String[argsList.size()];
                for (int i = 0; i < argsList.size(); i++) {
                    newargs[i] = argsList.get(i);
                }

                //Running the system----------------------------------------
                if (isRunningSC == true) {
                    runSC(prop);
                }

                if (isRunningCO == true) {
                    runCO(prop, newargs, isForced);
                }

            } catch (IOException e) {
                e.printStackTrace();
                LOGGER.severe(e.getMessage());
            }
        } else {
            throw new ParseException("-prop <properties_location> is a required option");
        }

    } catch (ParseException exp) {
        LOGGER.severe("Unexpected exception:" + exp.getMessage());

        //If its not working print out help info
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jadex-ABMS", options);
    }
}

From source file:com.beaconhill.yqd.CmdLine.java

CommandLine parseCmdLine(Options options, String[] args) {
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;/*  w  w w.  j av a 2  s.c  o  m*/
    try {
        cmd = parser.parse(options, args);
    } catch (MissingOptionException missingEx) {
        Log.error(missingEx.getMessage());
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return cmd;
}

From source file:com.dancorder.Archiverify.Parameters.java

private CommandLine getCommandLine(String[] args, Options options) throws ParseException {
    return new BasicParser().parse(options, args);
}

From source file:com.asakusafw.dmdl.thundergate.Main.java

/**
 * ??/*from  www. jav  a 2  s  .com*/
 * @param args ?
 * @return ??
 * @throws IllegalStateException ????
 */
public static Configuration loadConfigurationFromArguments(String[] args) {
    assert args != null;
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(OPTIONS, args);
    } catch (ParseException e) {
        throw new IllegalStateException(e);
    }

    Configuration result = new Configuration();

    String jdbc = getOption(cmd, OPT_JDBC_CONFIG, true);
    try {
        Properties jdbcProps = loadProperties(jdbc);
        result.setJdbcDriver(findProperty(jdbcProps, Constants.K_JDBC_DRIVER));
        result.setJdbcUrl(findProperty(jdbcProps, Constants.K_JDBC_URL));
        result.setJdbcUser(findProperty(jdbcProps, Constants.K_JDBC_USER));
        result.setJdbcPassword(findProperty(jdbcProps, Constants.K_JDBC_PASSWORD));
        result.setDatabaseName(findProperty(jdbcProps, Constants.K_DATABASE_NAME));
        LOG.info("JDBC??????: {}", jdbcProps);
    } catch (IOException e) {
        throw new IllegalStateException(
                MessageFormat.format("JDBC?????????: -{0}={1}",
                        OPT_JDBC_CONFIG.getOpt(), jdbc),
                e);
    }

    String output = getOption(cmd, OPT_OUTPUT, true);
    result.setOutput(new File(output));
    LOG.info("Output: {}", output);

    String includes = getOption(cmd, OPT_INCLUDES, false);
    if (includes != null && includes.isEmpty() == false) {
        try {
            Pattern pattern = Pattern.compile(includes, Pattern.CASE_INSENSITIVE);
            result.setMatcher(new ModelMatcher.Regex(pattern));
            LOG.info("Inclusion: {}", pattern);
        } catch (PatternSyntaxException e) {
            throw new IllegalArgumentException(MessageFormat
                    .format("??????????: {0}", includes), e);
        }
    } else {
        result.setMatcher(ModelMatcher.ALL);
    }

    String excludes = getOption(cmd, OPT_EXCLUDES, false);
    if (excludes != null && excludes.isEmpty() == false) {
        try {
            Pattern pattern = Pattern.compile(excludes, Pattern.CASE_INSENSITIVE);
            result.setMatcher(new ModelMatcher.And(result.getMatcher(),
                    new ModelMatcher.Not(new ModelMatcher.ConstantTable(Constants.SYSTEM_TABLE_NAMES)),
                    new ModelMatcher.Not(new ModelMatcher.Regex(pattern))));
            LOG.info("Exclusion: {}", pattern);
        } catch (PatternSyntaxException e) {
            throw new IllegalArgumentException(MessageFormat
                    .format("??????????: {0}", excludes), e);
        }
    } else {
        result.setMatcher(new ModelMatcher.And(result.getMatcher(),
                new ModelMatcher.Not(new ModelMatcher.ConstantTable(Constants.SYSTEM_TABLE_NAMES))));
    }

    String encoding = getOption(cmd, OPT_ENCODING, false);
    if (encoding != null) {
        try {
            Charset charset = Charset.forName(encoding);
            result.setEncoding(charset);
            LOG.info("Encoding: {}", charset);
        } catch (Exception e) {
            result.setEncoding(Constants.OUTPUT_ENCODING);
        }
    } else {
        result.setEncoding(Constants.OUTPUT_ENCODING);
    }

    checkIf(cmd, OPT_SID_COLUMN, OPT_TIMESTAMP_COLUMN);
    checkIf(cmd, OPT_TIMESTAMP_COLUMN, OPT_SID_COLUMN);

    checkIf(cmd, OPT_SID_COLUMN, OPT_DELETE_FLAG_COLUMN);
    checkIf(cmd, OPT_SID_COLUMN, OPT_DELETE_FLAG_VALUE);
    checkIf(cmd, OPT_DELETE_FLAG_COLUMN, OPT_DELETE_FLAG_VALUE);
    checkIf(cmd, OPT_DELETE_FLAG_VALUE, OPT_DELETE_FLAG_COLUMN);

    String sidColumn = trim(getOption(cmd, OPT_SID_COLUMN, false));
    String timestampColumn = trim(getOption(cmd, OPT_TIMESTAMP_COLUMN, false));
    String deleteFlagColumn = trim(getOption(cmd, OPT_DELETE_FLAG_COLUMN, false));
    String deleteFlagValue = trim(getOption(cmd, OPT_DELETE_FLAG_VALUE, false));
    if (deleteFlagValue != null) {
        // FIXME get "bare" string
        List<String> arguments = Arrays.asList(args);
        int index = arguments.indexOf('-' + OPT_DELETE_FLAG_VALUE.getOpt());
        assert index >= 0;
        assert arguments.size() > index + 1;
        deleteFlagValue = trim(arguments.get(index + 1));
    }

    result.setSidColumn(sidColumn);
    result.setTimestampColumn(timestampColumn);
    result.setDeleteFlagColumn(deleteFlagColumn);
    if (deleteFlagValue != null) {
        try {
            DmdlParser dmdl = new DmdlParser();
            AstLiteral literal = dmdl.parseLiteral(deleteFlagValue);
            result.setDeleteFlagValue(literal);
        } catch (DmdlSyntaxException e) {
            throw new IllegalArgumentException(MessageFormat.format(
                    "???Java???????????: {0}",
                    deleteFlagValue), e);
        }
    }
    String recordLockDdlOutput = getOption(cmd, OPT_RECORD_LOCK_DDL_OUTPUT, false);
    if (recordLockDdlOutput != null) {
        result.setRecordLockDdlOutput(new File(recordLockDdlOutput));
    }
    return result;
}

From source file:dk.hippogrif.prettyxml.app.Main.java

static CommandLine parse(String[] args) {
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;/*  w w  w .  ja  v  a  2s .  c o m*/
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException pe) {
        logger.log(Level.FINE, "parse", pe);
    }
    return cmd;
}

From source file:com.boundary.sdk.snmp.metric.ExportMibCli.java

private void parseCommandLineOptions(String[] args) throws Exception {

    buildOptions();//from w  w w . j  ava  2  s. c  o  m

    CommandLineParser parser = new BasicParser();
    cmd = parser.parse(options, args);

    // If the help argument is present then display usage
    if (cmd.hasOption("?") == true) {
        usage();
    }

    mibExporter.setVerbose(cmd.hasOption("v"));

    // Extract the module names passed on the command line
    getModules();
    setOutputDirectory();
    // Set the SNMP4J compiler license if provided, required for
    // MIBs using the enterprise branch
    getCompilerLicense();

    String exportOption = cmd.getOptionValue("e");
    exportType = ExportType.valueOf(exportOption);
    if (exportType != null) {
        mibExporter.setExportType(exportType);
    }
}