Search in sources :

Example 56 with JCommander

use of com.beust.jcommander.JCommander in project ignite by apache.

the class AgentLauncher method main.

/**
     * @param args Args.
     */
public static void main(String[] args) throws Exception {
    log.info("Starting Apache Ignite Web Console Agent...");
    final AgentConfiguration cfg = new AgentConfiguration();
    JCommander jCommander = new JCommander(cfg);
    String osName = System.getProperty("os.name").toLowerCase();
    jCommander.setProgramName("ignite-web-agent." + (osName.contains("win") ? "bat" : "sh"));
    try {
        jCommander.parse(args);
    } catch (ParameterException pe) {
        log.error("Failed to parse command line parameters: " + Arrays.toString(args), pe);
        jCommander.usage();
        return;
    }
    String prop = cfg.configPath();
    AgentConfiguration propCfg = new AgentConfiguration();
    try {
        File f = AgentUtils.resolvePath(prop);
        if (f == null)
            log.warn("Failed to find agent property file: {}", prop);
        else
            propCfg.load(f.toURI().toURL());
    } catch (IOException e) {
        if (!AgentConfiguration.DFLT_CFG_PATH.equals(prop))
            log.warn("Failed to load agent property file: " + prop, e);
    }
    cfg.merge(propCfg);
    if (cfg.help()) {
        jCommander.usage();
        return;
    }
    System.out.println();
    System.out.println("Agent configuration:");
    System.out.println(cfg);
    System.out.println();
    if (cfg.tokens() == null) {
        String webHost;
        try {
            webHost = new URI(cfg.serverUri()).getHost();
        } catch (URISyntaxException e) {
            log.error("Failed to parse Ignite Web Console uri", e);
            return;
        }
        System.out.println("Security token is required to establish connection to the web console.");
        System.out.println(String.format("It is available on the Profile page: https://%s/profile", webHost));
        String tokens = String.valueOf(readPassword("Enter security tokens separated by comma: "));
        cfg.tokens(Arrays.asList(tokens.trim().split(",")));
    }
    URI uri = URI.create(cfg.serverUri());
    // Create proxy authenticator using passed properties.
    switch(uri.getScheme()) {
        case "http":
        case "https":
            final String username = System.getProperty(uri.getScheme() + ".proxyUsername");
            final char[] pwd = System.getProperty(uri.getScheme() + ".proxyPassword", "").toCharArray();
            Authenticator.setDefault(new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, pwd);
                }
            });
            break;
        default:
    }
    IO.Options opts = new IO.Options();
    opts.path = "/agents";
    // Workaround for use self-signed certificate
    if (Boolean.getBoolean("trust.all")) {
        SSLContext ctx = SSLContext.getInstance("TLS");
        // Create an SSLContext that uses our TrustManager
        ctx.init(null, getTrustManagers(), null);
        opts.sslContext = ctx;
    }
    final Socket client = IO.socket(uri, opts);
    final RestExecutor restExecutor = new RestExecutor(cfg.nodeUri());
    try {
        final ClusterListener clusterLsnr = new ClusterListener(client, restExecutor);
        final DemoListener demoHnd = new DemoListener(client, restExecutor);
        Emitter.Listener onConnect = new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                log.info("Connection established.");
                JSONObject authMsg = new JSONObject();
                try {
                    authMsg.put("tokens", toJSON(cfg.tokens()));
                    authMsg.put("disableDemo", cfg.disableDemo());
                    String clsName = AgentLauncher.class.getSimpleName() + ".class";
                    String clsPath = AgentLauncher.class.getResource(clsName).toString();
                    if (clsPath.startsWith("jar")) {
                        String manifestPath = clsPath.substring(0, clsPath.lastIndexOf('!') + 1) + "/META-INF/MANIFEST.MF";
                        Manifest manifest = new Manifest(new URL(manifestPath).openStream());
                        Attributes attr = manifest.getMainAttributes();
                        authMsg.put("ver", attr.getValue("Implementation-Version"));
                        authMsg.put("bt", attr.getValue("Build-Time"));
                    }
                    client.emit("agent:auth", authMsg, new Ack() {

                        @Override
                        public void call(Object... args) {
                            if (args != null) {
                                if (args[0] instanceof String) {
                                    log.error((String) args[0]);
                                    System.exit(1);
                                }
                                if (args[0] == null && args[1] instanceof JSONArray) {
                                    try {
                                        List<String> activeTokens = fromJSON(args[1], List.class);
                                        if (!F.isEmpty(activeTokens)) {
                                            Collection<String> missedTokens = cfg.tokens();
                                            cfg.tokens(activeTokens);
                                            missedTokens.removeAll(activeTokens);
                                            if (!F.isEmpty(missedTokens)) {
                                                String tokens = F.concat(missedTokens, ", ");
                                                log.warn("Failed to authenticate with token(s): {}. " + "Please reload agent archive or check settings", tokens);
                                            }
                                            log.info("Authentication success.");
                                            clusterLsnr.watch();
                                            return;
                                        }
                                    } catch (Exception e) {
                                        log.error("Failed to authenticate agent. Please check agent\'s tokens", e);
                                        System.exit(1);
                                    }
                                }
                            }
                            log.error("Failed to authenticate agent. Please check agent\'s tokens");
                            System.exit(1);
                        }
                    });
                } catch (JSONException | IOException e) {
                    log.error("Failed to construct authentication message", e);
                    client.close();
                }
            }
        };
        DatabaseListener dbHnd = new DatabaseListener(cfg);
        RestListener restHnd = new RestListener(restExecutor);
        final CountDownLatch latch = new CountDownLatch(1);
        log.info("Connecting to: {}", cfg.serverUri());
        client.on(EVENT_CONNECT, onConnect).on(EVENT_CONNECT_ERROR, onError).on(EVENT_ERROR, onError).on(EVENT_DISCONNECT, onDisconnect).on(EVENT_LOG_WARNING, onLogWarning).on(EVENT_CLUSTER_BROADCAST_START, clusterLsnr.start()).on(EVENT_CLUSTER_BROADCAST_STOP, clusterLsnr.stop()).on(EVENT_DEMO_BROADCAST_START, demoHnd.start()).on(EVENT_DEMO_BROADCAST_STOP, demoHnd.stop()).on(EVENT_RESET_TOKENS, new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                String tok = String.valueOf(args[0]);
                log.warn("Security token has been reset: {}", tok);
                cfg.tokens().remove(tok);
                if (cfg.tokens().isEmpty()) {
                    client.off();
                    latch.countDown();
                }
            }
        }).on(EVENT_SCHEMA_IMPORT_DRIVERS, dbHnd.availableDriversListener()).on(EVENT_SCHEMA_IMPORT_SCHEMAS, dbHnd.schemasListener()).on(EVENT_SCHEMA_IMPORT_METADATA, dbHnd.metadataListener()).on(EVENT_NODE_VISOR_TASK, restHnd).on(EVENT_NODE_REST, restHnd);
        client.connect();
        latch.await();
    } finally {
        restExecutor.stop();
        client.close();
    }
}
Also used : Emitter(io.socket.emitter.Emitter) DemoListener(org.apache.ignite.console.agent.handlers.DemoListener) ClusterListener(org.apache.ignite.console.agent.handlers.ClusterListener) RestListener(org.apache.ignite.console.agent.handlers.RestListener) DatabaseListener(org.apache.ignite.console.agent.handlers.DatabaseListener) Attributes(java.util.jar.Attributes) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL) JCommander(com.beust.jcommander.JCommander) ParameterException(com.beust.jcommander.ParameterException) List(java.util.List) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication) DemoListener(org.apache.ignite.console.agent.handlers.DemoListener) IO(io.socket.client.IO) RestExecutor(org.apache.ignite.console.agent.rest.RestExecutor) Ack(io.socket.client.Ack) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) IOException(java.io.IOException) SSLContext(javax.net.ssl.SSLContext) DatabaseListener(org.apache.ignite.console.agent.handlers.DatabaseListener) Manifest(java.util.jar.Manifest) CountDownLatch(java.util.concurrent.CountDownLatch) ParameterException(com.beust.jcommander.ParameterException) URISyntaxException(java.net.URISyntaxException) JSONException(org.json.JSONException) ConnectException(java.net.ConnectException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) RestListener(org.apache.ignite.console.agent.handlers.RestListener) JSONObject(org.json.JSONObject) ClusterListener(org.apache.ignite.console.agent.handlers.ClusterListener) Collection(java.util.Collection) JSONObject(org.json.JSONObject) File(java.io.File) Socket(io.socket.client.Socket)

Example 57 with JCommander

use of com.beust.jcommander.JCommander in project GeoGig by boundlessgeo.

the class GeogigConsole method addCommandCompleter.

private void addCommandCompleter(ConsoleReader consoleReader, final GeogigCLI cli) {
    final JCommander globalCommandParser = cli.newCommandParser();
    final Map<String, JCommander> commands = globalCommandParser.getCommands();
    List<Completer> completers = new ArrayList<Completer>(commands.size());
    for (Map.Entry<String, JCommander> entry : commands.entrySet()) {
        String commandName = entry.getKey();
        JCommander commandParser = entry.getValue();
        List<ParameterDescription> parameters = commandParser.getParameters();
        List<String> options = new ArrayList<String>(parameters.size());
        for (ParameterDescription pd : parameters) {
            String longestName = pd.getLongestName();
            options.add(longestName);
        }
        Collections.sort(options);
        ArgumentCompleter commandCompleter = new ArgumentCompleter(new StringsCompleter(commandName), new StringsCompleter(options));
        completers.add(commandCompleter);
    }
    completers.add(new StringsCompleter("exit", "clear"));
    Completer completer = new AggregateCompleter(completers);
    consoleReader.addCompleter(completer);
}
Also used : ArgumentCompleter(jline.console.completer.ArgumentCompleter) AggregateCompleter(jline.console.completer.AggregateCompleter) ArrayList(java.util.ArrayList) Completer(jline.console.completer.Completer) StringsCompleter(jline.console.completer.StringsCompleter) AggregateCompleter(jline.console.completer.AggregateCompleter) ArgumentCompleter(jline.console.completer.ArgumentCompleter) StringsCompleter(jline.console.completer.StringsCompleter) JCommander(com.beust.jcommander.JCommander) Map(java.util.Map) ParameterDescription(com.beust.jcommander.ParameterDescription)

Example 58 with JCommander

use of com.beust.jcommander.JCommander in project GeoGig by boundlessgeo.

the class Help method run.

/**
     * Executes the help command.
     * 
     * @param cli
     * @see org.locationtech.geogig.cli.CLICommand#run(org.locationtech.geogig.cli.GeogigCLI)
     */
// @Override
public void run(GeogigCLI cli) {
    JCommander jc = cli.newCommandParser();
    if (all) {
        cli.printCommandList(jc);
    } else {
        if (parameters.isEmpty()) {
            cli.printShortCommandList(jc);
        } else {
            String command = parameters.get(0);
            jc.usage(command);
        }
    }
}
Also used : JCommander(com.beust.jcommander.JCommander)

Example 59 with JCommander

use of com.beust.jcommander.JCommander in project GeoGig by boundlessgeo.

the class GeogigCLI method printShortCommandList.

/**
     * This prints out only porcelain commands
     * 
     * @param mainCommander
     * 
     * @throws IOException
     */
public void printShortCommandList(JCommander mainCommander) {
    TreeSet<String> commandNames = Sets.newTreeSet();
    int longestCommandLenght = 0;
    // do this to ignore aliases
    for (String name : mainCommander.getCommands().keySet()) {
        JCommander command = mainCommander.getCommands().get(name);
        Class<? extends Object> clazz = command.getObjects().get(0).getClass();
        String packageName = clazz.getPackage().getName();
        if (!packageName.startsWith("org.locationtech.geogig.cli.plumbing")) {
            commandNames.add(name);
            longestCommandLenght = Math.max(longestCommandLenght, name.length());
        }
    }
    ConsoleReader console = getConsole();
    try {
        console.println("usage: geogig <command> [<args>]");
        console.println();
        console.println("The most commonly used geogig commands are:");
        for (String cmd : commandNames) {
            console.print(Strings.padEnd(cmd, longestCommandLenght, ' '));
            console.print("\t");
            console.println(mainCommander.getCommandDescription(cmd));
        }
        console.flush();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
Also used : ConsoleReader(jline.console.ConsoleReader) JCommander(com.beust.jcommander.JCommander) IOException(java.io.IOException)

Example 60 with JCommander

use of com.beust.jcommander.JCommander in project GeoGig by boundlessgeo.

the class AbstractCommand method printUsage.

/**
     * Prints the JCommander usage for this command.
     */
public void printUsage(GeogigCLI cli) {
    JCommander jc = new JCommander(this);
    String commandName = this.getClass().getAnnotation(Parameters.class).commandNames()[0];
    jc.setProgramName("geogig " + commandName);
    cli.printUsage(jc);
}
Also used : JCommander(com.beust.jcommander.JCommander)

Aggregations

JCommander (com.beust.jcommander.JCommander)65 ParameterException (com.beust.jcommander.ParameterException)15 IOException (java.io.IOException)10 Map (java.util.Map)6 ParameterDescription (com.beust.jcommander.ParameterDescription)4 FileInputStream (java.io.FileInputStream)3 Console (com.beust.jcommander.internal.Console)2 DefaultCommand (com.evolveum.midpoint.cli.common.DefaultCommand)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Charsets (com.google.common.base.Charsets)2 Throwables (com.google.common.base.Throwables)2 HostAndPort (com.google.common.net.HostAndPort)2 Service (com.google.common.util.concurrent.Service)2 CreationException (com.google.inject.CreationException)2 SystemException (com.torodb.core.exceptions.SystemException)2 BackendPasswordConfig (com.torodb.packaging.config.model.backend.BackendPasswordConfig)2 AbstractDerby (com.torodb.packaging.config.model.backend.derby.AbstractDerby)2 AbstractPostgres (com.torodb.packaging.config.model.backend.postgres.AbstractPostgres)2 AbstractReplication (com.torodb.packaging.config.model.protocol.mongo.AbstractReplication)2 MongoPasswordConfig (com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig)2