Example usage for org.apache.commons.cli Option getValue

List of usage examples for org.apache.commons.cli Option getValue

Introduction

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

Prototype

public String getValue() 

Source Link

Document

Returns the specified value of this Option or null if there is no value.

Usage

From source file:org.apache.commons.jci.examples.commandline.CommandlineCompiler.java

public static void main(String[] args) throws Exception {

    final Options options = new Options();

    options.addOption(OptionBuilder.withArgName("a.jar:b.jar").hasArg().withValueSeparator(':')
            .withDescription("Specify where to find user class files").create("classpath"));

    options.addOption(OptionBuilder.withArgName("release").hasArg()
            .withDescription("Provide source compatibility with specified release").create("source"));

    options.addOption(OptionBuilder.withArgName("release").hasArg()
            .withDescription("Generate class files for specific VM version").create("target"));

    options.addOption(OptionBuilder.withArgName("path").hasArg()
            .withDescription("Specify where to find input source files").create("sourcepath"));

    options.addOption(OptionBuilder.withArgName("directory").hasArg()
            .withDescription("Specify where to place generated class files").create("d"));

    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("Stop compilation after these number of errors").create("Xmaxerrs"));

    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("Stop compilation after these number of warning").create("Xmaxwarns"));

    options.addOption(OptionBuilder.withDescription("Generate no warnings").create("nowarn"));

    //        final HelpFormatter formatter = new HelpFormatter();
    //        formatter.printHelp("jci", options);

    final CommandLineParser parser = new GnuParser();
    final CommandLine cmd = parser.parse(options, args, true);

    ClassLoader classloader = CommandlineCompiler.class.getClassLoader();
    File sourcepath = new File(".");
    File targetpath = new File(".");
    int maxerrs = 10;
    int maxwarns = 10;
    final boolean nowarn = cmd.hasOption("nowarn");

    final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
    final JavaCompilerSettings settings = compiler.createDefaultSettings();

    for (Iterator it = cmd.iterator(); it.hasNext();) {
        final Option option = (Option) it.next();
        if ("classpath".equals(option.getOpt())) {
            final String[] values = option.getValues();
            final URL[] urls = new URL[values.length];
            for (int i = 0; i < urls.length; i++) {
                urls[i] = new File(values[i]).toURL();
            }//  w  w  w . jav a 2  s. co m
            classloader = new URLClassLoader(urls);
        } else if ("source".equals(option.getOpt())) {
            settings.setSourceVersion(option.getValue());
        } else if ("target".equals(option.getOpt())) {
            settings.setTargetVersion(option.getValue());
        } else if ("sourcepath".equals(option.getOpt())) {
            sourcepath = new File(option.getValue());
        } else if ("d".equals(option.getOpt())) {
            targetpath = new File(option.getValue());
        } else if ("Xmaxerrs".equals(option.getOpt())) {
            maxerrs = Integer.parseInt(option.getValue());
        } else if ("Xmaxwarns".equals(option.getOpt())) {
            maxwarns = Integer.parseInt(option.getValue());
        }
    }

    final ResourceReader reader = new FileResourceReader(sourcepath);
    final ResourceStore store = new FileResourceStore(targetpath);

    final int maxErrors = maxerrs;
    final int maxWarnings = maxwarns;
    compiler.setCompilationProblemHandler(new CompilationProblemHandler() {
        int errors = 0;
        int warnings = 0;

        public boolean handle(final CompilationProblem pProblem) {

            if (pProblem.isError()) {
                System.err.println(pProblem);

                errors++;

                if (errors >= maxErrors) {
                    return false;
                }
            } else {
                if (!nowarn) {
                    System.err.println(pProblem);
                }

                warnings++;

                if (warnings >= maxWarnings) {
                    return false;
                }
            }

            return true;
        }
    });

    final String[] resource = cmd.getArgs();

    for (int i = 0; i < resource.length; i++) {
        System.out.println("compiling " + resource[i]);
    }

    final CompilationResult result = compiler.compile(resource, reader, store, classloader);

    System.out.println(result.getErrors().length + " errors");
    System.out.println(result.getWarnings().length + " warnings");

}

From source file:org.apache.flex.compiler.clients.ASC.java

/**
 * Apache Common CLI did the lexer work. This function does the parser work
 * to construct an {@code ASC} job from the command-line options.
 * //from   ww  w  . j  a v  a 2s .  com
 * @param line - the tokenized command-line
 * @return a new ASC client for the given command-line configuration; null
 * if no arguments were given.
 */
private Boolean createClient(final CommandLine line) throws ParseException {
    // First, process parsed command line options.
    final Option[] options = line.getOptions();

    if (options == null)
        return false;

    for (int i = 0; i < options.length; i++) {
        final Option option = options[i];
        final String shortName = option.getOpt();

        if ("import".equals(shortName)) {
            String[] imports = option.getValues();
            for (int j = 0; j < imports.length; j++) {
                this.addImportFilename(imports[j]);
            }
        } else if ("in".equals(shortName)) {
            String[] includes = option.getValues();
            for (int j = 0; j < includes.length; j++) {
                this.addIncludeFilename(includes[j]);
            }
        } else if ("swf".equals(shortName)) {
            String[] swfValues = option.getValue().split(",");
            if (swfValues.length < 3)
                throw new MissingArgumentException(
                        "The swf option requires three arguments, only " + swfValues.length + " were found.");

            for (int j = 0; j < swfValues.length; j++) {
                String value = swfValues[j];
                if (j == 0)
                    this.setSymbolClass(value);
                else if (j == 1)
                    this.setWidth(value);
                else if (j == 2)
                    this.setHeight(value);
                else if (j == 3)
                    this.setFrameRate(value);
            }
        } else if ("use".equals(shortName)) {
            String[] namespaces = option.getValues();
            for (String namespace : namespaces) {
                this.addNamespace(namespace);
            }
        } else if ("config".equals(shortName)) {
            String[] config = option.getValues();
            if (config.length == 2) {
                // The config option will have been split around '='
                // e.g. CONFIG::Foo='hi' will be split into
                // 2 values - 'CONFIG::Foo' and 'hi'
                String name = config[0];
                String value = config[1];
                value = fixupMissingQuote(value);
                this.putConfigVar(name, value);
            }
        } else if ("strict".equals(shortName) || "!".equals(shortName)) {
            this.setUseStaticSemantics(true);
        } else if ("d".equals(shortName)) {
            this.setEmitDebugInfo(true);
        } else if ("warnings".equals(shortName) || "coach".equals(shortName)) {
            if ("coach".equals(shortName))
                err.println("'coach' has been deprecated. Please use 'warnings' instead.");
            this.setShowWarnings(true);
        } else if ("log".equals(shortName)) {
            this.setShowLog(true);
        } else if ("md".equals(shortName)) {
            this.setEmitMetadata(true);
        } else if ("merge".equals(shortName)) {
            this.setMergeABCs(true);
        } else if ("language".equals(shortName)) {
            String value = option.getValue();
            this.setLocale(getLocaleForLanguage(value));
        } else if ("doc".equals(shortName)) {
            this.setEmitDocInfo(true);
        } else if ("avmtarget".equals(shortName)) {
            String value = option.getValue();
            this.setTargetAVM(value);
        } else if ("AS3".equals(shortName)) {
            this.setDialect("AS3");
        } else if ("ES".equals(shortName)) {
            this.setDialect("ES");
        } else if ("o".equalsIgnoreCase(shortName) || "optimize".equalsIgnoreCase(shortName)) {
            this.setOptimize(true);
        } else if ("o2".equalsIgnoreCase(shortName)) {
            this.setOptimize(true);
        } else if ("out".equalsIgnoreCase(shortName)) {
            this.setOutputBasename(option.getValue());
        } else if ("outdir".equalsIgnoreCase(shortName)) {
            this.setOutputDirectory(option.getValue());
        } else if ("abcfuture".equals(shortName)) {
            this.setABCFuture(true);
        } else if ("p".equals(shortName)) {
            this.setShowParseTrees(true);
        } else if ("i".equals(shortName)) {
            this.setShowInstructions(true);
        } else if ("m".equals(shortName)) {
            this.setShowMachineCode(true);
        } else if ("f".equals(shortName)) {
            this.setShowFlowGraph(true);
        } else if ("exe".equals(shortName)) {
            String exe = option.getValue();
            this.setAvmplusFilename(exe);
        } else if ("movieclip".equals(shortName)) {
            this.setMakeMovieClip(true);
        } else if ("ES4".equals(shortName)) {
            this.setDialect("ES4");
        } else if ("li".equals(shortName)) {
            this.internalLibraries.add(option.getValue());
        } else if ("le".equals(shortName)) {
            this.externalLibraries.add(option.getValue());
        } else if ("parallel".equals(shortName)) {
            this.setParallel(true);
        } else if ("inline".equals(shortName)) {
            this.setMergeABCs(true); // inlining requires merging of ABCs
            this.setEnableInlining(true);
        } else if ("removedeadcode".equals(shortName)) {
            this.setRemoveDeadCode(true);
        } else {
            throw new UnrecognizedOptionException("Unrecognized option '" + shortName + "'", shortName);
        }
    }

    // Then any remaining arguments that were not options are interpreted as
    // source files to compile.
    final String[] remainingArgs = line.getArgs();
    if (remainingArgs != null) {
        for (int i = 0; i < remainingArgs.length; i++) {
            this.addSourceFilename(remainingArgs[i]);
        }
    } else {
        throw new MissingArgumentException(
                "At least one source file must be specified after the list of options.");
    }

    return true;
}

From source file:org.apache.flink.api.java.utils.ParameterTool.java

/**
 * Returns {@link ParameterTool} for the arguments parsed by {@link GenericOptionsParser}
 *
 * @param args Input array arguments. It should be parsable by {@link GenericOptionsParser}
 * @return A {@link ParameterTool}/*from ww w . j  a va  2s .c  o  m*/
 * @throws IOException If arguments cannot be parsed by {@link GenericOptionsParser}
 * @see GenericOptionsParser
 * @deprecated Please use {@link org.apache.flink.hadoopcompatibility.HadoopUtils#paramsFromGenericOptionsParser(String[])}
 * from project flink-hadoop-compatibility
 */
@Deprecated
@PublicEvolving
public static ParameterTool fromGenericOptionsParser(String[] args) throws IOException {
    Option[] options = new GenericOptionsParser(args).getCommandLine().getOptions();
    Map<String, String> map = new HashMap<String, String>();
    for (Option option : options) {
        String[] split = option.getValue().split("=");
        map.put(split[0], split[1]);
    }
    return fromMap(map);
}

From source file:org.apache.flink.hadoopcompatibility.HadoopUtils.java

/**
 * Returns {@link ParameterTool} for the arguments parsed by {@link GenericOptionsParser}
 *
 * @param args Input array arguments. It should be parsable by {@link GenericOptionsParser}
 * @return A {@link ParameterTool}/* w w w .  ja  v a 2  s. c om*/
 * @throws IOException If arguments cannot be parsed by {@link GenericOptionsParser}
 * @see GenericOptionsParser
 */
public static ParameterTool paramsFromGenericOptionsParser(String[] args) throws IOException {
    Option[] options = new GenericOptionsParser(args).getCommandLine().getOptions();
    Map<String, String> map = new HashMap<String, String>();
    for (Option option : options) {
        String[] split = option.getValue().split("=");
        map.put(split[0], split[1]);
    }
    return ParameterTool.fromMap(map);
}

From source file:org.apache.metron.dataservices.Main.java

public static void main(String[] args) throws Exception {

    Options options = new Options();

    options.addOption("homeDir", true, "Home directory for the service");

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

    Properties configProps = new Properties();

    String homeDir = cmd.getOptionValue("homeDir");

    if (homeDir.endsWith("/")) {
        homeDir = homeDir.substring(0, homeDir.length() - 1);
    }//  ww w  .j a v a  2  s .c o  m

    DOMConfigurator.configure(homeDir + "/log4j.xml");

    logger.warn("DataServices Server starting...");

    File configFile = new File(homeDir + "/config.properties");
    FileReader configFileReader = new FileReader(configFile);
    try {
        configProps.load(configFileReader);

        Option[] cmdOptions = cmd.getOptions();
        for (Option opt : cmdOptions) {
            String argName = opt.getOpt();
            String argValue = opt.getValue();

            configProps.put(argName, argValue);
        }

    } finally {
        if (configFileReader != null) {
            configFileReader.close();
        }
    }

    WebAppContext context = new WebAppContext();

    Injector injector = Guice.createInjector(new DefaultServletModule(configProps),
            new AlertsServerModule(configProps),
            new DefaultShiroWebModule(configProps, context.getServletContext()), new AbstractModule() {

                @Override
                protected void configure() {
                    binder().requireExplicitBindings();
                    bind(GuiceFilter.class);
                    bind(GuiceResteasyBootstrapServletContextListener.class);
                    bind(EnvironmentLoaderListener.class);

                }
            });

    injector.getAllBindings();
    injector.createChildInjector().getAllBindings();

    Server server = new Server(port);

    /***************************************************
     *************** enable SSL ************************
     ***************************************************/

    // HTTP Configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    http_config.setSecurePort(8443);
    http_config.setOutputBufferSize(32768);
    http_config.setRequestHeaderSize(8192);
    http_config.setResponseHeaderSize(8192);
    http_config.setSendServerVersion(true);
    http_config.setSendDateHeader(false);
    // httpConfig.addCustomizer(new ForwardedRequestCustomizer())
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    String sslKeystorePath = configProps.getProperty("sslKeystorePath", "/keystore");
    logger.debug("sslKeystorePath: " + sslKeystorePath);
    sslContextFactory.setKeyStorePath(homeDir + sslKeystorePath);

    String sslKeystorePassword = configProps.getProperty("sslKeystorePassword");
    sslContextFactory.setKeyStorePassword(sslKeystorePassword);

    String sslKeyManagerPassword = configProps.getProperty("sslKeyManagerPassword");
    if (sslKeyManagerPassword != null && !sslKeyManagerPassword.isEmpty()) {
        sslContextFactory.setKeyManagerPassword(sslKeyManagerPassword);
    }

    String sslTruststorePath = configProps.getProperty("sslTruststorePath");
    if (sslTruststorePath != null && !sslTruststorePath.isEmpty()) {
        sslContextFactory.setTrustStorePath(homeDir + sslTruststorePath);
    }

    String sslTruststorePassword = configProps.getProperty("sslTruststorePassword");
    if (sslTruststorePassword != null && !sslTruststorePassword.isEmpty()) {
        sslContextFactory.setTrustStorePassword(sslTruststorePassword);
    }

    sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA",
            "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
            "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
            "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");

    // SSL HTTP Configuration
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config));
    sslConnector.setPort(8443);
    server.addConnector(sslConnector);

    FilterHolder guiceFilter = new FilterHolder(injector.getInstance(GuiceFilter.class));

    /** For JSP support.  Used only for testing and debugging for now.  This came come out
     * once the real consumers for this service are in place
     */
    URL indexUri = Main.class.getResource(WEBROOT_INDEX);
    if (indexUri == null) {
        throw new FileNotFoundException("Unable to find resource " + WEBROOT_INDEX);
    }

    // Points to wherever /webroot/ (the resource) is
    URI baseUri = indexUri.toURI();

    // Establish Scratch directory for the servlet context (used by JSP compilation)
    File tempDir = new File(System.getProperty("java.io.tmpdir"));
    File scratchDir = new File(tempDir.toString(), "embedded-jetty-jsp");

    if (!scratchDir.exists()) {
        if (!scratchDir.mkdirs()) {
            throw new IOException("Unable to create scratch directory: " + scratchDir);
        }
    }

    // Set JSP to use Standard JavaC always
    System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");

    context.setAttribute("javax.servlet.context.tempdir", scratchDir);
    context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());

    //Ensure the jsp engine is initialized correctly
    JettyJasperInitializer sci = new JettyJasperInitializer();
    ServletContainerInitializersStarter sciStarter = new ServletContainerInitializersStarter(context);
    ContainerInitializer initializer = new ContainerInitializer(sci, null);
    List<ContainerInitializer> initializers = new ArrayList<ContainerInitializer>();
    initializers.add(initializer);

    context.setAttribute("org.eclipse.jetty.containerInitializers", initializers);
    context.addBean(sciStarter, true);

    // Set Classloader of Context to be sane (needed for JSTL)
    // JSP requires a non-System classloader, this simply wraps the
    // embedded System classloader in a way that makes it suitable
    // for JSP to use
    // new URL( "file:///home/prhodes/.m2/repository/javax/servlet/jsp/javax.servlet.jsp-api/2.3.1/javax.servlet.jsp-api-2.3.1.jar" ) 
    ClassLoader jspClassLoader = new URLClassLoader(new URL[] {},
            Thread.currentThread().getContextClassLoader());
    context.setClassLoader(jspClassLoader);

    // Add JSP Servlet (must be named "jsp")
    ServletHolder holderJsp = new ServletHolder("jsp", JspServlet.class);
    holderJsp.setInitOrder(0);
    holderJsp.setInitParameter("logVerbosityLevel", "DEBUG");
    holderJsp.setInitParameter("fork", "false");
    holderJsp.setInitParameter("xpoweredBy", "false");
    holderJsp.setInitParameter("compilerTargetVM", "1.7");
    holderJsp.setInitParameter("compilerSourceVM", "1.7");
    holderJsp.setInitParameter("keepgenerated", "true");
    context.addServlet(holderJsp, "*.jsp");
    //context.addServlet(holderJsp,"*.jspf");
    //context.addServlet(holderJsp,"*.jspx");

    // Add Default Servlet (must be named "default")
    ServletHolder holderDefault = new ServletHolder("default", DefaultServlet.class);
    holderDefault.setInitParameter("resourceBase", baseUri.toASCIIString());
    holderDefault.setInitParameter("dirAllowed", "true");
    context.addServlet(holderDefault, "/");

    /** end "for JSP support */

    context.setResourceBase(baseUri.toASCIIString());

    context.setInitParameter("resteasy.guice.modules",
            "org.apache.metron.dataservices.modules.guice.RestEasyModule");
    context.setInitParameter("resteasy.servlet.mapping.prefix", "/rest");

    context.addEventListener(injector.getInstance(GuiceResteasyBootstrapServletContextListener.class));
    context.addFilter(guiceFilter, "/*", EnumSet.allOf(DispatcherType.class));

    server.setHandler(context);
    server.start();

    AlertsProcessingServer alertsServer = injector.getInstance(AlertsProcessingServer.class);

    alertsServer.startProcessing();

    server.join();
}

From source file:org.apache.nifi.toolkit.cli.impl.command.AbstractPropertyCommand.java

@Override
public final R execute(final CommandLine commandLine) throws CommandException {
    try {/* ww  w  .jav a2 s .  c  o  m*/
        final Properties properties = new Properties();

        // start by loading the properties file if it was specified
        if (commandLine.hasOption(CommandOption.PROPERTIES.getLongName())) {
            final String propertiesFile = commandLine.getOptionValue(CommandOption.PROPERTIES.getLongName());
            if (!StringUtils.isBlank(propertiesFile)) {
                try (final InputStream in = new FileInputStream(propertiesFile)) {
                    properties.load(in);
                }
            }
        } else {
            // no properties file was specified so see if there is anything in the session
            final SessionVariable sessionVariable = getPropertiesSessionVariable();
            if (sessionVariable != null) {
                final Session session = getContext().getSession();
                final String sessionPropsFiles = session.get(sessionVariable.getVariableName());
                if (!StringUtils.isBlank(sessionPropsFiles)) {
                    try (final InputStream in = new FileInputStream(sessionPropsFiles)) {
                        properties.load(in);
                    }
                }
            }
        }

        // add in anything specified on command line, and override anything that was already there
        for (final Option option : commandLine.getOptions()) {
            final String optValue = option.getValue() == null ? "" : option.getValue();
            properties.setProperty(option.getLongOpt(), optValue);
        }

        // delegate to sub-classes
        return doExecute(properties);

    } catch (CommandException ce) {
        throw ce;
    } catch (Exception e) {
        throw new CommandException("Error executing command '" + getName() + "' : " + e.getMessage(), e);
    }
}

From source file:org.apache.reef.tang.formats.CommandLine.java

/**
 * Process command line arguments.//www.jav  a2  s . com
 *
 * @param <T> a type
 * @param args the command line arguments to be parsed
 * @param argClasses the target named classes to be set
 * @return Selfie if the command line parsing succeeded, null (or exception) otherwise.
 * @throws IOException if parsing fails
 * @throws BindException if a binding of short-named parameter fails
 */
@SafeVarargs
public final <T> CommandLine processCommandLine(final String[] args,
        final Class<? extends Name<?>>... argClasses) throws IOException, BindException {

    for (final Class<? extends Name<?>> c : argClasses) {
        registerShortNameOfClass(c);
    }

    final Options o = getCommandLineOptions();
    o.addOption(new Option("?", "help"));
    final Parser g = new GnuParser();

    final org.apache.commons.cli.CommandLine cl;
    try {
        cl = g.parse(o, args);
    } catch (final ParseException e) {
        throw new IOException("Could not parse config file", e);
    }

    if (cl.hasOption("?")) {
        new HelpFormatter().printHelp("reef", o);
        return null;
    }

    for (final Option option : cl.getOptions()) {

        final String shortName = option.getOpt();
        final String value = option.getValue();

        if (applicationOptions.containsKey(option)) {
            applicationOptions.get(option).process(option);
        } else {
            try {
                conf.bind(shortNames.get(shortName), value);
            } catch (final BindException e) {
                throw new BindException("Could not bind shortName " + shortName + " to value " + value, e);
            }
        }
    }

    return this;
}

From source file:org.apache.sentry.binding.hive.authz.SentryConfigTool.java

/**
 * parse arguments//  www. j a  v a2 s.  com
 * 
 * <pre>
 *   -d,--debug                  Enable debug output
 *   -e,--query <arg>            Query privilege verification, requires -u
 *   -h,--help                   Print usage
 *   -i,--policyIni <arg>        Policy file path
 *   -j,--jdbcURL <arg>          JDBC URL
 *   -l,--listPrivs,--listPerms  List privilges for given user, requires -u
 *   -p,--password <arg>         Password
 *   -s,--sentry-site <arg>      sentry-site file path
 *   -u,--user <arg>             user name
 *   -v,--validate               Validate policy file
 *   -I,--import                 Import policy file
 *   -E,--export                 Export policy file
 *   -o,--overwrite              Overwrite the exist role data when do the import
 * </pre>
 * 
 * @param args
 */
private void parseArgs(String[] args) {
    boolean enableDebug = false;

    Options sentryOptions = new Options();

    Option helpOpt = new Option("h", "help", false, "Print usage");
    helpOpt.setRequired(false);

    Option validateOpt = new Option("v", "validate", false, "Validate policy file");
    validateOpt.setRequired(false);

    Option queryOpt = new Option("e", "query", true, "Query privilege verification, requires -u");
    queryOpt.setRequired(false);

    Option listPermsOpt = new Option("l", "listPerms", false, "list permissions for given user, requires -u");
    listPermsOpt.setRequired(false);
    Option listPrivsOpt = new Option("listPrivs", false, "list privileges for given user, requires -u");
    listPrivsOpt.setRequired(false);

    Option importOpt = new Option("I", "import", true, "Import policy file");
    importOpt.setRequired(false);

    Option exportOpt = new Option("E", "export", true, "Export policy file");
    exportOpt.setRequired(false);
    // required args
    OptionGroup sentryOptGroup = new OptionGroup();
    sentryOptGroup.addOption(helpOpt);
    sentryOptGroup.addOption(validateOpt);
    sentryOptGroup.addOption(queryOpt);
    sentryOptGroup.addOption(listPermsOpt);
    sentryOptGroup.addOption(listPrivsOpt);
    sentryOptGroup.addOption(importOpt);
    sentryOptGroup.addOption(exportOpt);
    sentryOptGroup.setRequired(true);
    sentryOptions.addOptionGroup(sentryOptGroup);

    // optional args
    Option jdbcArg = new Option("j", "jdbcURL", true, "JDBC URL");
    jdbcArg.setRequired(false);
    sentryOptions.addOption(jdbcArg);

    Option sentrySitePath = new Option("s", "sentry-site", true, "sentry-site file path");
    sentrySitePath.setRequired(false);
    sentryOptions.addOption(sentrySitePath);

    Option globalPolicyPath = new Option("i", "policyIni", true, "Policy file path");
    globalPolicyPath.setRequired(false);
    sentryOptions.addOption(globalPolicyPath);

    Option userOpt = new Option("u", "user", true, "user name");
    userOpt.setRequired(false);
    sentryOptions.addOption(userOpt);

    Option passWordOpt = new Option("p", "password", true, "Password");
    userOpt.setRequired(false);
    sentryOptions.addOption(passWordOpt);

    Option debugOpt = new Option("d", "debug", false, "enable debug output");
    debugOpt.setRequired(false);
    sentryOptions.addOption(debugOpt);

    Option overwriteOpt = new Option("o", "overwrite", false, "enable import overwrite");
    overwriteOpt.setRequired(false);
    sentryOptions.addOption(overwriteOpt);

    try {
        Parser parser = new GnuParser();
        CommandLine cmd = parser.parse(sentryOptions, args);

        for (Option opt : cmd.getOptions()) {
            if (opt.getOpt().equals("s")) {
                setSentrySiteFile(opt.getValue());
            } else if (opt.getOpt().equals("i")) {
                setPolicyFile(opt.getValue());
            } else if (opt.getOpt().equals("e")) {
                setQuery(opt.getValue());
            } else if (opt.getOpt().equals("j")) {
                setJdbcURL(opt.getValue());
            } else if (opt.getOpt().equals("u")) {
                setUser(opt.getValue());
            } else if (opt.getOpt().equals("p")) {
                setPassWord(opt.getValue());
            } else if (opt.getOpt().equals("l") || opt.getOpt().equals("listPrivs")) {
                setListPrivs(true);
            } else if (opt.getOpt().equals("v")) {
                setValidate(true);
            } else if (opt.getOpt().equals("I")) {
                setImportPolicyFilePath(opt.getValue());
            } else if (opt.getOpt().equals("E")) {
                setExportPolicyFilePath(opt.getValue());
            } else if (opt.getOpt().equals("h")) {
                usage(sentryOptions);
            } else if (opt.getOpt().equals("d")) {
                enableDebug = true;
            } else if (opt.getOpt().equals("o")) {
                setImportOverwriteRole(true);
            }
        }

        if (isListPrivs() && (getUser() == null)) {
            throw new ParseException("Can't use -l without -u ");
        }
        if ((getQuery() != null) && (getUser() == null)) {
            throw new ParseException("Must use -u with -e ");
        }
    } catch (ParseException e1) {
        usage(sentryOptions);
    }

    if (!enableDebug) {
        // turn off log
        LogManager.getRootLogger().setLevel(Level.OFF);
    }
}

From source file:org.apache.sentry.cli.tools.PermissionsMigrationToolCommon.java

/**
 *  parse arguments/*from w ww  . ja  v  a  2  s .  c  o  m*/
 * <pre>
 *   -s,--source                   Sentry source version
 *   -c,--sentry_conf <filepath>   sentry config file path
 *   -p --policy_file <filepath>   sentry (source) policy file path
 *   -o --output      <filepath>   sentry (target) policy file path
 *   -d --dry_run                  provides the output the migration for inspection without
 *                                 making any configuration changes.
 *   -h,--help                     print usage
 * </pre>
 * @param args
 */
protected boolean parseArgs(String[] args) {
    Options options = new Options();

    Option sourceVersionOpt = new Option("s", "source", true, "Source Sentry version");
    sourceVersionOpt.setRequired(true);
    options.addOption(sourceVersionOpt);

    Option sentryConfPathOpt = new Option("c", "sentry_conf", true,
            "sentry-site.xml file path (only required in case of Sentry service)");
    sentryConfPathOpt.setRequired(false);
    options.addOption(sentryConfPathOpt);

    Option sentryPolicyFileOpt = new Option("p", "policy_file", true,
            "sentry (source) policy file path (only in case of file based Sentry configuration)");
    sentryPolicyFileOpt.setRequired(false);
    options.addOption(sentryPolicyFileOpt);

    Option sentryOutputFileOpt = new Option("o", "output", true,
            "sentry (target) policy file path (only in case of file based Sentry configuration)");
    sentryOutputFileOpt.setRequired(false);
    options.addOption(sentryOutputFileOpt);

    Option dryRunOpt = new Option("d", "dry_run", false,
            "provides the output the migration for inspection without making actual configuration changes");
    dryRunOpt.setRequired(false);
    options.addOption(dryRunOpt);

    // help option
    Option helpOpt = new Option("h", "help", false, "Shell usage");
    helpOpt.setRequired(false);
    options.addOption(helpOpt);

    // this Option is parsed first for help option
    Options helpOptions = new Options();
    helpOptions.addOption(helpOpt);

    try {
        Parser parser = new GnuParser();

        // parse help option first
        CommandLine cmd = parser.parse(helpOptions, args, true);
        for (Option opt : cmd.getOptions()) {
            if (opt.getOpt().equals("h")) {
                // get the help option, print the usage and exit
                usage(options);
                return false;
            }
        }

        // without help option
        cmd = parser.parse(options, args);

        String sourceVersionStr = null;

        for (Option opt : cmd.getOptions()) {
            if (opt.getOpt().equals("s")) {
                sourceVersionStr = opt.getValue();
            } else if (opt.getOpt().equals("c")) {
                confPath = Optional.of(opt.getValue());
            } else if (opt.getOpt().equals("p")) {
                policyFile = Optional.of(opt.getValue());
            } else if (opt.getOpt().equals("o")) {
                outputFile = Optional.of(opt.getValue());
            } else if (opt.getOpt().equals("d")) {
                dryRun = true;
            }
        }

        sourceVersion = Version.parse(sourceVersionStr);

        if (!(confPath.isPresent() || policyFile.isPresent())) {
            System.out.println("Please select either file-based Sentry configuration (-p and -o flags)"
                    + " or Sentry service (-c flag) for migration.");
            usage(options);
            return false;
        }

        if (confPath.isPresent() && (policyFile.isPresent() || outputFile.isPresent())) {
            System.out.println("In order to migrate service based Sentry configuration,"
                    + " do not specify either -p or -o parameters");
            usage(options);
            return false;
        }

        if (!confPath.isPresent() && (policyFile.isPresent() ^ outputFile.isPresent())) {
            System.out.println("In order to migrate file based Sentry configuration,"
                    + " please make sure to specify both -p and -o parameters.");
            usage(options);
            return false;
        }

    } catch (ParseException | java.text.ParseException pe) {
        System.out.println(pe.getMessage());
        usage(options);
        return false;
    }
    return true;
}

From source file:org.apache.sentry.cli.tools.SentryConfigToolCommon.java

/**
  *  parse arguments// w  w  w .ja va 2s.c  o m
  * <pre>
  *   -conf,--sentry_conf <filepath>     sentry config file path
  *   -p,--policy_ini     <arg>          policy file path
  *   -v,--validate                      validate policy file
  *   -c,--checkcompat                   check compatibility with service
  *   -i,--import                        import policy file
  *   -h,--help                          print usage
  * </pre>
  * @param args
  */
protected boolean parseArgs(String[] args) {
    Options options = new Options();

    Option globalPolicyPath = new Option("p", "policy_ini", true, "Policy file path");
    globalPolicyPath.setRequired(true);
    options.addOption(globalPolicyPath);

    Option validateOpt = new Option("v", "validate", false, "Validate policy file");
    validateOpt.setRequired(false);
    options.addOption(validateOpt);

    Option checkCompatOpt = new Option("c", "checkcompat", false, "Check compatibility with Sentry Service");
    checkCompatOpt.setRequired(false);
    options.addOption(checkCompatOpt);

    Option importOpt = new Option("i", "import", false, "Import policy file");
    importOpt.setRequired(false);
    options.addOption(importOpt);

    // file path of sentry-site
    Option sentrySitePathOpt = new Option("conf", "sentry_conf", true, "sentry-site file path");
    sentrySitePathOpt.setRequired(true);
    options.addOption(sentrySitePathOpt);

    // help option
    Option helpOpt = new Option("h", "help", false, "Shell usage");
    helpOpt.setRequired(false);
    options.addOption(helpOpt);

    // this Options is parsed first for help option
    Options helpOptions = new Options();
    helpOptions.addOption(helpOpt);

    try {
        Parser parser = new GnuParser();

        // parse help option first
        CommandLine cmd = parser.parse(helpOptions, args, true);
        for (Option opt : cmd.getOptions()) {
            if (opt.getOpt().equals("h")) {
                // get the help option, print the usage and exit
                usage(options);
                return false;
            }
        }

        // without help option
        cmd = parser.parse(options, args);

        for (Option opt : cmd.getOptions()) {
            if (opt.getOpt().equals("p")) {
                policyFile = opt.getValue();
            } else if (opt.getOpt().equals("v")) {
                validate = true;
            } else if (opt.getOpt().equals("i")) {
                importPolicy = true;
            } else if (opt.getOpt().equals("c")) {
                checkCompat = true;
            } else if (opt.getOpt().equals("conf")) {
                confPath = opt.getValue();
            }
        }

        if (!validate && !importPolicy) {
            throw new IllegalArgumentException(
                    "No action specified; at least one of action or import must be specified");
        }
    } catch (ParseException pe) {
        System.out.println(pe.getMessage());
        usage(options);
        return false;
    }
    return true;
}