Search in sources :

Example 31 with BasicParser

use of org.apache.commons.cli.BasicParser in project perun by CESNET.

the class ExporterStarter method main.

public static void main(String[] args) {
    // create Options object
    Options options = new Options();
    options.addOption("id", true, "exporter ID");
    OptionGroup outputOptions = new OptionGroup();
    outputOptions.addOption(new Option("stdout", "Print audit log messages to the stdout"));
    outputOptions.addOption(new Option("tcp", "sends audit log messages to the host:port over TCP"));
    outputOptions.addOption(new Option("udp", "sends audit log messages to the host:port over UDP"));
    options.addOptionGroup(outputOptions);
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        String exporterId = cmd.getOptionValue("id");
        if (exporterId == null) {
            System.err.println("Exporter ID must be specified.");
            System.exit(1);
        }
        OutputType outputType = cmd.hasOption("stdout") ? OutputType.STDOUT : cmd.hasOption("tcp") ? OutputType.TCP : cmd.hasOption("udp") ? OutputType.UDP : OutputType.STDOUT;
        ExporterStarter exporter = new ExporterStarter(outputType);
        exporter.run(exporterId);
    } catch (ParseException e) {
        help(options);
        System.exit(1);
    }
}
Also used : Options(org.apache.commons.cli.Options) BasicParser(org.apache.commons.cli.BasicParser) CommandLine(org.apache.commons.cli.CommandLine) OptionGroup(org.apache.commons.cli.OptionGroup) Option(org.apache.commons.cli.Option) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException)

Example 32 with BasicParser

use of org.apache.commons.cli.BasicParser in project bookkeeper by apache.

the class FileSystemUpgrade method main.

public static void main(String[] args) throws Exception {
    org.apache.log4j.Logger root = org.apache.log4j.Logger.getRootLogger();
    root.addAppender(new org.apache.log4j.ConsoleAppender(new org.apache.log4j.PatternLayout("%-5p [%t]: %m%n")));
    root.setLevel(org.apache.log4j.Level.ERROR);
    org.apache.log4j.Logger.getLogger(FileSystemUpgrade.class).setLevel(org.apache.log4j.Level.INFO);
    final Options opts = new Options();
    opts.addOption("c", "conf", true, "Configuration for Bookie");
    opts.addOption("u", "upgrade", false, "Upgrade bookie directories");
    opts.addOption("f", "finalize", false, "Finalize upgrade");
    opts.addOption("r", "rollback", false, "Rollback upgrade");
    opts.addOption("h", "help", false, "Print help message");
    BasicParser parser = new BasicParser();
    CommandLine cmdLine = parser.parse(opts, args);
    if (cmdLine.hasOption("h")) {
        printHelp(opts);
        return;
    }
    if (!cmdLine.hasOption("c")) {
        String err = "Cannot upgrade without configuration";
        LOG.error(err);
        printHelp(opts);
        throw new IllegalArgumentException(err);
    }
    String confFile = cmdLine.getOptionValue("c");
    ServerConfiguration conf = new ServerConfiguration();
    try {
        conf.loadConf(new File(confFile).toURI().toURL());
    } catch (MalformedURLException mue) {
        LOG.error("Could not open configuration file " + confFile, mue);
        throw new IllegalArgumentException();
    } catch (ConfigurationException ce) {
        LOG.error("Invalid configuration file " + confFile, ce);
        throw new IllegalArgumentException();
    }
    if (cmdLine.hasOption("u")) {
        upgrade(conf);
    } else if (cmdLine.hasOption("r")) {
        rollback(conf);
    } else if (cmdLine.hasOption("f")) {
        finalizeUpgrade(conf);
    } else {
        String err = "Must specify -upgrade, -finalize or -rollback";
        LOG.error(err);
        printHelp(opts);
        throw new IllegalArgumentException(err);
    }
}
Also used : Options(org.apache.commons.cli.Options) MalformedURLException(java.net.MalformedURLException) ServerConfiguration(org.apache.bookkeeper.conf.ServerConfiguration) BasicParser(org.apache.commons.cli.BasicParser) CommandLine(org.apache.commons.cli.CommandLine) ConfigurationException(org.apache.commons.configuration.ConfigurationException) File(java.io.File)

Example 33 with BasicParser

use of org.apache.commons.cli.BasicParser in project cdap by caskdata.

the class CLIMain method main.

public static void main(String[] args) {
    // disable logback logging
    Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(Level.OFF);
    final PrintStream output = System.out;
    Options options = getOptions();
    CLIMainArgs cliMainArgs = CLIMainArgs.parse(args, options);
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine command = parser.parse(options, cliMainArgs.getOptionTokens());
        if (command.hasOption(HELP_OPTION.getOpt())) {
            usage();
            System.exit(0);
        }
        LaunchOptions launchOptions = LaunchOptions.builder().setUri(command.getOptionValue(URI_OPTION.getOpt(), getDefaultURI().toString())).setDebug(command.hasOption(DEBUG_OPTION.getOpt())).setVerifySSL(parseBooleanOption(command, VERIFY_SSL_OPTION, DEFAULT_VERIFY_SSL)).setAutoconnect(parseBooleanOption(command, AUTOCONNECT_OPTION, DEFAULT_AUTOCONNECT)).build();
        String scriptFile = command.getOptionValue(SCRIPT_OPTION.getOpt(), "");
        boolean hasScriptFile = command.hasOption(SCRIPT_OPTION.getOpt());
        String[] commandArgs = cliMainArgs.getCommandTokens();
        try {
            ClientConfig clientConfig = ClientConfig.builder().setConnectionConfig(null).setDefaultReadTimeout(parseIntegerOption(command, TIMEOUT_OPTION, 60) * 1000).build();
            final CLIConfig cliConfig = new CLIConfig(clientConfig, output, new AltStyleTableRenderer());
            CLIMain cliMain = new CLIMain(launchOptions, cliConfig);
            CLI cli = cliMain.getCLI();
            if (!cliMain.tryAutoconnect(command)) {
                System.exit(0);
            }
            CLIConnectionConfig connectionConfig = new CLIConnectionConfig(cliConfig.getClientConfig().getConnectionConfig(), cliConfig.getCurrentNamespace(), null);
            cliMain.updateCLIPrompt(connectionConfig);
            if (hasScriptFile) {
                File script = cliMain.getFilePathResolver().resolvePathToFile(scriptFile);
                if (!script.exists()) {
                    output.println("ERROR: Script file '" + script.getAbsolutePath() + "' does not exist");
                    System.exit(1);
                }
                List<String> scriptLines = Files.readLines(script, Charsets.UTF_8);
                for (String scriptLine : scriptLines) {
                    output.print(cliMain.getPrompt(connectionConfig));
                    output.println(scriptLine);
                    cli.execute(scriptLine, output);
                    output.println();
                }
            } else if (commandArgs.length == 0) {
                cli.startInteractiveMode(output);
            } else {
                cli.execute(Joiner.on(" ").join(commandArgs), output);
            }
        } catch (DisconnectedException e) {
            output.printf("Couldn't reach the CDAP instance at '%s'.", e.getConnectionConfig().getURI().toString());
        } catch (Exception e) {
            e.printStackTrace(output);
        }
    } catch (ParseException e) {
        output.println(e.getMessage());
        usage();
    }
}
Also used : PrintStream(java.io.PrintStream) Options(org.apache.commons.cli.Options) CLI(co.cask.common.cli.CLI) AltStyleTableRenderer(co.cask.cdap.cli.util.table.AltStyleTableRenderer) Logger(ch.qos.logback.classic.Logger) URISyntaxException(java.net.URISyntaxException) DisconnectedException(co.cask.cdap.client.exception.DisconnectedException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) InvalidCommandException(co.cask.common.cli.exception.InvalidCommandException) ParseException(org.apache.commons.cli.ParseException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) BasicParser(org.apache.commons.cli.BasicParser) CommandLine(org.apache.commons.cli.CommandLine) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException) ClientConfig(co.cask.cdap.client.config.ClientConfig) File(java.io.File) DisconnectedException(co.cask.cdap.client.exception.DisconnectedException)

Example 34 with BasicParser

use of org.apache.commons.cli.BasicParser in project cdap by caskdata.

the class CoprocessorBuildTool method main.

public static void main(final String[] args) throws ParseException {
    Options options = new Options().addOption(new Option("h", "help", false, "Print this usage message.")).addOption(new Option("f", "force", false, "Overwrites any coprocessors that already exist."));
    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);
    String[] commandArgs = commandLine.getArgs();
    // if help is an option, or if there isn't a single 'ensure' command, print usage and exit.
    if (commandLine.hasOption("h") || commandArgs.length != 1 || !"check".equalsIgnoreCase(commandArgs[0])) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(CoprocessorBuildTool.class.getName() + " check", "Checks that HBase coprocessors required by CDAP are loaded onto HDFS. " + "If not, the coprocessors are built and placed on HDFS.", options, "");
        System.exit(0);
    }
    boolean overwrite = commandLine.hasOption("f");
    CConfiguration cConf = CConfiguration.create();
    Configuration hConf = HBaseConfiguration.create();
    Injector injector = Guice.createInjector(new ConfigModule(cConf, hConf), // for LocationFactory
    new PrivateModule() {

        @Override
        protected void configure() {
            bind(FileContext.class).toProvider(FileContextProvider.class).in(Scopes.SINGLETON);
            expose(LocationFactory.class);
        }

        @Provides
        @Singleton
        private LocationFactory providesLocationFactory(Configuration hConf, CConfiguration cConf, FileContext fc) {
            final String namespace = cConf.get(Constants.CFG_HDFS_NAMESPACE);
            if (UserGroupInformation.isSecurityEnabled()) {
                return new FileContextLocationFactory(hConf, namespace);
            }
            return new InsecureFileContextLocationFactory(hConf, namespace, fc);
        }
    });
    try {
        SecurityUtil.loginForMasterService(cConf);
    } catch (Exception e) {
        LOG.error("Failed to login as CDAP user", e);
        System.exit(1);
    }
    LocationFactory locationFactory = injector.getInstance(LocationFactory.class);
    HBaseTableUtil tableUtil = new HBaseTableUtilFactory(cConf).get();
    CoprocessorManager coprocessorManager = new CoprocessorManager(cConf, locationFactory, tableUtil);
    try {
        Location location = coprocessorManager.ensureCoprocessorExists(overwrite);
        LOG.info("coprocessor exists at {}.", location);
    } catch (IOException e) {
        LOG.error("Unable to build and upload coprocessor jars.", e);
        System.exit(1);
    }
}
Also used : Options(org.apache.commons.cli.Options) CConfiguration(co.cask.cdap.common.conf.CConfiguration) Configuration(org.apache.hadoop.conf.Configuration) HBaseConfiguration(org.apache.hadoop.hbase.HBaseConfiguration) ConfigModule(co.cask.cdap.common.guice.ConfigModule) InsecureFileContextLocationFactory(co.cask.cdap.common.guice.InsecureFileContextLocationFactory) FileContextLocationFactory(org.apache.twill.filesystem.FileContextLocationFactory) HelpFormatter(org.apache.commons.cli.HelpFormatter) Injector(com.google.inject.Injector) InsecureFileContextLocationFactory(co.cask.cdap.common.guice.InsecureFileContextLocationFactory) HBaseTableUtilFactory(co.cask.cdap.data2.util.hbase.HBaseTableUtilFactory) CommandLineParser(org.apache.commons.cli.CommandLineParser) PrivateModule(com.google.inject.PrivateModule) IOException(java.io.IOException) Provides(com.google.inject.Provides) CConfiguration(co.cask.cdap.common.conf.CConfiguration) HBaseTableUtil(co.cask.cdap.data2.util.hbase.HBaseTableUtil) IOException(java.io.IOException) ParseException(org.apache.commons.cli.ParseException) InsecureFileContextLocationFactory(co.cask.cdap.common.guice.InsecureFileContextLocationFactory) LocationFactory(org.apache.twill.filesystem.LocationFactory) FileContextLocationFactory(org.apache.twill.filesystem.FileContextLocationFactory) BasicParser(org.apache.commons.cli.BasicParser) CommandLine(org.apache.commons.cli.CommandLine) CoprocessorManager(co.cask.cdap.data2.util.hbase.CoprocessorManager) Singleton(com.google.inject.Singleton) Option(org.apache.commons.cli.Option) FileContext(org.apache.hadoop.fs.FileContext) Location(org.apache.twill.filesystem.Location)

Example 35 with BasicParser

use of org.apache.commons.cli.BasicParser in project atlas by apache.

the class HBaseBridge method main.

public static void main(String[] args) {
    int exitCode = EXIT_CODE_FAILED;
    try {
        Options options = new Options();
        options.addOption("n", "namespace", true, "namespace");
        options.addOption("t", "table", true, "tablename");
        options.addOption("f", "filename", true, "filename");
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);
        String namespaceToImport = cmd.getOptionValue("n");
        String tableToImport = cmd.getOptionValue("t");
        String fileToImport = cmd.getOptionValue("f");
        Configuration atlasConf = ApplicationProperties.get();
        String[] urls = atlasConf.getStringArray(ATLAS_ENDPOINT);
        if (urls == null || urls.length == 0) {
            urls = new String[] { DEFAULT_ATLAS_URL };
        }
        final AtlasClientV2 atlasClientV2;
        if (!AuthenticationUtil.isKerberosAuthenticationEnabled()) {
            String[] basicAuthUsernamePassword = AuthenticationUtil.getBasicAuthenticationInput();
            atlasClientV2 = new AtlasClientV2(urls, basicAuthUsernamePassword);
        } else {
            UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
            atlasClientV2 = new AtlasClientV2(ugi, ugi.getShortUserName(), urls);
        }
        HBaseBridge importer = new HBaseBridge(atlasConf, atlasClientV2);
        if (StringUtils.isNotEmpty(fileToImport)) {
            File f = new File(fileToImport);
            if (f.exists() && f.canRead()) {
                BufferedReader br = new BufferedReader(new FileReader(f));
                String line = null;
                while ((line = br.readLine()) != null) {
                    String[] val = line.split(":");
                    if (ArrayUtils.isNotEmpty(val)) {
                        namespaceToImport = val[0];
                        if (val.length > 1) {
                            tableToImport = val[1];
                        } else {
                            tableToImport = "";
                        }
                        importer.importHBaseEntities(namespaceToImport, tableToImport);
                    }
                }
                exitCode = EXIT_CODE_SUCCESS;
            } else {
                LOG.error("Failed to read the file");
            }
        } else {
            importer.importHBaseEntities(namespaceToImport, tableToImport);
            exitCode = EXIT_CODE_SUCCESS;
        }
    } catch (ParseException e) {
        LOG.error("Failed to parse arguments. Error: ", e.getMessage());
        printUsage();
    } catch (Exception e) {
        System.out.println("ImportHBaseEntities failed. Please check the log file for the detailed error message");
        LOG.error("ImportHBaseEntities failed", e);
    }
    System.exit(exitCode);
}
Also used : Options(org.apache.commons.cli.Options) AtlasClientV2(org.apache.atlas.AtlasClientV2) Configuration(org.apache.commons.configuration.Configuration) HBaseConfiguration(org.apache.hadoop.hbase.HBaseConfiguration) ParseException(org.apache.commons.cli.ParseException) AtlasHookException(org.apache.atlas.hook.AtlasHookException) BasicParser(org.apache.commons.cli.BasicParser) CommandLine(org.apache.commons.cli.CommandLine) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException) File(java.io.File) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Aggregations

BasicParser (org.apache.commons.cli.BasicParser)53 CommandLine (org.apache.commons.cli.CommandLine)49 Options (org.apache.commons.cli.Options)38 CommandLineParser (org.apache.commons.cli.CommandLineParser)35 ParseException (org.apache.commons.cli.ParseException)33 HelpFormatter (org.apache.commons.cli.HelpFormatter)25 File (java.io.File)14 IOException (java.io.IOException)14 Option (org.apache.commons.cli.Option)11 ClientConfig (co.cask.cdap.client.config.ClientConfig)2 BufferedReader (java.io.BufferedReader)2 FileInputStream (java.io.FileInputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 FileOutputStream (java.io.FileOutputStream)2 FileReader (java.io.FileReader)2 URL (java.net.URL)2 ArrayList (java.util.ArrayList)2 AtlasClientV2 (org.apache.atlas.AtlasClientV2)2 AtlasHookException (org.apache.atlas.hook.AtlasHookException)2 ServerConfiguration (org.apache.bookkeeper.conf.ServerConfiguration)2