Example usage for java.util.logging Logger info

List of usage examples for java.util.logging Logger info

Introduction

In this page you can find the example usage for java.util.logging Logger info.

Prototype

public void info(Supplier<String> msgSupplier) 

Source Link

Document

Log a INFO message, which is only to be constructed if the logging level is such that the message will actually be logged.

Usage

From source file:sys.core.configuracion.ApplicationHelper.java

public static void cargarLogger() {
    Logger logger = null;
    try {/*from  ww  w.  ja v a  2 s .  co m*/
        RecursosManager recursosManager = (RecursosManager) WebServletContextListener.getApplicationContext()
                .getBean("recursosManager");
        String rutaLog = "";
        {
            ParametroDto p = recursosManager
                    .obtenerParametroPorID(ConstantesCore.Parametro.PARAMETRO_GENERAL_LOG);
            if (p.getValorCadena() != null) {
                rutaLog = p.getValorCadena();
            } else {
                rutaLog = "D:\\log\\FastRemisse";
            }
        }
        System.out.print("= = = = = = = = = =  INICIANDO CONTEXTO FAST REMISSE = = = = = = = = = =  ");
        Properties prop = new Properties();
        prop.setProperty("log4j.rootCategory", "INFO, LOGFILE, CONSOLE");
        prop.setProperty("log4j.appender.CONSOLE", "org.apache.log4j.ConsoleAppender");
        prop.setProperty("log4j.appender.CONSOLE.layout", "org.apache.log4j.PatternLayout");
        prop.setProperty("log4j.appender.CONSOLE.layout.ConversionPattern",
                "[%d{yyyy-MM-dd HH:mm:ss}] - [%5p] (%C{1}.%M:%L) - %m%n");
        prop.setProperty("log4j.appender.LOGFILE", "org.apache.log4j.DailyRollingFileAppender");
        prop.setProperty("log4j.appender.LOGFILE.file", rutaLog);
        prop.setProperty("log4j.appender.LOGFILE.DatePattern", "'.'yyyy-MM-dd'.log'");
        prop.setProperty("log4j.appender.LOGFILE.MaxFileSize", "2048KB");
        prop.setProperty("log4j.appender.archivo.maxFileSize", "20MB");
        prop.setProperty("log4j.appender.archivo.maxBackupIndex", "5");
        prop.setProperty("log4j.appender.LOGFILE.append", "true");
        prop.setProperty("log4j.appender.LOGFILE.layout", "org.apache.log4j.PatternLayout");
        prop.setProperty("log4j.appender.LOGFILE.layout.ConversionPattern",
                "[%d{yyyy-MM-dd HH:mm:ss}] - [%5p] (%C{1}.%M:%L) - %m%n");
        //prop.setProperty("log4j.logger.org.springframework", "INFO, LOGFILE, CONSOLE");
        //prop.setProperty("log4j.logger.org.hibernate", "INFO, LOGFILE, CONSOLE");
        PropertyConfigurator.configure(prop);

        logger.info(
                "= = = = = = = = = =  CONTEXTO FAST REMISSE CARGADO SATISFACTORIAMENTE = = = = = = = = = =  ");
        System.out.print(
                "= = = = = = = = = =  CONTEXTO FAST REMISSE CARGADO SATISFACTORIAMENTE = = = = = = = = = =  ");

    } catch (Exception e) {
        BasicConfigurator.configure();
    }
}

From source file:view.FXApplicationController.java

public void showPopUp(String message) {
    FXPopUp popUp = new FXPopUp();
    popUp.showPopupMessage(message, primaryStage);
    Logger log = Logger.getLogger(this.getClass().getName());
    log.setLevel(Level.ALL);/*from w w  w . j a v a2s  . c  o m*/
    log.info(message);
}

From source file:edu.harvard.iq.dataverse.harvest.client.HarvesterServiceBean.java

/**
 * /*w  ww .j a va 2s. c  o  m*/
 * @param harvestingClient  the harvesting client object
 * @param hdLogger          custom logger (specific to this harvesting run)
 * @param harvestErrorOccurred  have we encountered any errors during harvest?
 * @param failedIdentifiers     Study Identifiers for failed "GetRecord" requests
 */
private List<Long> harvestOAI(DataverseRequest dataverseRequest, HarvestingClient harvestingClient,
        Logger hdLogger, PrintWriter importCleanupLog, MutableBoolean harvestErrorOccurred,
        List<String> failedIdentifiers, List<String> deletedIdentifiers,
        List<Long> harvestedDatasetIdsThisBatch)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {

    logBeginOaiHarvest(hdLogger, harvestingClient);

    List<Long> harvestedDatasetIds = new ArrayList<Long>();
    MutableLong processedSizeThisBatch = new MutableLong(0L);
    OaiHandler oaiHandler;

    try {
        oaiHandler = new OaiHandler(harvestingClient);
    } catch (OaiHandlerException ohe) {
        String errorMessage = "Failed to create OaiHandler for harvesting client " + harvestingClient.getName()
                + "; " + ohe.getMessage();
        hdLogger.log(Level.SEVERE, errorMessage);
        throw new IOException(errorMessage);
    }

    try {
        for (Iterator<Header> idIter = oaiHandler.runListIdentifiers(); idIter.hasNext();) {

            Header h = idIter.next();
            String identifier = h.getIdentifier();

            hdLogger.info("processing identifier: " + identifier);

            MutableBoolean getRecordErrorOccurred = new MutableBoolean(false);

            // Retrieve and process this record with a separate GetRecord call:
            Long datasetId = processRecord(dataverseRequest, hdLogger, importCleanupLog, oaiHandler, identifier,
                    getRecordErrorOccurred, processedSizeThisBatch, deletedIdentifiers);

            hdLogger.info("Total content processed in this batch so far: " + processedSizeThisBatch);
            if (datasetId != null) {
                harvestedDatasetIds.add(datasetId);

                if (harvestedDatasetIdsThisBatch == null) {
                    harvestedDatasetIdsThisBatch = new ArrayList<Long>();
                }
                harvestedDatasetIdsThisBatch.add(datasetId);

            }

            if (getRecordErrorOccurred.booleanValue() == true) {
                failedIdentifiers.add(identifier);
                harvestErrorOccurred.setValue(true);
                //temporary:
                //throw new IOException("Exception occured, stopping harvest");
            }

            // reindexing in batches? - this is from DVN 3; 
            // we may not need it anymore. 
            if (processedSizeThisBatch.longValue() > INDEXING_CONTENT_BATCH_SIZE) {

                hdLogger.log(Level.INFO, "REACHED CONTENT BATCH SIZE LIMIT; calling index ("
                        + harvestedDatasetIdsThisBatch.size() + " datasets in the batch).");
                //indexService.updateIndexList(this.harvestedDatasetIdsThisBatch);
                hdLogger.log(Level.INFO, "REINDEX DONE.");

                processedSizeThisBatch.setValue(0L);
                harvestedDatasetIdsThisBatch = null;
            }

        }
    } catch (OaiHandlerException e) {
        throw new IOException("Failed to run ListIdentifiers: " + e.getMessage());
    }

    logCompletedOaiHarvest(hdLogger, harvestingClient);

    return harvestedDatasetIds;

}

From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java

/**
 * Calls each supplied name individually to Mojang's servers, treating them
 * as previously used names which henceforth were changed. This method is
 * much slower than the other call methods, and should only be used
 * if there is a need to retrieve names which are now changed
 * /*  w  ww.  j ava2 s.c  o  m*/
 * @since 0.1.0
 * @version 0.1.0
 * 
 * @param output Whether or not to print output
 * @param log The {@link Logger} to print to
 * @param doOutput A {@link Predicate} representing when to output a number
 * @return A {@link Map} of supplied names to relevant {@link UserInfo}.
 *         Note that this map will contain the supplied names even if they
 *         are invalid or not actual usernames (in which case, they will
 *         be mapped to {@code null}). Note names that have never been
 *         changed before will be mapped as invalid per this method
 * @throws IOException If there's a problem sending or receiving the request
 * @throws ParseException If the request response cannot be read
 * @throws InterruptedException If the thread is interrupted while sleeping
 */
public Map<String, UserInfo> callFromOldNames(boolean output, Logger log, Predicate<? super Integer> doOutput)
        throws IOException, ParseException, InterruptedException {
    Map<String, UserInfo> back = new HashMap<>();
    int completed = 0;
    int failed = 0;
    for (String s : names) {
        HttpURLConnection connection = UUIDFetcher.createSingleProfileConnection(s);
        if (connection.getResponseCode() == 429 && this.rateLimiting) {
            log.warning("[UUIDFetcher] Rate limit hit! Waiting 10 minutes until continuing conversion...");
            Thread.sleep(TimeUnit.MINUTES.toMillis(10));
            connection = UUIDFetcher.createSingleProfileConnection(s);
        }
        if (connection.getResponseCode() == 200) {
            JSONObject o = (JSONObject) this.jsonParser
                    .parse(new InputStreamReader(connection.getInputStream()));
            back.put(s, new UserInfo((String) o.get("name"), UUIDFetcher.getUUID((String) o.get("id"))));
            completed++;
        } else { //e.g. 400, 204
            if (output) {
                log.warning(String.format("No profile found for '%s', skipping...", s));
            }
            back.put(s, null);
            failed++;
            continue; //nothing can be done with the return
        }
        if (output) {
            int processed = completed + failed;
            if (doOutput.test(processed) || processed == this.names.size()) {
                log.info(String.format("[UUIDFetcher] Progress: %d/%d, %.2f%%, Failed names: %d", processed,
                        this.names.size(), ((double) processed / this.names.size()) * 100D, failed));
            }
        }
    }
    return back;
}

From source file:org.openconcerto.sql.PropsConfiguration.java

protected SQLServer createServer() {
    final String wanAddr = getProperty("server.wan.addr");
    final String wanPort = getProperty("server.wan.port");
    if (!hasWANProperties(wanAddr, wanPort))
        return doCreateServer();

    // if wanAddr is specified, always include it in ID, that way if we connect through the LAN
    // or through the WAN we have the same ID
    final String serverID = "tunnel to " + wanAddr + ":" + wanPort + " then " + getProperty("server.ip");
    final Logger log = Log.get();
    Exception origExn = null;/*from   w w w. ja v a2s. c o m*/
    final SQLServer defaultServer;
    if (!"true".equals(getProperty("server.wan.only"))) {
        try {
            defaultServer = doCreateServer(serverID);
            // works since all ds params are provided by doCreateServer()
            defaultServer.getSystemRoot(getSystemRootName());
            // ok
            log.config("using " + defaultServer);

            return defaultServer;
        } catch (final RuntimeException e) {
            origExn = e;
            // on essaye par SSL
            log.config(e.getLocalizedMessage());
        }
        assert origExn != null;
    }
    this.openSSLConnection(wanAddr, Integer.valueOf(wanPort));
    this.isUsingSSH = true;
    log.info("ssl connection to " + this.conn.getHost() + ":" + this.conn.getPort());
    final int localPort = NetUtils.findFreePort(5436);
    try {
        // TODO add and use server.port
        final String[] serverAndPort = getProperty("server.ip").split(":");
        log.info("ssl tunnel from local port " + localPort + " to remote " + serverAndPort[0] + ":"
                + serverAndPort[1]);
        this.conn.setPortForwardingL(localPort, serverAndPort[0], Integer.valueOf(serverAndPort[1]));
    } catch (final Exception e1) {
        throw new IllegalStateException(
                "Impossible de crer la liaison scurise. Vrifier que le logiciel n'est pas dj lanc.",
                e1);
    }
    final SQLServer serverThruSSL = doCreateServer("localhost:" + localPort, null, serverID);
    try {
        serverThruSSL.getSystemRoot(getSystemRootName());
    } catch (final Exception e) {
        this.closeSSLConnection();
        throw new IllegalStateException("Couldn't connect through SSL : " + e.getLocalizedMessage(), origExn);
    }
    return serverThruSSL;

}

From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java

/**
 * Makes a request to mojang's servers of a sublist of at most 100 player's
 * names. Additionally can provide progress outputs
 * //  w ww .  jav  a  2  s.co  m
 * @since 0.0.1
 * @version 0.1.0
 * 
 * @param output Whether or not to print output
 * @param log The {@link Logger} to print to
 * @param doOutput A {@link Predicate} representing when to output a number
 * @return A {@link Map} of player names to their {@link UUID}s
 * @throws IOException If there's a problem sending or receiving the request
 * @throws ParseException If the request response cannot be read
 * @throws InterruptedException If the thread is interrupted while sleeping
 */
public Map<String, UUID> callWithProgessOutput(boolean output, Logger log, Predicate<? super Integer> doOutput)
        throws IOException, ParseException, InterruptedException {
    //Method start
    Map<String, UUID> uuidMap = new HashMap<>();
    int totalNames = this.names.size();
    int completed = 0;
    int failed = 0;
    int requests = (int) Math.ceil(this.names.size() / UUIDFetcher.PROFILES_PER_REQUEST);
    for (int i = 0; i < requests; i++) {
        List<String> request = names.subList(i * 100, Math.min((i + 1) * 100, this.names.size()));
        String body = JSONArray.toJSONString(request);
        HttpURLConnection connection = UUIDFetcher.createConnection();
        UUIDFetcher.writeBody(connection, body);
        if (connection.getResponseCode() == 429 && this.rateLimiting) {
            log.warning("[UUIDFetcher] Rate limit hit! Waiting 10 minutes until continuing conversion...");
            Thread.sleep(TimeUnit.MINUTES.toMillis(10));
            connection = UUIDFetcher.createConnection();
            UUIDFetcher.writeBody(connection, body);
        }
        JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
        completed += array.size();
        failed += request.size() - array.size();
        for (Object profile : array) {
            JSONObject jsonProfile = (JSONObject) profile;
            UUID uuid = UUIDFetcher.getUUID((String) jsonProfile.get("id"));
            uuidMap.put((String) jsonProfile.get("name"), uuid);
        }
        if (output) {
            int processed = completed + failed;
            if (doOutput.test(processed) || processed == totalNames) {
                log.info(String.format("[UUIDFetcher] Progress: %d/%d, %.2f%%, Failed names: %d", processed,
                        totalNames, ((double) processed / totalNames) * 100D, failed));
            }
        }
    }
    return uuidMap;
}

From source file:me.realized.tm.utilities.profile.UUIDFetcher.java

/**
 * Makes a request to mojang's servers of a sublist of at most 100 player's
 * names. Additionally can provide progress outputs
 *
 * @param output   Whether or not to print output
 * @param log      The {@link Logger} to print to
 * @param doOutput A {@link Predicate} representing when to output a number
 * @return A {@link Map} of player names to their {@link UUID}s
 * @throws IOException          If there's a problem sending or receiving the request
 * @throws ParseException       If the request response cannot be read
 * @throws InterruptedException If the thread is interrupted while sleeping
 * @version 0.1.0//from   ww w .j  a va2  s . com
 * @since 0.0.1
 */
public Map<String, UUID> callWithProgressOutput(boolean output, Logger log, Predicate<? super Integer> doOutput)
        throws IOException, ParseException, InterruptedException {
    Map<String, UUID> uuidMap = new HashMap<>();
    int totalNames = this.names.size();
    int completed = 0;
    int failed = 0;
    int requests = (int) Math.ceil(this.names.size() / UUIDFetcher.PROFILES_PER_REQUEST);
    for (int i = 0; i < requests; i++) {
        List<String> request = names.subList(i * 100, Math.min((i + 1) * 100, this.names.size()));
        String body = JSONArray.toJSONString(request);
        HttpURLConnection connection = UUIDFetcher.createConnection();
        UUIDFetcher.writeBody(connection, body);
        if (connection.getResponseCode() == 429 && this.rateLimiting) {
            String out = "[UUIDFetcher] Rate limit hit! Waiting 10 minutes until continuing conversion...";
            if (log != null) {
                log.warning(out);
            } else {
                Bukkit.getLogger().warning(out);
            }
            Thread.sleep(TimeUnit.MINUTES.toMillis(10));
            connection = UUIDFetcher.createConnection();
            UUIDFetcher.writeBody(connection, body);
        }

        JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
        completed += array.size();
        failed += request.size() - array.size();

        for (Object profile : array) {
            JSONObject jsonProfile = (JSONObject) profile;
            UUID uuid = UUIDFetcher.getUUID((String) jsonProfile.get("id"));
            uuidMap.put((String) jsonProfile.get("name"), uuid);
        }

        if (output) {
            int processed = completed + failed;
            if (doOutput.apply(processed) || processed == totalNames) {
                if (log != null) {
                    log.info(String.format("[UUIDFetcher] Progress: %d/%d, %.2f%%, Failed names: %d", processed,
                            totalNames, ((double) processed / totalNames) * 100D, failed));
                }
            }
        }
    }
    return uuidMap;
}

From source file:org.cloudifysource.usm.UniversalServiceManagerBean.java

private RollingFileAppenderTailer createFileTailerTask() {
    final String filePattern = createUniqueFileName() + "(" + OUTPUT_FILE_NAME_SUFFIX + "|"
            + ERROR_FILE_NAME_SUFFFIX + ")";

    final Logger outputLogger = Logger.getLogger(getUsmLifecycleBean().getOutputReaderLoggerName());
    final Logger errorLogger = Logger.getLogger(getUsmLifecycleBean().getErrorReaderLoggerName());

    logger.info("Creating tailer for dir: " + getLogsDir() + ", with regex: " + filePattern);
    final RollingFileAppenderTailer tailer = new RollingFileAppenderTailer(getLogsDir(), filePattern,
            new LineHandler() {

                @Override//from ww w  .j a va2s .  co  m
                public void handleLine(final String fileName, final String line) {
                    //
                    if (fileName.endsWith(".out")) {
                        outputLogger.info(line);
                    } else {
                        errorLogger.info(line);
                    }

                }
            });
    return tailer;
}

From source file:org.blazr.extrastorage.ExtraStorage.java

@SuppressWarnings("deprecation")
public void onEnable() {
    compilationSuccess();//from w  w  w .  j  a v  a  2s  .  c  o m
    Logger log = getLogger();
    try {
        plugin = this;
        e_file = getFile();
        PluginManager pm = getServer().getPluginManager();
        EventHandlers eh = new EventHandlers(this);
        pm.registerEvents(eh, this);
        File defaultDir = getDataFolder().getCanonicalFile();
        if (!defaultDir.exists()) {
            defaultDir.mkdir();
            File newDataLoc = new File(defaultDir.getCanonicalPath() + File.separator + "data");
            newDataLoc.mkdir();
            saveResource("LICENSE.txt", true);
        } else {
            File newDataLoc = new File(defaultDir.getCanonicalPath() + File.separator + "data");
            if (!newDataLoc.exists()) {
                newDataLoc.mkdir();
                saveResource("LICENSE.txt", true);
            }
        }
        File oldFile1 = new File(defaultDir.getCanonicalPath() + File.separator + "data" + File.separator
                + "LastUpdateCheckTime");
        File oldFile2 = new File(
                defaultDir.getCanonicalPath() + File.separator + "data" + File.separator + "LatestVersion");
        if (oldFile1.exists()) {
            oldFile1.delete();
        }
        if (oldFile2.exists()) {
            oldFile2.delete();
        }
        for (Player player : getServer().getOnlinePlayers()) {
            if (!getConfig().getList("world-blacklist.worlds").contains(player.getWorld().getName())) {
                IO.loadBackpackFromDiskOnLogin(player, this);
            }
        }
        log.info("Enabled successfully.");
        FileConfiguration conf = getConfig();
        conf.options().copyDefaults(true);
        if (conf.get("Comaptibility-Settings.Vanish-No-Packet.no-item-pickup-when-vanished") != null) {
            conf.set("Comaptibility-Settings", null);
        }
        if (!conf.isSet("display-prefix")) {
            conf.set("display-prefix", true);
        }
        if (conf.getBoolean("display-prefix")) {
            PNC = ChatColor.YELLOW + "[ExtraStorage]";
        } else {
            PNC = "";
        }
        List<String> blacklist = conf.getStringList("blacklisted-items");
        boolean isOldStyle = false;
        for (String item : blacklist) {
            if (isNumeric(item)) {
                isOldStyle = true;
            }
        }
        if (isOldStyle) {
            List<String> newList = new ArrayList<String>();
            for (String item : blacklist) {
                if (isNumeric(item)) {
                    int itemCode = Integer.parseInt(item);

                    ItemStack tempIS = new ItemStack(itemCode);
                    newList.add(tempIS.getType().toString());
                } else {
                    newList.add(item);
                }
            }
            conf.set("blacklisted-items", newList);
        }
        if (!conf.isSet("update-check"))
            conf.set("update-check", true);
        if (!conf.isSet("use-Minecraft-UUID"))
            conf.set("use-Minecraft-UUID", true);
        boolean update_check = conf.getBoolean("update-check");
        mojangUUID = conf.getBoolean("use-Minecraft-UUID");
        loadUUID(this);
        saveConfig();

        try {
            Metrics metrics = new Metrics(this);
            metrics.start();
        } catch (IOException e) {
            // Failed to submit the stats :-(
        }

        if (update_check) {
            Updater up = new Updater(this, 56836, getFile(), Updater.UpdateType.NO_DOWNLOAD, false);
            if (up.getResult() == UpdateResult.UPDATE_AVAILABLE) {
                getLogger().info("A new version of the plugin is available !");
                updatenotice = true;
                updatenoticemessage = up.getLatestName().toLowerCase().replace("extrastorage", "");
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        log.severe("Error in onEnable! Plugin not enabled properly!");
    }

}

From source file:hudson.cli.CLI.java

public static int _main(String[] _args) throws Exception {
    List<String> args = Arrays.asList(_args);
    PrivateKeyProvider provider = new PrivateKeyProvider();
    boolean sshAuthRequestedExplicitly = false;
    String httpProxy = null;//from w ww  . j a va  2  s .  c om

    String url = System.getenv("JENKINS_URL");

    if (url == null)
        url = System.getenv("HUDSON_URL");

    boolean tryLoadPKey = true;

    Mode mode = null;

    String user = null;
    String auth = null;

    String userIdEnv = System.getenv("JENKINS_USER_ID");
    String tokenEnv = System.getenv("JENKINS_API_TOKEN");

    boolean strictHostKey = false;

    while (!args.isEmpty()) {
        String head = args.get(0);
        if (head.equals("-version")) {
            System.out.println("Version: " + computeVersion());
            return 0;
        }
        if (head.equals("-http")) {
            if (mode != null) {
                printUsage("-http clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.HTTP;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-ssh")) {
            if (mode != null) {
                printUsage("-ssh clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.SSH;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-remoting")) {
            if (mode != null) {
                printUsage("-remoting clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.REMOTING;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-s") && args.size() >= 2) {
            url = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-noCertificateCheck")) {
            LOGGER.info("Skipping HTTPS certificate checks altogether. Note that this is not secure at all.");
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
            // bypass host name check, too.
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-noKeyAuth")) {
            tryLoadPKey = false;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-i") && args.size() >= 2) {
            File f = new File(args.get(1));
            if (!f.exists()) {
                printUsage(Messages.CLI_NoSuchFileExists(f));
                return -1;
            }

            provider.readFrom(f);

            args = args.subList(2, args.size());
            sshAuthRequestedExplicitly = true;
            continue;
        }
        if (head.equals("-strictHostKey")) {
            strictHostKey = true;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-user") && args.size() >= 2) {
            user = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-auth") && args.size() >= 2) {
            auth = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-p") && args.size() >= 2) {
            httpProxy = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-logger") && args.size() >= 2) {
            Level level = parse(args.get(1));
            for (Handler h : Logger.getLogger("").getHandlers()) {
                h.setLevel(level);
            }
            for (Logger logger : new Logger[] { LOGGER, FullDuplexHttpStream.LOGGER, PlainCLIProtocol.LOGGER,
                    Logger.getLogger("org.apache.sshd") }) { // perhaps also Channel
                logger.setLevel(level);
            }
            args = args.subList(2, args.size());
            continue;
        }
        break;
    }

    if (url == null) {
        printUsage(Messages.CLI_NoURL());
        return -1;
    }

    if (auth == null) {
        // -auth option not set
        if (StringUtils.isNotBlank(userIdEnv) && StringUtils.isNotBlank(tokenEnv)) {
            auth = StringUtils.defaultString(userIdEnv).concat(":").concat(StringUtils.defaultString(tokenEnv));
        } else if (StringUtils.isNotBlank(userIdEnv) || StringUtils.isNotBlank(tokenEnv)) {
            printUsage(Messages.CLI_BadAuth());
            return -1;
        } // Otherwise, none credentials were set

    }

    if (!url.endsWith("/")) {
        url += '/';
    }

    if (args.isEmpty())
        args = Arrays.asList("help"); // default to help

    if (tryLoadPKey && !provider.hasKeys())
        provider.readFromDefaultLocations();

    if (mode == null) {
        mode = Mode.HTTP;
    }

    LOGGER.log(FINE, "using connection mode {0}", mode);

    if (user != null && auth != null) {
        LOGGER.warning("-user and -auth are mutually exclusive");
    }

    if (mode == Mode.SSH) {
        if (user == null) {
            // TODO SshCliAuthenticator already autodetects the user based on public key; why cannot AsynchronousCommand.getCurrentUser do the same?
            LOGGER.warning("-user required when using -ssh");
            return -1;
        }
        return SSHCLI.sshConnection(url, user, args, provider, strictHostKey);
    }

    if (strictHostKey) {
        LOGGER.warning("-strictHostKey meaningful only with -ssh");
    }

    if (user != null) {
        LOGGER.warning("Warning: -user ignored unless using -ssh");
    }

    CLIConnectionFactory factory = new CLIConnectionFactory().url(url).httpsProxyTunnel(httpProxy);
    String userInfo = new URL(url).getUserInfo();
    if (userInfo != null) {
        factory = factory.basicAuth(userInfo);
    } else if (auth != null) {
        factory = factory.basicAuth(
                auth.startsWith("@") ? FileUtils.readFileToString(new File(auth.substring(1))).trim() : auth);
    }

    if (mode == Mode.HTTP) {
        return plainHttpConnection(url, args, factory);
    }

    CLI cli = factory.connect();
    try {
        if (provider.hasKeys()) {
            try {
                // TODO: server verification
                cli.authenticate(provider.getKeys());
            } catch (IllegalStateException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.warning("The server doesn't support public key authentication");
                    return -1;
                }
            } catch (UnsupportedOperationException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.warning("The server doesn't support public key authentication");
                    return -1;
                }
            } catch (GeneralSecurityException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.log(WARNING, null, e);
                    return -1;
                }
                LOGGER.warning("Failed to authenticate with your SSH keys. Proceeding as anonymous");
                LOGGER.log(FINE, null, e);
            }
        }

        // execute the command
        // Arrays.asList is not serializable --- see 6835580
        args = new ArrayList<String>(args);
        return cli.execute(args, System.in, System.out, System.err);
    } finally {
        cli.close();
    }
}