Search in sources :

Example 1 with BuiltinHelpFormatter

use of joptsimple.BuiltinHelpFormatter in project SpongeVanilla by SpongePowered.

the class VanillaServerMain method main.

public static void main(String[] args) throws Exception {
    OptionSet options = VanillaCommandLine.parse(args);
    if (options.has(HELP)) {
        if (System.console() == null) {
            // We have no supported terminal, print help with default terminal width
            VanillaCommandLine.printHelp(System.err);
        } else {
            // Terminal is (very likely) supported, use the terminal width provided by jline
            Terminal terminal = TerminalBuilder.builder().dumb(true).build();
            VanillaCommandLine.printHelp(new BuiltinHelpFormatter(terminal.getWidth(), 3), System.err);
        }
        return;
    } else if (options.has(VERSION)) {
        final Package pack = VanillaServerMain.class.getPackage();
        System.out.println(pack.getImplementationTitle() + ' ' + pack.getImplementationVersion());
        System.out.println(pack.getSpecificationTitle() + ' ' + pack.getSpecificationVersion());
        return;
    }
    // Download/verify Minecraft server installation if necessary and not disabled
    if (!options.has(NO_VERIFY_CLASSPATH)) {
        // Get the location of our jar
        Path base = Paths.get(VanillaServerMain.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
        try {
            // Download dependencies
            if (!downloadMinecraft(base, !options.has(NO_DOWNLOAD))) {
                System.err.println("Failed to load all required dependencies. Please download them manually:");
                System.err.println("Download " + MINECRAFT_SERVER_REMOTE + " and copy it to " + base.resolve(MINECRAFT_SERVER_LOCAL).toAbsolutePath());
                System.err.println("Download " + LAUNCHWRAPPER_REMOTE + " and copy it to " + base.resolve(LAUNCHWRAPPER_LOCAL).toAbsolutePath());
                System.exit(1);
                return;
            }
        } catch (IOException e) {
            System.err.println("Failed to download required dependencies. Please try again later.");
            e.printStackTrace();
            System.exit(1);
            return;
        }
    } else {
        System.err.println("Classpath verification is disabled. The server may NOT start properly unless you have all required dependencies on " + "the classpath!");
    }
    Launch.main(getLaunchArguments(TWEAKER, options.valuesOf(TWEAK_CLASS)));
}
Also used : Path(java.nio.file.Path) BuiltinHelpFormatter(joptsimple.BuiltinHelpFormatter) IOException(java.io.IOException) OptionSet(joptsimple.OptionSet) Terminal(org.jline.terminal.Terminal)

Example 2 with BuiltinHelpFormatter

use of joptsimple.BuiltinHelpFormatter in project LanternServer by LanternPowered.

the class LanternServerLaunch method main.

public void main(String[] args) {
    final LanternClassLoader classLoader = LanternClassLoader.get();
    // Exclude the ASM library
    classLoader.addTransformerExclusion(Exclusion.forPackage("org.objectweb.asm"));
    classLoader.addTransformerExclusion(Exclusion.forPackage("org.lanternpowered.server.transformer"));
    classLoader.addTransformerExclusion(Exclusion.forClass("org.lanternpowered.server.util.BytecodeUtils"));
    classLoader.addTransformer(new FinalFieldClassTransformer());
    classLoader.addTransformer(new FastValueContainerClassTransformer());
    // Get the default logger
    final Logger logger = LoggerFactory.getLogger(InternalPluginsInfo.Implementation.IDENTIFIER);
    try {
        // Create the shared option parser
        final OptionParser optionParser = new OptionParser();
        optionParser.allowsUnrecognizedOptions();
        final OptionSpec<Void> version = optionParser.acceptsAll(Arrays.asList("version", "v"), "Display the Lantern version");
        if (optionParser.parse(args).has(version)) {
            final Package pack = Platform.class.getPackage();
            logger.info(pack.getImplementationTitle() + ' ' + pack.getImplementationVersion());
            logger.info(pack.getSpecificationTitle() + ' ' + pack.getSpecificationVersion());
            return;
        }
        final OptionSpec<Void> help = optionParser.acceptsAll(Arrays.asList("help", "h", "?"), "Show this help text").forHelp();
        // Initialize the injector
        final LanternModule module = new LanternModule(logger, args, optionParser);
        final Injector injector = Guice.createInjector(Stage.DEVELOPMENT, module);
        logger.info("Instantiated the Injector in {} mode.", Environment.get().name().toLowerCase());
        // Create the server instance
        final LanternServer lanternServer = injector.getInstance(LanternServer.class);
        // Initialize and start the server
        lanternServer.initialize();
        try {
            final Field field = OptionParser.class.getDeclaredField("allowsUnrecognizedOptions");
            field.setAccessible(true);
            field.set(optionParser, false);
            optionParser.parse(args);
        } catch (OptionException e) {
            logger.warn("Something went wrong while parsing options", e);
        } catch (Exception e) {
            logger.error("Unexpected error", e);
        }
        // annotations will be detected
        if (optionParser.parse(args).has(help)) {
            if (System.console() != null) {
                // Terminal is (very likely) supported, use the terminal width provided by jline
                final Terminal terminal = TerminalConsoleAppender.getTerminal();
                if (terminal != null) {
                    optionParser.formatHelpWith(new BuiltinHelpFormatter(terminal.getWidth(), 3));
                }
            }
            optionParser.printHelpOn(System.err);
            return;
        }
        lanternServer.start();
    } catch (Throwable t) {
        logger.error("Error during server startup.", t);
        System.exit(1);
    }
}
Also used : LanternClassLoader(org.lanternpowered.launch.LanternClassLoader) OptionException(joptsimple.OptionException) Logger(org.slf4j.Logger) OptionParser(joptsimple.OptionParser) Terminal(org.jline.terminal.Terminal) OptionException(joptsimple.OptionException) Field(java.lang.reflect.Field) BuiltinHelpFormatter(joptsimple.BuiltinHelpFormatter) Injector(com.google.inject.Injector) FastValueContainerClassTransformer(org.lanternpowered.server.transformer.data.FastValueContainerClassTransformer) LanternModule(org.lanternpowered.server.inject.LanternModule) FinalFieldClassTransformer(org.lanternpowered.server.transformer.FinalFieldClassTransformer)

Example 3 with BuiltinHelpFormatter

use of joptsimple.BuiltinHelpFormatter in project apollo by spotify.

the class ServiceImpl method parseArgs.

private static Config parseArgs(Config config, String[] args, boolean cliHelp, ImmutableList.Builder<String> unprocessedArgsBuilder) throws IOException {
    config = appendConfig(config, CommonConfigKeys.APOLLO_ARGS_CORE.getKey(), Arrays.asList(args), "apollo cli args");
    final OptionParser parser = new OptionParser();
    parser.formatHelpWith(new BuiltinHelpFormatter(1024, 2));
    parser.allowsUnrecognizedOptions();
    parser.posixlyCorrect(System.getenv("POSIXLY_CORRECT") != null);
    parser.recognizeAlternativeLongOptions(true);
    final OptionSpec<Void> helpOption;
    if (cliHelp) {
        helpOption = parser.acceptsAll(ImmutableList.of("help", "h"), "Shows this help.").forHelp();
    } else {
        helpOption = null;
    }
    final OptionSpec<String> configOption = parser.accepts("D", "Set configuration key with '-Dkey=value'.  Supports Typesafe Config syntax, i.e. " + "'-Dhosts+=foo.${domain}'.").withRequiredArg();
    final OptionSpec<Boolean> syslogOption = parser.accepts("syslog", String.format("Log to syslog (Alias for '-D%s=<value>').", CommonConfigKeys.LOGGING_SYSLOG.getKey())).withOptionalArg().ofType(Boolean.class);
    final OptionSpec<Void> verboseOption = parser.acceptsAll(ImmutableList.of("verbose", "v"), String.format("Increase logging verbosity.  Overrides config key '%s'.", CommonConfigKeys.LOGGING_VERBOSITY.getKey()));
    final OptionSpec<Void> conciseOption = parser.acceptsAll(ImmutableList.of("concise", "c"), String.format("Decrease logging verbosity.  Overrides config key '%s'.", CommonConfigKeys.LOGGING_VERBOSITY.getKey()));
    final OptionSpec<Void> quietOption = parser.acceptsAll(ImmutableList.of("quiet", "q"), String.format("Resets logging level to OFF.  Can be mixed with '-v'/'--verbose' or " + "'-c'/'--concise'.  Overrides config key '%s'.", CommonConfigKeys.LOGGING_VERBOSITY.getKey()));
    final OptionSpec<String> configFile = parser.accepts("config", "Load configuration from the specified file. The values from the file will be " + "overlayed on top of any already loaded configuration.").withRequiredArg();
    final OptionSpec<String> unparsedOption = parser.nonOptions("Service-specific options that will be passed to the underlying service.");
    final OptionSet parsed;
    try {
        parsed = parser.parse(args);
    } catch (OptionException e) {
        throw new ApolloCliException("Could not parse command-line arguments", e);
    }
    if (helpOption != null && parsed.has(helpOption)) {
        // TODO: make help output a bit prettier
        StringWriter stringWriter = new StringWriter();
        try (PrintWriter pw = new PrintWriter(stringWriter)) {
            pw.println();
            pw.println("Usage: <program> [options...] -- [non-option args...]");
            pw.println();
            parser.printHelpOn(pw);
        }
        throw new ApolloHelpException(stringWriter.toString());
    }
    unprocessedArgsBuilder.addAll(parsed.valuesOf(unparsedOption));
    config = appendConfig(config, CommonConfigKeys.APOLLO_ARGS_UNPARSED.getKey(), unprocessedArgsBuilder.build(), "apollo unparsed cli args");
    int verbosity = 0;
    boolean hasVerbosity = false;
    for (OptionSpec<?> optionSpec : parsed.specs()) {
        if (optionSpec == quietOption) {
            verbosity = LOGGING_OFF_OFFSET;
            hasVerbosity = true;
        } else if (optionSpec == verboseOption) {
            verbosity++;
            hasVerbosity = true;
        } else if (optionSpec == conciseOption) {
            verbosity--;
            hasVerbosity = true;
        }
    }
    if (hasVerbosity) {
        config = appendConfig(config, CommonConfigKeys.LOGGING_VERBOSITY.getKey(), verbosity, "Command-line verbosity flags");
    }
    if (parsed.has(syslogOption)) {
        final boolean syslog;
        if (parsed.hasArgument(syslogOption)) {
            syslog = parsed.valueOf(syslogOption);
        } else {
            syslog = true;
        }
        config = appendConfig(config, CommonConfigKeys.LOGGING_SYSLOG.getKey(), syslog, "Command-line option --syslog");
    }
    for (String configString : parsed.valuesOf(configOption)) {
        String[] parts = configString.split("=", 2);
        final String key;
        final Object value;
        if (parts.length == 2) {
            key = parts[0];
            value = parts[1];
        } else {
            key = parts[0];
            value = true;
        }
        config = appendConfig(config, key, value, "Command-line configuration -D" + parts[0]);
    }
    if (parsed.has(configFile)) {
        final String configFileValue = parsed.valueOf(configFile);
        final Config overlayConfig = ConfigFactory.parseFile(new File(configFileValue));
        config = overlayConfig.withFallback(config);
    }
    return config;
}
Also used : Config(com.typesafe.config.Config) OptionException(joptsimple.OptionException) OptionParser(joptsimple.OptionParser) BuiltinHelpFormatter(joptsimple.BuiltinHelpFormatter) StringWriter(java.io.StringWriter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) OptionSet(joptsimple.OptionSet) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 4 with BuiltinHelpFormatter

use of joptsimple.BuiltinHelpFormatter in project PayFile by mikehearn.

the class Main method main.

public static void main(String[] args) throws Exception {
    // allow client to choose another network for testing by passing through an argument.
    OptionParser parser = new OptionParser();
    parser.accepts("network").withRequiredArg().withValuesConvertedBy(regex("(mainnet)|(testnet)|(regtest)")).defaultsTo("mainnet");
    parser.accepts("help").forHelp();
    parser.formatHelpWith(new BuiltinHelpFormatter(120, 10));
    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (OptionException e) {
        System.err.println(e.getMessage());
        System.err.println("");
        parser.printHelpOn(System.err);
        return;
    }
    if (options.has("help")) {
        parser.printHelpOn(System.out);
        return;
    }
    if (options.valueOf("network").equals(("testnet"))) {
        params = TestNet3Params.get();
        filePrefix = "testnet-";
    } else if (options.valueOf("network").equals(("mainnet"))) {
        params = MainNetParams.get();
        filePrefix = "";
    } else if (options.valueOf("network").equals(("regtest"))) {
        params = RegTestParams.get();
        filePrefix = "regtest-";
    }
    launch(args);
}
Also used : BuiltinHelpFormatter(joptsimple.BuiltinHelpFormatter) OptionException(joptsimple.OptionException) OptionSet(joptsimple.OptionSet) OptionParser(joptsimple.OptionParser)

Example 5 with BuiltinHelpFormatter

use of joptsimple.BuiltinHelpFormatter in project PayFile by mikehearn.

the class CLI method main.

public static void main(String[] args) throws Exception {
    BriefLogFormatter.init();
    //Logger.getLogger("").setLevel(Level.OFF);
    // allow client to choose another network for testing by passing through an argument.
    OptionParser parser = new OptionParser();
    parser.accepts("network").withRequiredArg().withValuesConvertedBy(regex("(mainnet)|(testnet)|(regtest)")).defaultsTo("mainnet");
    parser.accepts("server").withRequiredArg().required();
    parser.accepts("help").forHelp();
    parser.formatHelpWith(new BuiltinHelpFormatter(120, 10));
    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (OptionException e) {
        System.err.println(e.getMessage());
        System.err.println("");
        parser.printHelpOn(System.err);
        return;
    }
    if (options.has("help")) {
        parser.printHelpOn(System.out);
        return;
    }
    if (options.valueOf("network").equals(("testnet"))) {
        params = TestNet3Params.get();
        filePrefix = "testnet-";
    } else if (options.valueOf("network").equals(("mainnet"))) {
        params = MainNetParams.get();
        filePrefix = "";
    } else if (options.valueOf("network").equals(("regtest"))) {
        params = RegTestParams.get();
        filePrefix = "regtest-";
    }
    String server = options.valueOf("server").toString();
    System.out.println("Connecting to " + server);
    Socket socket = new Socket(server, 18754);
    final CLI cli = new CLI(socket);
    ShellFactory.createConsoleShell(server, "PayFile", cli).commandLoop();
    cli.shutdown();
}
Also used : BuiltinHelpFormatter(joptsimple.BuiltinHelpFormatter) OptionException(joptsimple.OptionException) OptionSet(joptsimple.OptionSet) OptionParser(joptsimple.OptionParser) Socket(java.net.Socket)

Aggregations

BuiltinHelpFormatter (joptsimple.BuiltinHelpFormatter)8 OptionException (joptsimple.OptionException)5 OptionParser (joptsimple.OptionParser)4 OptionSet (joptsimple.OptionSet)4 IOException (java.io.IOException)2 Terminal (org.jline.terminal.Terminal)2 Injector (com.google.inject.Injector)1 Config (com.typesafe.config.Config)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 OutputStream (java.io.OutputStream)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 Field (java.lang.reflect.Field)1 Socket (java.net.Socket)1 Path (java.nio.file.Path)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 LanternClassLoader (org.lanternpowered.launch.LanternClassLoader)1 LanternModule (org.lanternpowered.server.inject.LanternModule)1 FinalFieldClassTransformer (org.lanternpowered.server.transformer.FinalFieldClassTransformer)1