Search in sources :

Example 31 with OptionParser

use of joptsimple.OptionParser 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 32 with OptionParser

use of joptsimple.OptionParser in project nzbhydra2 by theotherp.

the class NzbHydra method main.

public static void main(String[] args) throws Exception {
    LoggerFactory.getILoggerFactory();
    String version = NzbHydra.class.getPackage().getImplementationVersion();
    OptionParser parser = new OptionParser();
    parser.accepts("datafolder", "Define path to main data folder. Must start with ./ for relative paths").withRequiredArg().defaultsTo("./data");
    parser.accepts("host", "Run on this host").withOptionalArg();
    parser.accepts("nobrowser", "Don't open browser to Hydra");
    parser.accepts("port", "Run on this port (default: 5076)").withOptionalArg();
    parser.accepts("baseurl", "Set base URL (e.g. /nzbhydra)").withOptionalArg();
    parser.accepts("repairdb", "Repair database. Add database file path as argument").withRequiredArg();
    parser.accepts("help", "Print help");
    parser.accepts("version", "Print version");
    OptionSet options = null;
    try {
        options = parser.parse(args);
    } catch (OptionException e) {
        logger.error("Invalid startup options detected: {}", e.getMessage());
        System.exit(1);
    }
    if (System.getProperty("fromWrapper") == null && Arrays.stream(args).noneMatch(x -> x.equals("directstart"))) {
        logger.info("NZBHydra 2 must be started using the wrapper for restart and updates to work. If for some reason you need to start it from the JAR directly provide the command line argument \"directstart\"");
    } else if (options.has("help")) {
        parser.printHelpOn(System.out);
    } else if (options.has("version")) {
        logger.info("NZBHydra 2 version: " + version);
    } else if (options.has("repairdb")) {
        String databaseFilePath = (String) options.valueOf("repairdb");
        repairDb(databaseFilePath);
    } else {
        startup(args, options);
    }
}
Also used : Arrays(java.util.Arrays) AopAutoConfiguration(org.springframework.boot.autoconfigure.aop.AopAutoConfiguration) ApplicationReadyEvent(org.springframework.boot.context.event.ApplicationReadyEvent) UrlCalculator(org.nzbhydra.web.UrlCalculator) LoggerFactory(org.slf4j.LoggerFactory) LocalDateTime(java.time.LocalDateTime) Autowired(org.springframework.beans.factory.annotation.Autowired) SpringApplication(org.springframework.boot.SpringApplication) PreDestroy(javax.annotation.PreDestroy) OptionException(joptsimple.OptionException) ConfigProvider(org.nzbhydra.config.ConfigProvider) CacheManager(org.springframework.cache.CacheManager) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) OptionParser(joptsimple.OptionParser) JdbcDataSource(org.h2.jdbcx.JdbcDataSource) EnableScheduling(org.springframework.scheduling.annotation.EnableScheduling) URI(java.net.URI) OptionSet(joptsimple.OptionSet) EnableCaching(org.springframework.cache.annotation.EnableCaching) DebugInfosProvider(org.nzbhydra.debuginfos.DebugInfosProvider) Logger(org.slf4j.Logger) EnableAutoConfiguration(org.springframework.boot.autoconfigure.EnableAutoConfiguration) EventListener(org.springframework.context.event.EventListener) IOException(java.io.IOException) GenericStorage(org.nzbhydra.genericstorage.GenericStorage) ApplicationContext(org.springframework.context.ApplicationContext) RestController(org.springframework.web.bind.annotation.RestController) ComponentScan(org.springframework.context.annotation.ComponentScan) File(java.io.File) GuavaCacheManager(org.springframework.cache.guava.GuavaCacheManager) Configuration(org.springframework.context.annotation.Configuration) java.awt(java.awt) BrowserOpener(org.nzbhydra.misc.BrowserOpener) WebSocketAutoConfiguration(org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration) ConnectorStartFailedException(org.springframework.boot.context.embedded.tomcat.ConnectorStartFailedException) PostConstruct(javax.annotation.PostConstruct) Flyway(org.flywaydb.core.Flyway) Bean(org.springframework.context.annotation.Bean) YAMLException(org.yaml.snakeyaml.error.YAMLException) javax.swing(javax.swing) OptionException(joptsimple.OptionException) OptionSet(joptsimple.OptionSet) OptionParser(joptsimple.OptionParser)

Example 33 with OptionParser

use of joptsimple.OptionParser in project launcher by runelite.

the class Launcher method main.

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("version").withRequiredArg();
    parser.accepts("clientargs").withRequiredArg();
    parser.accepts("nojvm");
    parser.accepts("debug");
    OptionSet options = parser.parse(args);
    try {
        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception ex) {
        logger.warn("Unable to set cross platform look and feel", ex);
    }
    LauncherFrame frame = new LauncherFrame();
    Bootstrap bootstrap = getBootstrap();
    // update packr vmargs
    PackrConfig.updateLauncherArgs(bootstrap);
    if (options.has("version")) {
        String version = (String) options.valueOf("version");
        logger.info("Using version {}", version);
        DefaultArtifact artifact = bootstrap.getClient();
        artifact = (DefaultArtifact) artifact.setVersion(version);
        bootstrap.setClient(artifact);
        // non-releases are not signed
        verify = false;
    }
    ArtifactResolver resolver = new ArtifactResolver(REPO_DIR);
    resolver.setListener(frame);
    resolver.addRepositories();
    Artifact a = bootstrap.getClient();
    List<ArtifactResult> results = resolver.resolveArtifacts(a);
    if (results.isEmpty()) {
        logger.error("Unable to resolve artifacts");
        return;
    }
    try {
        verifyJarSignature(results.get(0).getArtifact().getFile());
        logger.info("Verified signature of {}", results.get(0).getArtifact());
    } catch (CertificateException | IOException | SecurityException ex) {
        if (verify) {
            logger.error("Unable to verify signature of jar file", ex);
            return;
        } else {
            logger.warn("Unable to verify signature of jar file", ex);
        }
    }
    frame.setVisible(false);
    frame.dispose();
    String clientArgs = getArgs(options);
    // packr doesn't let us specify command line arguments
    if ("true".equals(System.getProperty("runelite.launcher.nojvm")) || options.has("nojvm")) {
        ReflectionLauncher.launch(results, clientArgs, options);
    } else {
        JvmLauncher.launch(bootstrap, results, clientArgs, options);
    }
}
Also used : CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) OptionParser(joptsimple.OptionParser) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) DefaultArtifact(org.eclipse.aether.artifact.DefaultArtifact) Artifact(org.eclipse.aether.artifact.Artifact) ArtifactResult(org.eclipse.aether.resolution.ArtifactResult) Bootstrap(net.runelite.launcher.beans.Bootstrap) OptionSet(joptsimple.OptionSet) DefaultArtifact(org.eclipse.aether.artifact.DefaultArtifact)

Example 34 with OptionParser

use of joptsimple.OptionParser in project jopt-simple by jopt-simple.

the class HelpFormatterExample method main.

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser() {

        {
            accepts("c").withRequiredArg().ofType(Integer.class).describedAs("count").defaultsTo(1);
            accepts("q").withOptionalArg().ofType(Double.class).describedAs("quantity");
            accepts("d", "some date").withRequiredArg().required().withValuesConvertedBy(datePattern("MM/dd/yy"));
            acceptsAll(asList("v", "talkative", "chatty"), "be more verbose");
            accepts("output-file").withOptionalArg().ofType(File.class).describedAs("file");
            acceptsAll(asList("h", "?"), "show help").forHelp();
            acceptsAll(asList("cp", "classpath")).withRequiredArg().describedAs("path1" + pathSeparatorChar + "path2:...").ofType(File.class).withValuesSeparatedBy(pathSeparatorChar);
            nonOptions("files to chew on").ofType(File.class).describedAs("input files");
        }
    };
    parser.formatHelpWith(new MyFormatter());
    parser.printHelpOn(System.out);
}
Also used : OptionParser(joptsimple.OptionParser) File(java.io.File)

Example 35 with OptionParser

use of joptsimple.OptionParser in project jopt-simple by jopt-simple.

the class HelpScreenExample method main.

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser() {

        {
            accepts("c").withRequiredArg().ofType(Integer.class).describedAs("count").defaultsTo(1);
            accepts("q").withOptionalArg().ofType(Double.class).describedAs("quantity");
            accepts("d", "some date").withRequiredArg().required().withValuesConvertedBy(datePattern("MM/dd/yy"));
            acceptsAll(asList("v", "talkative", "chatty"), "be more verbose");
            accepts("output-file").withOptionalArg().ofType(File.class).describedAs("file");
            acceptsAll(asList("h", "?"), "show help").forHelp();
            acceptsAll(asList("cp", "classpath")).withRequiredArg().describedAs("path1" + pathSeparatorChar + "path2:...").ofType(File.class).withValuesSeparatedBy(pathSeparatorChar);
        }
    };
    parser.printHelpOn(System.out);
}
Also used : OptionParser(joptsimple.OptionParser) File(java.io.File)

Aggregations

OptionParser (joptsimple.OptionParser)199 OptionSet (joptsimple.OptionSet)151 File (java.io.File)58 IOException (java.io.IOException)29 Test (org.junit.Test)28 OptionException (joptsimple.OptionException)25 ArrayList (java.util.ArrayList)21 Properties (java.util.Properties)16 List (java.util.List)15 OptionSpec (joptsimple.OptionSpec)14 Test (org.junit.jupiter.api.Test)12 VerifiableProperties (com.github.ambry.config.VerifiableProperties)11 FileNotFoundException (java.io.FileNotFoundException)9 BufferedReader (java.io.BufferedReader)8 ArgumentAcceptingOptionSpec (joptsimple.ArgumentAcceptingOptionSpec)8 FileReader (java.io.FileReader)7 OptionSpecBuilder (joptsimple.OptionSpecBuilder)7 Closer (com.google.common.io.Closer)6 Cluster (voldemort.cluster.Cluster)6 StoreDefinition (voldemort.store.StoreDefinition)6