Example usage for java.util.logging Logger setLevel

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

Introduction

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

Prototype

public void setLevel(Level newLevel) throws SecurityException 

Source Link

Document

Set the log level specifying which message levels will be logged by this logger.

Usage

From source file:org.azrul.langmera.DecisionService.java

public static void main(String[] args) throws IOException {
    ConfigurationProvider config = null;
    ConfigFilesProvider configFilesProvider = () -> Arrays.asList(Paths.get("config.properties"));
    if (args.length <= 0) {
        ConfigurationSource source = new ClasspathConfigurationSource(configFilesProvider);
        config = new ConfigurationProviderBuilder().withConfigurationSource(source).build();
    } else {//from   ww  w  .  ja v  a2  s . c o m
        ConfigurationSource source = new FilesConfigurationSource(configFilesProvider);
        Environment environment = new ImmutableEnvironment(args[0]);
        config = new ConfigurationProviderBuilder().withConfigurationSource(source).withEnvironment(environment)
                .build();

    }
    Logger logger = null;
    if (config.getProperty("log.file", String.class).isEmpty() == false) {
        FileHandler logHandler = new FileHandler(config.getProperty("log.file", String.class),
                config.getProperty("log.sizePerFile", Integer.class) * 1024 * 1024,
                config.getProperty("log.maxFileCount", Integer.class), true);
        logHandler.setFormatter(new SimpleFormatter());
        logHandler.setLevel(Level.INFO);

        Logger rootLogger = Logger.getLogger("");
        rootLogger.removeHandler(rootLogger.getHandlers()[0]);
        logHandler.setLevel(Level.parse(config.getProperty("log.level", String.class)));
        rootLogger.setLevel(Level.parse(config.getProperty("log.level", String.class)));
        rootLogger.addHandler(logHandler);

        logger = rootLogger;
    } else {
        logger = Logger.getGlobal();
    }

    VertxOptions options = new VertxOptions();
    options.setMaxEventLoopExecuteTime(Long.MAX_VALUE);
    options.setWorkerPoolSize(config.getProperty("workerPoolSize", Integer.class));
    options.setEventLoopPoolSize(40);

    Vertx vertx = Vertx.vertx(options);
    vertx.deployVerticle(new DecisionService(logger, config));
    vertx.deployVerticle(new SaveToDB(logger, config));

}

From source file:de.burlov.amazon.s3.dirsync.CLI.java

/**
 * @param args/*from www . j  av a 2s. c  o m*/
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Logger.getLogger("").setLevel(Level.OFF);
    Logger deLogger = Logger.getLogger("de");
    deLogger.setLevel(Level.INFO);
    Handler handler = new ConsoleHandler();
    handler.setFormatter(new VerySimpleFormatter());
    deLogger.addHandler(handler);
    deLogger.setUseParentHandlers(false);
    //      if (true)
    //      {
    //         LogFactory.getLog(CLI.class).error("test msg", new Exception("test extception"));
    //         return;
    //      }
    Options opts = new Options();
    OptionGroup gr = new OptionGroup();

    /*
     * Befehlsgruppe initialisieren
     */
    gr = new OptionGroup();
    gr.setRequired(true);
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download changed or new files").create(CMD_UPDATE));
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download directory snapshot").create(CMD_SNAPSHOT));
    gr.addOption(OptionBuilder.withDescription("Delete remote folder").create(CMD_DELETE_DIR));
    gr.addOption(OptionBuilder.withDescription("Delete a bucket").create(CMD_DELETE_BUCKET));
    gr.addOption(OptionBuilder.create(CMD_HELP));
    gr.addOption(OptionBuilder.create(CMD_VERSION));
    gr.addOption(OptionBuilder.withDescription("Prints summary for stored data").create(CMD_SUMMARY));
    gr.addOption(OptionBuilder.withDescription("Clean up orphaned objekts").create(CMD_CLEANUP));
    gr.addOption(OptionBuilder.withDescription("Changes encryption password").withArgName("new password")
            .hasArg().create(CMD_CHANGE_PASSWORD));
    gr.addOption(OptionBuilder.withDescription("Lists all buckets").create(CMD_LIST_BUCKETS));
    gr.addOption(OptionBuilder.withDescription("Lists raw objects in a bucket").create(CMD_LIST_BUCKET));
    gr.addOption(OptionBuilder.withDescription("Lists files in remote folder").create(CMD_LIST_DIR));
    opts.addOptionGroup(gr);
    /*
     * Parametergruppe initialisieren
     */
    opts.addOption(OptionBuilder.withArgName("key").isRequired(false).hasArg().withDescription("S3 access key")
            .create(OPT_S3S_KEY));
    opts.addOption(OptionBuilder.withArgName("secret").isRequired(false).hasArg()
            .withDescription("Secret key for S3 account").create(OPT_S3S_SECRET));
    opts.addOption(OptionBuilder.withArgName("bucket").isRequired(false).hasArg().withDescription(
            "Optional bucket name for storage. If not specified then an unique bucket name will be generated")
            .create(OPT_BUCKET));
    // opts.addOption(OptionBuilder.withArgName("US|EU").hasArg().
    // withDescription(
    // "Where the new bucket should be created. Default US").create(
    // OPT_LOCATION));
    opts.addOption(OptionBuilder.withArgName("path").isRequired(false).hasArg()
            .withDescription("Local directory path").create(OPT_LOCAL_DIR));
    opts.addOption(OptionBuilder.withArgName("name").isRequired(false).hasArg()
            .withDescription("Remote directory name").create(OPT_REMOTE_DIR));
    opts.addOption(OptionBuilder.withArgName("password").isRequired(false).hasArg()
            .withDescription("Encryption password").create(OPT_ENC_PASSWORD));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs()
            .withDescription("Comma separated exclude file patterns like '*.tmp,*/dir/*.tmp'")
            .create(OPT_EXCLUDE_PATTERNS));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs().withDescription(
            "Comma separated include patterns like '*.java'. If not specified, then all files in specified local directory will be included")
            .create(OPT_INCLUDE_PATTERNS));

    if (args.length == 0) {
        printUsage(opts);
        return;
    }

    CommandLine cmd = null;
    try {
        cmd = new GnuParser().parse(opts, args);
        if (cmd.hasOption(CMD_HELP)) {
            printUsage(opts);
            return;
        }
        if (cmd.hasOption(CMD_VERSION)) {
            System.out.println("s3dirsync version " + Version.CURRENT_VERSION);
            return;
        }
        String awsKey = cmd.getOptionValue(OPT_S3S_KEY);
        String awsSecret = cmd.getOptionValue(OPT_S3S_SECRET);
        String bucket = cmd.getOptionValue(OPT_BUCKET);
        String bucketLocation = cmd.getOptionValue(OPT_LOCATION);
        String localDir = cmd.getOptionValue(OPT_LOCAL_DIR);
        String remoteDir = cmd.getOptionValue(OPT_REMOTE_DIR);
        String password = cmd.getOptionValue(OPT_ENC_PASSWORD);
        String exclude = cmd.getOptionValue(OPT_EXCLUDE_PATTERNS);
        String include = cmd.getOptionValue(OPT_INCLUDE_PATTERNS);

        if (StringUtils.isBlank(awsKey) || StringUtils.isBlank(awsSecret)) {
            System.out.println("S3 account data required");
            return;
        }

        if (StringUtils.isBlank(bucket)) {
            bucket = awsKey + ".dirsync";
        }

        if (cmd.hasOption(CMD_DELETE_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            int deleted = S3Utils.deleteBucket(awsKey, awsSecret, bucket);
            System.out.println("Deleted objects: " + deleted);
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKETS)) {
            for (String str : S3Utils.listBuckets(awsKey, awsSecret)) {
                System.out.println(str);
            }
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            for (String str : S3Utils.listObjects(awsKey, awsSecret, bucket)) {
                System.out.println(str);
            }
            return;
        }
        if (StringUtils.isBlank(password)) {
            System.out.println("Encryption password required");
            return;
        }
        char[] psw = password.toCharArray();
        DirSync ds = new DirSync(awsKey, awsSecret, bucket, bucketLocation, psw);
        ds.setExcludePatterns(parseSubargumenths(exclude));
        ds.setIncludePatterns(parseSubargumenths(include));
        if (cmd.hasOption(CMD_SUMMARY)) {
            ds.printStorageSummary();
            return;
        }
        if (StringUtils.isBlank(remoteDir)) {
            System.out.println("Remote directory name required");
            return;
        }
        if (cmd.hasOption(CMD_DELETE_DIR)) {
            ds.deleteFolder(remoteDir);
            return;
        }
        if (cmd.hasOption(CMD_LIST_DIR)) {
            Folder folder = ds.getFolder(remoteDir);
            if (folder == null) {
                System.out.println("No such folder found: " + remoteDir);
                return;
            }
            for (Map.Entry<String, FileInfo> entry : folder.getIndexData().entrySet()) {
                System.out.println(entry.getKey() + " ("
                        + FileUtils.byteCountToDisplaySize(entry.getValue().getLength()) + ")");
            }
            return;
        }
        if (cmd.hasOption(CMD_CLEANUP)) {
            ds.cleanUp();
            return;
        }
        if (cmd.hasOption(CMD_CHANGE_PASSWORD)) {
            String newPassword = cmd.getOptionValue(CMD_CHANGE_PASSWORD);
            if (StringUtils.isBlank(newPassword)) {
                System.out.println("new password required");
                return;
            }
            char[] chars = newPassword.toCharArray();
            ds.changePassword(chars);
            newPassword = null;
            Arrays.fill(chars, ' ');
            return;
        }
        if (StringUtils.isBlank(localDir)) {
            System.out.println(OPT_LOCAL_DIR + " argument required");
            return;
        }
        String direction = "";
        boolean up = false;
        boolean snapshot = false;
        if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_UPDATE))) {
            direction = cmd.getOptionValue(CMD_UPDATE);
        } else if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_SNAPSHOT))) {
            direction = cmd.getOptionValue(CMD_SNAPSHOT);
            snapshot = true;
        }
        if (StringUtils.isBlank(direction)) {
            System.out.println("Operation direction required");
            return;
        }
        up = StringUtils.equalsIgnoreCase(OPT_UP, direction);
        File baseDir = new File(localDir);
        if (!baseDir.exists() && !baseDir.mkdirs()) {
            System.out.println("Invalid local directory: " + baseDir.getAbsolutePath());
            return;
        }
        ds.syncFolder(baseDir, remoteDir, up, snapshot);

    } catch (DirSyncException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printUsage(opts);

    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:primarydatamanager.PrimaryDataManager.java

public static void main(String[] args) {
    // setup logging
    try {//from  w  w  w  .ja v  a2  s  .com
        // Get the default Logger
        Logger mainLogger = Logger.getLogger("");
        mainLogger.setLevel(Level.FINEST);

        Handler consoleHandler = mainLogger.getHandlers()[0];
        consoleHandler.setLevel(Level.FINEST);
        consoleHandler.setFormatter(new VerySimpleFormatter());

        // Add a file handler
        new File("log").mkdir();
        Handler fileHandler = new FileHandler("log/datamanager.log", 50000, 2, true);
        fileHandler.setLevel(Level.INFO);
        mainLogger.addHandler(fileHandler);
    } catch (IOException exc) {
        System.out.println("Can't create log file");
        exc.printStackTrace();
    }

    // Start the update
    if (args.length == 0) {
        System.out.println("USAGE: PrimaryDataManager [-forceCompleteUpdate [channel{;channel}]] groups...");
        System.exit(1);
    } else {
        try {
            PrimaryDataManager manager = new PrimaryDataManager(new File("."));
            ArrayList<String> groupNames = new ArrayList<String>();
            for (int i = 0; i < args.length; i++) {
                if (args[i].equalsIgnoreCase("-forceCompleteUpdate")) {
                    if ((i + 1) >= args.length) {
                        System.out.println("You have to specify a colon separated "
                                + "list of channels after -forceCompleteUpdate");
                        System.exit(1);
                    } else {
                        i++;
                        StringTokenizer tokenizer = new StringTokenizer(args[i], ":");
                        while (tokenizer.hasMoreTokens()) {
                            manager.forceCompleteUpdateFor(tokenizer.nextToken());
                        }
                    }
                } else {
                    final String[] groups = args[i].split(",");
                    groupNames.addAll(Arrays.asList(groups));
                }
            }

            if (groupNames.size() == 0) {
                System.out.println("Please specify at least one channel group");
                System.exit(-1);
            }

            if (!manager.doesPreparedExist()) {
                System.out.println(
                        "The prepared directory is missing, this directory is very important and shouldn't "
                                + "be deleted, because this leeds to massiv problems.");
                System.exit(-1);
            }

            if (!manager.createLockFile()) {
                System.out.println("The PrimaryDataManager is already running.");
                System.exit(-1);
            }

            String[] groupNamesArr = new String[groupNames.size()];
            groupNames.toArray(groupNamesArr);
            manager.setGroupNames(groupNamesArr);

            manager.updateRawDataDir();

            manager.deleteLockFile();

            // Exit with error code 2 if some day programs were put into quarantine
            if (manager.mRawDataProcessor.getQuarantineCount() != 0) {
                System.exit(2);
            }
        } catch (PreparationException exc) {
            exc.printStackTrace();
            System.exit(1);
        }
    }
}

From source file:pl.otros.logview.gui.LogViewMainFrame.java

/**
 * @param args porgram CLI arguments/*  w w w  .  j  av  a  2  s  .  c  om*/
 * @throws InitializationException
 * @throws InvocationTargetException
 * @throws InterruptedException
 */
public static void main(final String[] args)
        throws InitializationException, InterruptedException, InvocationTargetException {
    if (args.length > 0 && "-batch".equals(args[0])) {
        try {
            String[] batchArgs = new String[args.length - 1];
            System.arraycopy(args, 1, batchArgs, 0, batchArgs.length);
            BatchProcessor.main(batchArgs);
        } catch (IOException e) {
            System.err.println("Error during batch processing: " + e.getMessage());
            e.printStackTrace();
        } catch (ConfigurationException e) {
            System.err.println("Error during batch processing: " + e.getMessage());
            e.printStackTrace();
        }
        return;
    }
    SingleInstanceRequestResponseDelegate singleInstanceRequestResponseDelegate = SingleInstanceRequestResponseDelegate
            .getInstance();
    singleInstance = SingleInstance.request("OtrosLogViewer", singleInstanceRequestResponseDelegate,
            singleInstanceRequestResponseDelegate, args);
    if (singleInstance == null) {
        LOGGER.info("OtrosLogViewer is already running, params send using requestAction");
        System.exit(0);
    }
    GuiJulHandler handler = new GuiJulHandler();
    handler.setLevel(Level.ALL);
    Logger olvLogger = Logger.getLogger("pl.otros.logview");
    olvLogger.setLevel(Level.ALL);
    olvLogger.addHandler(handler);
    LOGGER.info("Starting application");
    OtrosSplash.setMessage("Starting application");
    OtrosSplash.setMessage("Loading configuration");
    final XMLConfiguration c = getConfiguration("config.xml");
    if (!c.containsKey(ConfKeys.UUID)) {
        c.setProperty(ConfKeys.UUID, UUID.randomUUID().toString());
    }
    IconsLoader.loadIcons();
    OtrosSplash.setMessage("Loading icons");
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            try {
                OtrosSplash.setMessage("Loading L&F");
                String lookAndFeel = c.getString("lookAndFeel",
                        "com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
                LOGGER.config("Initializing look and feelL: " + lookAndFeel);
                PlasticLookAndFeel.setTabStyle(Plastic3DLookAndFeel.TAB_STYLE_METAL_VALUE);
                UIManager.setLookAndFeel(lookAndFeel);
            } catch (Throwable e1) {
                LOGGER.warning("Cannot initialize LookAndFeel: " + e1.getMessage());
            }
            try {
                final DataConfiguration c1 = new OtrosConfiguration(c);
                final LogViewMainFrame mf = new LogViewMainFrame(c1);
                // mf.exitAction was instantiated in the constructor (previous line)
                // Not sure retrieving this from most appropriate Apache config
                // object.
                mf.exitAction.setConfirm(c.getBoolean("generalBehavior.confirmExit", true));
                /* TODO:  Implement User Preferences screen or checkbox on exit widget
                 * that will update the same config object something like:
                 *     c.setProperty("generalBehavior.confirmExit", newValue);
                 */
                mf.addComponentListener(new ComponentAdapter() {
                    @Override
                    public void componentResized(ComponentEvent e) {
                        c.setProperty("gui.state", mf.getExtendedState());
                        if (mf.getExtendedState() == Frame.NORMAL) {
                            c.setProperty("gui.width", mf.getWidth());
                            c.setProperty("gui.height", mf.getHeight());
                        }
                    }

                    @Override
                    public void componentMoved(ComponentEvent e) {
                        c.setProperty("gui.location.x", mf.getLocation().x);
                        c.setProperty("gui.location.y", mf.getLocation().y);
                    }
                });
                mf.addWindowListener(mf.exitAction);
                SingleInstanceRequestResponseDelegate.openFilesFromStartArgs(mf.otrosApplication,
                        Arrays.asList(args), mf.otrosApplication.getAppProperties().getCurrentDir());
            } catch (InitializationException e) {
                LOGGER.log(Level.SEVERE, "Cannot initialize main frame", e);
            }
        }
    });
}

From source file:NewApplication.java

/**
 * @param args the command line arguments
 *///from w  w w .j  a  v a 2  s  .co  m
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(NewApplication.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewApplication.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewApplication.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewApplication.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    }
    //</editor-fold>

    Logger log = Logger.getLogger("NewApplication");
    try {
        FileInputStream fis = new FileInputStream("p.properties");
        LogManager.getLogManager().readConfiguration(fis);
        log.setLevel(Level.FINE);
        log.addHandler(new java.util.logging.ConsoleHandler());
        log.setUseParentHandlers(false);

        log.info("starting NewApplication");
        fis.close();
    } catch (Exception e) {
    }
    ;

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewApplication().setVisible(true);
        }
    });
}

From source file:com.spinn3r.api.Main.java

public static void main(String[] args) throws Exception {

    // NOTE this could be cleaned up to pass the values into the config
    // object directly.

    // parse out propeties.

    String api = null;//w  w  w. jav a  2 s . com

    for (int i = 0; i < args.length; ++i) {
        String v = args[i];

        if (v.startsWith("--api")) {
            api = getOpt(v);
        }

    }

    if (api == null)
        api = "permalink";

    // First. Determine which API you'd like to use.

    long after = -1;
    Format format = Format.PROTOSTREAM;
    String vendor = null;
    String remoteFilter = null;
    Long sleep_duration = null;
    boolean skip_description = false;
    String host = "api.spinn3r.com";

    for (int i = 0; i < args.length; ++i) {

        String v = args[i];

        if (v.startsWith("--vendor")) {
            vendor = getOpt(v);
            continue;
        }

        if (v.startsWith("--filter")) {
            filter = getOpt(v);
            continue;
        }

        if (v.startsWith("--remote-filter")) {
            remoteFilter = getOpt(v);
            continue;
        }

        if (v.startsWith("--show_results")) {
            show_results = Integer.parseInt(getOpt(v));
            continue;
        }

        /*
         * The code for the --afterTimestamp must come
         * before the code for --after because --afterTimestamp
         * also matches startsWith("after");
         */
        if (v.startsWith("--afterTimestamp")) {
            after = Long.parseLong(getOpt(v));
            continue;
        }

        if (v.startsWith("--after")) {
            after = getOptAsTimeInMillis(v);
            continue;
        }

        /*
         * The code for the --beforeTimestamp must come
         * before the code for --before because --beforeTimestamp
         * also matches startsWith("before");
         */
        if (v.startsWith("--beforeTimestamp")) {
            before = Long.parseLong(getOpt(v));
            continue;
        }

        if (v.startsWith("--before")) {
            before = getOptAsTimeInMillis(v);
            continue;
        }

        if (v.startsWith("--range")) {
            range = Long.parseLong(getOpt(v));
            continue;
        }

        if (v.startsWith("--recover")) {
            restore = true;
            continue;
        }

        if (v.startsWith("--sleep_duration")) {
            sleep_duration = Long.parseLong(getOpt(v));
            continue;
        }

        if (v.startsWith("--save=")) {
            save = getOpt(v);
            continue;
        }

        if (v.startsWith("--save_method=")) {
            save_method = getOpt(v);
            continue;
        }

        if (v.startsWith("--skip_description=")) {
            skip_description = Boolean.parseBoolean(getOpt(v));
            continue;
        }

        if (v.startsWith("--save_compressed=")) {
            saveCompressed = Boolean.parseBoolean(getOpt(v));
            continue;
        }

        if (v.startsWith("--timing")) {
            timing = "true".equals(getOpt(v));
            continue;
        }

        if (v.startsWith("--debug")) {
            logLevel = Level.FINE;
            debugLogFilePath = getOpt(v);
            continue;
        }

        /*
         * if ( v.startsWith( "--spam_probability" ) ) {
         * config.setSpamProbability( Double.parseDouble( getOpt( v ) ) );
         * continue; }
         */

        if (v.startsWith("--dump_fields=")) {
            dumpFields = Boolean.parseBoolean(getOpt(v));
            continue;
        }

        if (v.startsWith("--dump=")) {
            dump = Boolean.parseBoolean(getOpt(v));
            continue;
        }

        if (v.startsWith("--csv=")) {
            csv = Boolean.parseBoolean(getOpt(v));
            continue;
        }

        if (v.startsWith("--memory")) {

            System.out.printf("max memory: %s\n", Runtime.getRuntime().maxMemory());
            System.exit(0);
        }

        if (v.startsWith("--host")) {
            host = getOpt(v);
            continue;
        }

        if (v.startsWith("--enable3")) {
            // is now default
            continue;
        }

        if (v.startsWith("com.spinn3r"))
            continue;

        if (v.startsWith("--api"))
            continue;

        // That's an unknown command line option. Exit.
        System.err.printf("Unknown command line option: %s\n", v);
        syntax();
        System.exit(1);

    }

    /*
     * Set the log level
     */
    Logger anonymousLogger = Logger.getAnonymousLogger();
    anonymousLogger.setLevel(logLevel);
    if (debugLogFilePath != null) {
        anonymousLogger.addHandler(new FileHandler(debugLogFilePath));
    }

    Factory factory = new Factory();
    String restoreURL = null;

    if (save != null && restore) {
        File savedir = new File(save);
        Collection<File> logFiles = getLogFiles(savedir);
        PermalinkLogReaderAdapter adapter = getRestoreURLS(logFiles);

        restoreURL = adapter.getLastUrl();
        long ctr = adapter.getLastCtr();

        for (File file : logFiles) {
            if (!file.delete())
                throw new IOException("Failed to delete " + file.toString());
        }

        factory.enableLogging(savedir, 1000000);
        if (restoreURL != null) {
            factory.enableRestart(ctr, restoreURL);
        }
        logManager = factory.getInjector().getInstance(TransactionHistoryManager.class);
    } else {
        logManager = factory.getInjector().getInstance(TransactionHistoryManager.class);
    }

    Config<? extends BaseResult> config = null;
    BaseClient<? extends BaseResult> client = null;

    if (api.startsWith("feed")) {
        config = new FeedConfig();
        client = new FeedClient();
    } else if (api.startsWith("comment")) {
        config = new CommentConfig();
        client = new CommentClient();
    } else {
        config = new PermalinkConfig();
        client = new PermalinkClient(
                restoreURL != null ? ImmutableList.of(restoreURL) : Collections.<String>emptyList());
    }

    config.setCommandLine(StringUtils.join(args, " "));

    config.setApi(api);
    config.setFormat(format);
    config.setVendor(vendor);
    config.setHost(host);
    config.setFilter(remoteFilter);
    config.setSkipDescription(skip_description);
    if (sleep_duration != null)
        client.setSleepDuration(sleep_duration);

    // assert that we have all required options.

    if (config.getVendor() == null) {
        syntax();
        System.exit(1);
    }

    long maxMemory = Runtime.getRuntime().maxMemory();
    long requiredMemory = (save == null) ? PARSE_REQUIRED_MEMORY : SAVE_REQUIRED_MEMORY;

    if (maxMemory < requiredMemory) {

        System.out.printf("ERROR: Reference client requires at least 2GB of memory.\n");
        System.out.printf("\n");
        System.out.printf("Now running with: %s vs %s required\n", maxMemory, requiredMemory);
        System.out.printf("\n");
        System.out.printf("Add -Xmx%dM to your command line and run again.\n", requiredMemory / (1024 * 1024));

        System.exit(1);

    }

    // use defaults

    System.out.println("Using vendor: " + config.getVendor());
    System.out.println("Using api:    " + api);

    if (after > -1)
        System.out.printf("After: %s (%s)\n", ISO8601DateParser.toString(Config.timestampToDate(after)), after);

    if (before > -1)
        System.out.printf("Before: %s (%s)\n", ISO8601DateParser.toString(Config.timestampToDate(before)),
                before);

    System.out.println("Saving results to disk: " + save);

    // Fetch for the last 5 minutes and then try to get up to date. In
    // production you'd want to call setFirstRequestURL from the
    // getLastRequestURL returned from fetch() below

    if (after == -1) {
        after = Config.millisecondsToTimestamp(System.currentTimeMillis());
        after = after - INTERVAL;
    }

    config.setAfterTimestamp(after);

    new Main().exec(client, config);

}

From source file:edu.usc.cssl.tacit.classify.naivebayes.services.Vectors2Classify.java

public static ArrayList<String> main(String[] args) throws bsh.EvalError, java.io.IOException {
    result.clear();/*from w  ww.j  av  a2s.  com*/
    classifierTrainerStrings = new ArrayList<String>();
    ReportOptions = new boolean[][] { { false, false, false, false }, { false, false, false, false },
            { false, false, false, false } };

    double pvalue = 0;
    // Process the command-line options
    CommandOption.setSummary(Vectors2Classify.class,
            "A tool for training, saving and printing diagnostics from a classifier on vectors.");
    CommandOption.process(Vectors2Classify.class, args);

    // handle default trainer here for now; default argument processing
    // doesn't work
    if (!trainerConstructor.wasInvoked()) {
        classifierTrainerStrings.add("new NaiveBayesTrainer()");
    }

    if (!report.wasInvoked()) {
        ReportOptions = new boolean[][] { { true, false, false, false }, { true, false, true, false },
                { false, false, false, false } };
        //report.postParsing(null); // force postprocessing of default value

    }

    int verbosity = verbosityOption.value;

    Logger rootLogger = ((MalletLogger) progressLogger).getRootLogger();

    if (verbosityOption.wasInvoked()) {
        rootLogger.setLevel(MalletLogger.LoggingLevels[verbosity]);
    }

    if (noOverwriteProgressMessagesOption.value == false) {
        // install special formatting for progress messages
        // find console handler on root logger; change formatter to one
        // that knows about progress messages
        Handler[] handlers = rootLogger.getHandlers();
        for (int i = 0; i < handlers.length; i++) {
            if (handlers[i] instanceof ConsoleHandler) {
                handlers[i].setFormatter(new ProgressMessageLogFormatter());
            }
        }
    }

    boolean separateIlists = testFile.wasInvoked() || trainingFile.wasInvoked() || validationFile.wasInvoked();
    InstanceList ilist = null;
    InstanceList testFileIlist = null;
    InstanceList trainingFileIlist = null;
    InstanceList validationFileIlist = null;

    if (!separateIlists) { // normal case, --input-file specified
        // Read in the InstanceList, from stdin if the input filename is
        // "-".
        ilist = InstanceList.load(new File(inputFile.value));
        //ilist = new InstanceList(ilist.getAlphabet(), ilist.getAlphabet());
    } else { // user specified separate files for testing and training sets.
        trainingFileIlist = InstanceList.load(new File(trainingFile.value));
        logger.info("Training vectors loaded from " + trainingFile.value);

        if (testFile.wasInvoked()) {
            testFileIlist = InstanceList.load(new File(testFile.value));
            logger.info("Testing vectors loaded from " + testFile.value);

            if (!testFileIlist.getPipe().alphabetsMatch(trainingFileIlist.getPipe())) {
                throw new RuntimeException(trainingFileIlist.getPipe().getDataAlphabet() + "\n"
                        + testFileIlist.getPipe().getDataAlphabet() + "\n"
                        + trainingFileIlist.getPipe().getTargetAlphabet() + "\n"
                        + testFileIlist.getPipe().getTargetAlphabet() + "\n"
                        + "Training and testing alphabets don't match!\n");
            }
        }

        if (validationFile.wasInvoked()) {
            validationFileIlist = InstanceList.load(new File(validationFile.value));
            logger.info("validation vectors loaded from " + validationFile.value);
            if (!validationFileIlist.getPipe().alphabetsMatch(trainingFileIlist.getPipe())) {
                throw new RuntimeException(trainingFileIlist.getPipe().getDataAlphabet() + "\n"
                        + validationFileIlist.getPipe().getDataAlphabet() + "\n"
                        + trainingFileIlist.getPipe().getTargetAlphabet() + "\n"
                        + validationFileIlist.getPipe().getTargetAlphabet() + "\n"
                        + "Training and validation alphabets don't match!\n");
            }
        } else {
            validationFileIlist = new InstanceList(new cc.mallet.pipe.Noop());
        }

    }

    if (crossValidation.wasInvoked() && trainingProportionOption.wasInvoked()) {
        logger.warning(
                "Both --cross-validation and --training-portion were invoked.  Using cross validation with "
                        + crossValidation.value + " folds.");
    }
    if (crossValidation.wasInvoked() && validationProportionOption.wasInvoked()) {
        logger.warning(
                "Both --cross-validation and --validation-portion were invoked.  Using cross validation with "
                        + crossValidation.value + " folds.");
    }
    if (crossValidation.wasInvoked() && numTrialsOption.wasInvoked()) {
        logger.warning("Both --cross-validation and --num-trials were invoked.  Using cross validation with "
                + crossValidation.value + " folds.");
    }

    int numTrials;
    if (crossValidation.wasInvoked()) {
        numTrials = crossValidation.value;
    } else {
        numTrials = numTrialsOption.value;
    }

    Random r = randomSeedOption.wasInvoked() ? new Random(randomSeedOption.value) : new Random();

    int numTrainers = classifierTrainerStrings.size();

    double trainAccuracy[][] = new double[numTrainers][numTrials];
    double testAccuracy[][] = new double[numTrainers][numTrials];
    double validationAccuracy[][] = new double[numTrainers][numTrials];

    String trainConfusionMatrix[][] = new String[numTrainers][numTrials];
    String testConfusionMatrix[][] = new String[numTrainers][numTrials];
    String validationConfusionMatrix[][] = new String[numTrainers][numTrials];

    double t = trainingProportionOption.value;
    double v = validationProportionOption.value;

    if (!separateIlists) {
        if (crossValidation.wasInvoked()) {
            logger.info("Cross-validation folds = " + crossValidation.value);
        } else {
            logger.info("Training portion = " + t);
            logger.info(" Unlabeled training sub-portion = " + unlabeledProportionOption.value);
            logger.info("Validation portion = " + v);
            logger.info("Testing portion = " + (1 - v - t));
        }
    }

    // for (int i=0; i<3; i++){
    // for (int j=0; j<4; j++){
    // System.out.print(" " + ReportOptions[i][j]);
    // }
    // System.out.println();
    // }

    CrossValidationIterator cvIter;
    if (crossValidation.wasInvoked()) {
        if (crossValidation.value < 2) {
            throw new RuntimeException(
                    "At least two folds (set with --cross-validation) are required for cross validation");
        }
        //System.out.println("Alphabets : "+ ilist.getDataAlphabet() +":"+ ilist.getTargetAlphabet());
        cvIter = new CrossValidationIterator(ilist, crossValidation.value, r);
    } else {
        cvIter = null;
    }

    String[] trainerNames = new String[numTrainers];
    for (int trialIndex = 0; trialIndex < numTrials; trialIndex++) {
        System.out.println("\n-------------------- Trial " + trialIndex + "  --------------------\n");
        InstanceList[] ilists;
        BitSet unlabeledIndices = null;
        if (!separateIlists) {
            if (crossValidation.wasInvoked()) {
                InstanceList[] cvSplit = cvIter.next();
                ilists = new InstanceList[3];
                ilists[0] = cvSplit[0];
                ilists[1] = cvSplit[1];
                ilists[2] = cvSplit[0].cloneEmpty();
            } else {
                ilists = ilist.split(r, new double[] { t, 1 - t - v, v });
            }
        } else {
            ilists = new InstanceList[3];
            ilists[0] = trainingFileIlist;
            ilists[1] = testFileIlist;
            ilists[2] = validationFileIlist;
        }

        if (unlabeledProportionOption.value > 0)
            unlabeledIndices = new cc.mallet.util.Randoms(r.nextInt()).nextBitSet(ilists[0].size(),
                    unlabeledProportionOption.value);

        // InfoGain ig = new InfoGain (ilists[0]);
        // int igl = Math.min (10, ig.numLocations());
        // for (int i = 0; i < igl; i++)
        // System.out.println
        // ("InfoGain["+ig.getObjectAtRank(i)+"]="+ig.getValueAtRank(i));
        // ig.print();

        // FeatureSelection selectedFeatures = new FeatureSelection (ig,
        // 8000);
        // ilists[0].setFeatureSelection (selectedFeatures);
        // OddsRatioFeatureInducer orfi = new OddsRatioFeatureInducer
        // (ilists[0]);
        // orfi.induceFeatures (ilists[0], false, true);

        // System.out.println
        // ("Training with "+ilists[0].size()+" instances");
        long time[] = new long[numTrainers];
        for (int c = 0; c < numTrainers; c++) {
            time[c] = System.currentTimeMillis();
            ClassifierTrainer trainer = getTrainer(classifierTrainerStrings.get(c));
            trainer.setValidationInstances(ilists[2]);
            // ConsoleView.writeInConsole("Trial " + trialIndex + " Training " + trainer + " with " + ilists[0].size() + " instances");
            ConsoleView.printlInConsoleln("Training " + trainer + " with " + ilists[0].size() + " instances");
            if (unlabeledProportionOption.value > 0)
                ilists[0].hideSomeLabels(unlabeledIndices);
            Classifier classifier = trainer.train(ilists[0]);
            if (unlabeledProportionOption.value > 0)
                ilists[0].unhideAllLabels();

            //ConsoleView.writeInConsole("Trial " + trialIndex + " Training " + trainer.toString() + " finished");
            ConsoleView.printlInConsoleln("Training " + trainer.toString() + " finished");
            time[c] = System.currentTimeMillis() - time[c];
            Trial trainTrial = new Trial(classifier, ilists[0]);
            // assert (ilists[1].size() > 0);
            Trial testTrial = new Trial(classifier, ilists[1]);
            Trial validationTrial = new Trial(classifier, ilists[2]);

            // gdruck - only perform evaluation if requested in report
            // options
            if (ReportOptions[ReportOption.train][ReportOption.confusion] && ilists[0].size() > 0)
                trainConfusionMatrix[c][trialIndex] = new ConfusionMatrix(trainTrial).toString();
            if (ReportOptions[ReportOption.test][ReportOption.confusion] && ilists[1].size() > 0)
                testConfusionMatrix[c][trialIndex] = new ConfusionMatrix(testTrial).toString();
            if (ReportOptions[ReportOption.validation][ReportOption.confusion] && ilists[2].size() > 0)
                validationConfusionMatrix[c][trialIndex] = new ConfusionMatrix(validationTrial).toString();

            // gdruck - only perform evaluation if requested in report
            // options
            if (ReportOptions[ReportOption.train][ReportOption.accuracy])
                trainAccuracy[c][trialIndex] = trainTrial.getAccuracy();
            if (ReportOptions[ReportOption.test][ReportOption.accuracy])
                testAccuracy[c][trialIndex] = testTrial.getAccuracy();
            if (ReportOptions[ReportOption.validation][ReportOption.accuracy])
                validationAccuracy[c][trialIndex] = validationTrial.getAccuracy();

            if (outputFile.wasInvoked()) {
                String filename = outputFile.value;
                if (numTrainers > 1)
                    filename = filename + trainer.toString();
                if (numTrials > 1)
                    filename = filename + ".trial" + trialIndex;
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
                    oos.writeObject(classifier);
                    oos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new IllegalArgumentException("Couldn't write classifier to filename " + filename);
                }
            }

            // New Reporting

            // raw output
            if (ReportOptions[ReportOption.train][ReportOption.raw]) {
                System.out.println("Trial " + trialIndex + " Trainer " + trainer.toString());
                System.out.println(" Raw Training Data");
                printTrialClassification(trainTrial);
            }

            if (ReportOptions[ReportOption.test][ReportOption.raw]) {
                System.out.println("Trial " + trialIndex + " Trainer " + trainer.toString());
                System.out.println(" Raw Testing Data");
                printTrialClassification(testTrial);
                //System.out.println("Report Option :"+(ReportOptions[ReportOption.test][ReportOption.raw]));
            }

            if (ReportOptions[ReportOption.validation][ReportOption.raw]) {
                System.out.println("Trial " + trialIndex + " Trainer " + trainer.toString());
                System.out.println(" Raw Validation Data");
                printTrialClassification(validationTrial);
            }
            System.out.println(
                    "Bino test vars size " + ilists[1].size() + "and accuracy + " + testTrial.getAccuracy()
                            + " then success " + (int) testTrial.getAccuracy() * ilists[1].size());
            BinomialTest binomtest = new BinomialTest();
            double p = 0.5;

            // train
            if (ReportOptions[ReportOption.train][ReportOption.confusion]) {
                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer "    + trainer.toString() + " Training Data Confusion Matrix");
                ConsoleView.printlInConsoleln(trainer.toString() + " Training Data Confusion Matrix");
                if (ilists[0].size() > 0)
                    ConsoleView.printlInConsoleln(trainConfusionMatrix[c][trialIndex]);
            }

            if (ReportOptions[ReportOption.train][ReportOption.accuracy]) {
                pvalue = binomtest.binomialTest(ilists[0].size(),
                        (int) (trainTrial.getAccuracy() * ilists[0].size()), p,
                        AlternativeHypothesis.TWO_SIDED);
                if (pvalue != 0) {
                    if (pvalue > 0.5)
                        pvalue = Math.abs(pvalue - 1);
                    ConsoleView.printlInConsoleln("Binomial 2-Sided P value = " + pvalue + "\n");
                }

                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " training data accuracy= " + trainAccuracy[c][trialIndex]);
                ConsoleView.printlInConsoleln(
                        trainer.toString() + " training data accuracy= " + trainAccuracy[c][trialIndex]);
            }

            if (ReportOptions[ReportOption.train][ReportOption.f1]) {
                String label = ReportOptionArgs[ReportOption.train][ReportOption.f1];
                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer "+ trainer.toString() + " training data F1(" + label + ") = " + trainTrial.getF1(label));
                ConsoleView.printlInConsoleln(
                        trainer.toString() + " training data F1(" + label + ") = " + trainTrial.getF1(label));
            }

            // validation
            if (ReportOptions[ReportOption.validation][ReportOption.confusion]) {
                //   ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " Validation Data Confusion Matrix");
                ConsoleView.printlInConsoleln(trainer.toString() + " Validation Data Confusion Matrix");
                if (ilists[2].size() > 0)
                    ConsoleView.printlInConsoleln(validationConfusionMatrix[c][trialIndex]);
            }

            if (ReportOptions[ReportOption.validation][ReportOption.accuracy]) {
                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " validation data accuracy= " + validationAccuracy[c][trialIndex]);
                ConsoleView.printlInConsoleln(
                        trainer.toString() + " validation data accuracy= " + validationAccuracy[c][trialIndex]);
            }

            if (ReportOptions[ReportOption.validation][ReportOption.f1]) {
                String label = ReportOptionArgs[ReportOption.validation][ReportOption.f1];
                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " validation data F1(" + label + ") = " + validationTrial.getF1(label));
                ConsoleView.printlInConsoleln(trainer.toString() + " validation data F1(" + label + ") = "
                        + validationTrial.getF1(label));
            }

            // test
            if (ReportOptions[ReportOption.test][ReportOption.confusion]) {
                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " Test Data Confusion Matrix");
                ConsoleView.printlInConsoleln(trainer.toString() + " Test Data Confusion Matrix");
                if (ilists[1].size() > 0)
                    ConsoleView.printlInConsoleln(testConfusionMatrix[c][trialIndex]);
            }

            if (ReportOptions[ReportOption.test][ReportOption.accuracy]) {
                pvalue = binomtest.binomialTest(ilists[1].size(),
                        (int) (testTrial.getAccuracy() * ilists[1].size()), 0.5,
                        AlternativeHypothesis.TWO_SIDED);
                if (pvalue != 0) {
                    if (pvalue > 0.5)
                        pvalue = Math.abs(pvalue - 1);
                    ConsoleView.printlInConsoleln("Binomial 2-Sided P value = " + pvalue + " \n");
                }

                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " test data accuracy= " + testAccuracy[c][trialIndex]);
                ConsoleView.printlInConsoleln(
                        trainer.toString() + " test data accuracy= " + testAccuracy[c][trialIndex]);
            }

            if (ReportOptions[ReportOption.test][ReportOption.f1]) {
                String label = ReportOptionArgs[ReportOption.test][ReportOption.f1];
                //ConsoleView.writeInConsole("Trial " + trialIndex + " Trainer " + trainer.toString() + " test data F1(" + label + ") = " + testTrial.getF1(label));
                ConsoleView.printlInConsoleln(
                        trainer.toString() + " test data F1(" + label + ") = " + testTrial.getF1(label));
            }

            if (trialIndex == 0)
                trainerNames[c] = trainer.toString();

        } // end for each trainer
    } // end for each trial

    // New reporting
    // "[train|test|validation]:[accuracy|f1|confusion|raw]"
    for (int c = 0; c < numTrainers; c++) {
        ConsoleView.printlInConsole("\n" + trainerNames[c].toString() + "\n");
        if (ReportOptions[ReportOption.train][ReportOption.accuracy]) {
            /*ConsoleView.printlInConsoleln("Summary. train accuracy mean = "
                  + MatrixOps.mean(trainAccuracy[c]) + " stddev = "
                  + MatrixOps.stddev(trainAccuracy[c]) + " stderr = "
                  + MatrixOps.stderr(trainAccuracy[c])); */

            String trainResult = "";
            if (pvalue != 0)
                trainResult += "Summary. train accuracy = " + MatrixOps.mean(trainAccuracy[c]);
            else
                trainResult += "Summary. train accuracy = " + MatrixOps.mean(trainAccuracy[c]);

            if (numTrials > 1) {
                trainResult += " stddev = " + MatrixOps.stddev(trainAccuracy[c]) + " stderr = "
                        + MatrixOps.stderr(trainAccuracy[c]);
            }
            ConsoleView.printlInConsoleln(trainResult);

        }

        if (ReportOptions[ReportOption.validation][ReportOption.accuracy]) {
            /*
            ConsoleView.printlInConsoleln("Summary. validation accuracy mean = "
                  + MatrixOps.mean(validationAccuracy[c]) + " stddev = "
                  + MatrixOps.stddev(validationAccuracy[c])
                  + " stderr = "
                  + MatrixOps.stderr(validationAccuracy[c]));*/

            String validationResult = "";
            if (pvalue != 0)
                validationResult += "Summary. validation accuracy = " + MatrixOps.mean(validationAccuracy[c]);
            else
                validationResult += "Summary. validation accuracy = " + MatrixOps.mean(validationAccuracy[c]);

            if (numTrials > 1) {
                validationResult += " stddev = " + MatrixOps.stddev(validationAccuracy[c]) + " stderr = "
                        + MatrixOps.stderr(validationAccuracy[c]);
            }
            ConsoleView.printlInConsoleln(validationResult);

        }

        if (ReportOptions[ReportOption.test][ReportOption.accuracy]) {
            String testResult = "";
            if (pvalue != 0)
                testResult += "Summary. test accuracy = " + MatrixOps.mean(testAccuracy[c])
                        + " Binomial 2-Sided Pvalue = " + pvalue;
            else
                testResult += "Summary. test accuracy = " + MatrixOps.mean(testAccuracy[c])
                        + " Pvalue < 10^(-1022)\n";

            if (numTrials > 1) {
                testResult += " stddev = " + MatrixOps.stddev(testAccuracy[c]) + " stderr = "
                        + MatrixOps.stderr(testAccuracy[c]);
            }
            ConsoleView.printlInConsoleln(testResult);

            /*
            if (pvalue != 0)
               ConsoleView.printlInConsoleln("Summary. test accuracy mean = "
             + MatrixOps.mean(testAccuracy[c]) + " stddev = "
             + MatrixOps.stddev(testAccuracy[c]) + " stderr = "
             + MatrixOps.stderr(testAccuracy[c]) + " pvalue = "
             + pvalue);
            else
               ConsoleView.printlInConsoleln("Summary. test accuracy mean = "
             + MatrixOps.mean(testAccuracy[c]) + " stddev = "
             + MatrixOps.stddev(testAccuracy[c]) + " stderr = "
             + MatrixOps.stderr(testAccuracy[c])
             + " P value < 10^(-1022)\n"); */
        }

        // If we are testing the classifier with two folders, result will be
        // empty - no report is generated
        if (result.isEmpty()) {
            if (pvalue != 0)
                result.add("Summary. test accuracy = " + MatrixOps.mean(testAccuracy[c])
                        + " Binomial 2-Sided  Pvalue = " + pvalue);
            else
                result.add("Summary. test accuracy = " + MatrixOps.mean(testAccuracy[c])
                        + " Pvalue < 10^(-1022)\n");

            if (numTrials > 1) {
                result.add(" stddev = " + MatrixOps.stddev(testAccuracy[c]) + " stderr = "
                        + MatrixOps.stderr(testAccuracy[c]));
            }
        }
    } // end for each trainer

    return result;
}

From source file:net.sf.freecol.FreeCol.java

/**
 * The entrypoint./*from  w w  w . ja va 2  s . com*/
 *
 * @param args The command-line arguments.
 * @throws IOException 
 * @throws FontFormatException 
 */
public static void main(String[] args) throws FontFormatException, IOException {
    freeColRevision = FREECOL_VERSION;
    JarURLConnection juc;
    try {
        juc = getJarURLConnection(FreeCol.class);
    } catch (IOException ioe) {
        juc = null;
        System.err.println("Unable to open class jar: " + ioe.getMessage());
    }
    if (juc != null) {
        try {
            String revision = readVersion(juc);
            if (revision != null) {
                freeColRevision += " (Revision: " + revision + ")";
            }
        } catch (Exception e) {
            System.err.println("Unable to load Manifest: " + e.getMessage());
        }
        try {
            splashStream = getDefaultSplashStream(juc);
        } catch (Exception e) {
            System.err.println("Unable to open default splash: " + e.getMessage());
        }
    }

    // Java bug #7075600 causes BR#2554.  The workaround is to set
    // the following property.  Remove if/when they fix Java.
    System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");

    // We can not even emit localized error messages until we find
    // the data directory, which might have been specified on the
    // command line.
    String dataDirectoryArg = findArg("--freecol-data", args);
    String err = FreeColDirectories.setDataDirectory(dataDirectoryArg);
    if (err != null)
        fatal(err); // This must not fail.

    // Now we have the data directory, establish the base locale.
    // Beware, the locale may change!
    String localeArg = findArg("--default-locale", args);
    if (localeArg == null) {
        locale = Locale.getDefault();
    } else {
        int index = localeArg.indexOf('.'); // Strip encoding if present
        if (index > 0)
            localeArg = localeArg.substring(0, index);
        locale = Messages.getLocale(localeArg);
    }
    Messages.loadMessageBundle(locale);

    // Now that we can emit error messages, parse the other
    // command line arguments.
    handleArgs(args);

    // Do the potentially fatal system checks as early as possible.
    if (javaCheck && JAVA_VERSION_MIN.compareTo(JAVA_VERSION) > 0) {
        fatal(StringTemplate.template("main.javaVersion").addName("%version%", JAVA_VERSION)
                .addName("%minVersion%", JAVA_VERSION_MIN));
    }
    if (memoryCheck && MEMORY_MAX < MEMORY_MIN * 1000000) {
        fatal(StringTemplate.template("main.memory").addAmount("%memory%", MEMORY_MAX).addAmount("%minMemory%",
                MEMORY_MIN));
    }

    // Having parsed the command line args, we know where the user
    // directories should be, so we can set up the rest of the
    // file/directory structure.
    String userMsg = FreeColDirectories.setUserDirectories();

    // Now we have the log file path, start logging.
    final Logger baseLogger = Logger.getLogger("");
    final Handler[] handlers = baseLogger.getHandlers();
    for (Handler handler : handlers) {
        baseLogger.removeHandler(handler);
    }
    String logFile = FreeColDirectories.getLogFilePath();
    try {
        baseLogger.addHandler(new DefaultHandler(consoleLogging, logFile));
        Logger freecolLogger = Logger.getLogger("net.sf.freecol");
        freecolLogger.setLevel(logLevel);
    } catch (FreeColException e) {
        System.err.println("Logging initialization failure: " + e.getMessage());
        e.printStackTrace();
    }
    Thread.setDefaultUncaughtExceptionHandler((Thread thread, Throwable e) -> {
        baseLogger.log(Level.WARNING, "Uncaught exception from thread: " + thread, e);
    });

    // Now we can find the client options, allow the options
    // setting to override the locale, if no command line option
    // had been specified.
    // We have users whose machines default to Finnish but play
    // FreeCol in English.
    // If the user has selected automatic language selection, do
    // nothing, since we have already set up the default locale.
    if (localeArg == null) {
        String clientLanguage = ClientOptions.getLanguageOption();
        Locale clientLocale;
        if (clientLanguage != null && !Messages.AUTOMATIC.equalsIgnoreCase(clientLanguage)
                && (clientLocale = Messages.getLocale(clientLanguage)) != locale) {
            locale = clientLocale;
            Messages.loadMessageBundle(locale);
            logger.info("Loaded messages for " + locale);
        }
    }

    // Now we have the user mods directory and the locale is now
    // stable, load the mods and their messages.
    Mods.loadMods();
    Messages.loadModMessageBundle(locale);

    // Report on where we are.
    if (userMsg != null)
        logger.info(Messages.message(userMsg));
    logger.info(getConfiguration().toString());

    // Ready to specialize into client or server.
    if (standAloneServer) {
        startServer();
    } else {
        startClient(userMsg);
    }
    startYourAddition();
}

From source file:org.wor.drawca.DrawCAMain.java

/**
 * Main function which start drawing the cellular automata.
 *
 * @param args Command line arguments.//  w w w.  j a  va 2s .  c om
 */
public static void main(final String[] args) {
    final Logger log = Logger.getGlobal();
    LogManager.getLogManager().reset();

    Options options = new Options();
    boolean hasArgs = true;

    // TODO: show defaults in option description
    options.addOption("h", "help", !hasArgs, "Show this help message");
    options.addOption("pci", "perclickiteration", !hasArgs, "Generate one line per mouse click");

    options.addOption("v", "verbose", hasArgs, "Verbosity level [-1,7]");
    options.addOption("r", "rule", hasArgs, "Rule number to use 0-255");
    options.addOption("wh", "windowheigth", hasArgs, "Draw window height");
    options.addOption("ww", "windowwidth", hasArgs, "Draw window width");
    options.addOption("x", "xscalefactor", hasArgs, "X Scale factor");
    options.addOption("y", "yscalefactor", hasArgs, "Y scale factor");
    options.addOption("f", "initline", hasArgs, "File name with Initial line.");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        e.printStackTrace();
        showHelp(options);
        return;
    }

    // Options without an argument
    if (cmd.hasOption("h")) {
        showHelp(options);
        return;
    }
    final boolean perClickIteration = cmd.hasOption("pci");

    // Options with an argument
    final int verbosityLevel = Integer.parseInt(cmd.getOptionValue('v', "0"));
    final int rule = Integer.parseInt(cmd.getOptionValue('r', "110"));
    final int windowHeigth = Integer.parseInt(cmd.getOptionValue("wh", "300"));
    final int windowWidth = Integer.parseInt(cmd.getOptionValue("ww", "400"));
    final float xScaleFactor = Float.parseFloat(cmd.getOptionValue('x', "2.0"));
    final float yScaleFactor = Float.parseFloat(cmd.getOptionValue('y', "2.0"));
    final String initLineFile = cmd.getOptionValue('f', "");

    final Level logLevel = VERBOSITY_MAP.get(verbosityLevel);
    log.setLevel(logLevel);

    // Set log handler
    Handler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(logLevel);
    log.addHandler(consoleHandler);

    log.info("Log level set to: " + log.getLevel());

    // Read initial line from a file
    String initLine = "";
    if (initLineFile.length() > 0) {
        Path initLineFilePath = FileSystems.getDefault().getPath(initLineFile);
        try {
            // Should be string of ones and zeros only
            initLine = new String(Files.readAllBytes(initLineFilePath), "UTF-8");
        } catch (IOException e) {
            System.err.format("IOException: %s\n", e);
            return;
        }
    }

    SwingUtilities.invokeLater(new RunGUI(windowWidth, windowHeigth, xScaleFactor, yScaleFactor, rule, initLine,
            perClickIteration));
}

From source file:tvbrowser.TVBrowser.java

/**
 * Entry point of the application/* w  ww.  j av a  2 s .  c o m*/
 * @param args The arguments given in the command line.
 */
public static void main(String[] args) {
    // Read the command line parameters
    parseCommandline(args);

    try {
        Toolkit.getDefaultToolkit().setDynamicLayout(
                (Boolean) Toolkit.getDefaultToolkit().getDesktopProperty("awt.dynamicLayoutSupported"));
    } catch (Exception e) {
        e.printStackTrace();
    }

    mLocalizer = util.ui.Localizer.getLocalizerFor(TVBrowser.class);

    // Check whether the TV-Browser was started in the right directory
    if (!new File("imgs").exists()) {
        String msg = "Please start TV-Browser in the TV-Browser directory!";
        if (mLocalizer != null) {
            msg = mLocalizer.msg("error.2", "Please start TV-Browser in the TV-Browser directory!");
        }
        JOptionPane.showMessageDialog(null, msg);
        System.exit(1);
    }

    if (mIsTransportable) {
        System.getProperties().remove("propertiesfile");
    }

    // setup logging

    // Get the default Logger
    Logger mainLogger = Logger.getLogger("");

    // Use a even simpler Formatter for console logging
    mainLogger.getHandlers()[0].setFormatter(createFormatter());

    if (mIsTransportable) {
        File settingsDir = new File("settings");
        try {
            File test = File.createTempFile("write", "test", settingsDir);
            test.delete();
        } catch (IOException e) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e1) {
                //ignore
            }

            JTextArea area = new JTextArea(mLocalizer.msg("error.noWriteRightsText",
                    "You are using the transportable version of TV-Browser but you have no writing rights in the settings directory:\n\n{0}'\n\nTV-Browser will be closed.",
                    settingsDir.getAbsolutePath()));
            area.setFont(new JLabel().getFont());
            area.setFont(area.getFont().deriveFont((float) 14).deriveFont(Font.BOLD));
            area.setLineWrap(true);
            area.setWrapStyleWord(true);
            area.setPreferredSize(new Dimension(500, 100));
            area.setEditable(false);
            area.setBorder(null);
            area.setOpaque(false);

            JOptionPane.showMessageDialog(null, area,
                    mLocalizer.msg("error.noWriteRightsTitle", "No write rights in settings directory"),
                    JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
    }

    // Load the settings
    Settings.loadSettings();
    Locale.setDefault(new Locale(Settings.propLanguage.getString(), Settings.propCountry.getString()));

    if (Settings.propFirstStartDate.getDate() == null) {
        Settings.propFirstStartDate.setDate(Date.getCurrentDate());
    }

    if (!createLockFile()) {
        updateLookAndFeel();
        showTVBrowserIsAlreadyRunningMessageBox();
    }

    String logDirectory = Settings.propLogdirectory.getString();
    if (logDirectory != null) {
        try {
            File logDir = new File(logDirectory);
            logDir.mkdirs();
            mainLogger.addHandler(
                    new FileLoggingHandler(logDir.getAbsolutePath() + "/tvbrowser.log", createFormatter()));
        } catch (IOException exc) {
            String msg = mLocalizer.msg("error.4", "Can't create log file.");
            ErrorHandler.handle(msg, exc);
        }
    } else {
        // if no logging is configured, show WARNING or worse for normal usage, show everything for unstable versions
        if (TVBrowser.isStable()) {
            mainLogger.setLevel(Level.WARNING);
        }
    }

    // log warning for OpenJDK users
    if (!isJavaImplementationSupported()) {
        mainLogger.warning(SUN_JAVA_WARNING);
    }

    //Update plugin on version change
    if (Settings.propTVBrowserVersion.getVersion() != null
            && VERSION.compareTo(Settings.propTVBrowserVersion.getVersion()) > 0) {
        updateLookAndFeel();
        updatePluginsOnVersionChange();
    }

    // Capture unhandled exceptions
    //System.setErr(new PrintStream(new MonitoringErrorStream()));

    String timezone = Settings.propTimezone.getString();
    if (timezone != null) {
        TimeZone.setDefault(TimeZone.getTimeZone(timezone));
    }
    mLog.info("Using timezone " + TimeZone.getDefault().getDisplayName());

    // refresh the localizers because we know the language now
    Localizer.emptyLocalizerCache();
    mLocalizer = Localizer.getLocalizerFor(TVBrowser.class);
    ProgramInfo.resetLocalizer();
    ReminderPlugin.resetLocalizer();
    Date.resetLocalizer();
    ProgramFieldType.resetLocalizer();

    // Set the proxy settings
    updateProxySettings();

    // Set the String to use for indicating the user agent in http requests
    System.setProperty("http.agent", MAINWINDOW_TITLE);

    Version tmpVer = Settings.propTVBrowserVersion.getVersion();
    final Version currentVersion = tmpVer != null
            ? new Version(tmpVer.getMajor(), tmpVer.getMinor(),
                    Settings.propTVBrowserVersionIsStable.getBoolean())
            : tmpVer;

    /*TODO Create an update service for installed TV data services that doesn't
     *     work with TV-Browser 3.0 and updates for them are known.
     */
    if (!isTransportable() && Launch.isOsWindowsNtBranch() && currentVersion != null
            && currentVersion.compareTo(new Version(3, 0, true)) < 0) {
        String tvDataDir = Settings.propTVDataDirectory.getString().replace("/", File.separator);

        if (!tvDataDir.startsWith(System.getenv("appdata"))) {
            StringBuilder oldDefaultTvDataDir = new StringBuilder(System.getProperty("user.home"))
                    .append(File.separator).append("TV-Browser").append(File.separator).append("tvdata");

            if (oldDefaultTvDataDir.toString().equals(tvDataDir)) {
                Settings.propTVDataDirectory.setString(Settings.propTVDataDirectory.getDefault());
            }
        }
    }

    Settings.propTVBrowserVersion.setVersion(VERSION);
    Settings.propTVBrowserVersionIsStable.setBoolean(VERSION.isStable());

    final Splash splash;

    if (mShowSplashScreen && Settings.propSplashShow.getBoolean()) {
        splash = new SplashScreen(Settings.propSplashImage.getString(), Settings.propSplashTextPosX.getInt(),
                Settings.propSplashTextPosY.getInt(), Settings.propSplashForegroundColor.getColor());
    } else {
        splash = new DummySplash();
    }
    splash.showSplash();

    /* Initialize the MarkedProgramsList */
    MarkedProgramsList.getInstance();

    /*Maybe there are tvdataservices to install (.jar.inst files)*/
    PluginLoader.getInstance().installPendingPlugins();

    PluginLoader.getInstance().loadAllPlugins();

    mLog.info("Loading TV listings service...");
    splash.setMessage(mLocalizer.msg("splash.dataService", "Loading TV listings service..."));
    TvDataServiceProxyManager.getInstance().init();
    ChannelList.createForTvBrowserStart();

    ChannelList.initSubscribedChannels();

    if (!lookAndFeelInitialized) {
        mLog.info("Loading Look&Feel...");
        splash.setMessage(mLocalizer.msg("splash.laf", "Loading look and feel..."));

        updateLookAndFeel();
    }

    mLog.info("Loading plugins...");
    splash.setMessage(mLocalizer.msg("splash.plugins", "Loading plugins..."));
    try {
        PluginProxyManager.getInstance().init();
    } catch (TvBrowserException exc) {
        ErrorHandler.handle(exc);
    }

    splash.setMessage(mLocalizer.msg("splash.tvData", "Checking TV database..."));

    mLog.info("Checking TV listings inventory...");
    TvDataBase.getInstance().checkTvDataInventory();

    mLog.info("Starting up...");
    splash.setMessage(mLocalizer.msg("splash.ui", "Starting up..."));

    Toolkit.getDefaultToolkit().getSystemEventQueue().push(new TextComponentPopupEventQueue());

    // Init the UI
    final boolean fStartMinimized = Settings.propMinimizeAfterStartup.getBoolean() || mMinimized;
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            initUi(splash, fStartMinimized);

            new Thread("Start finished callbacks") {
                public void run() {
                    setPriority(Thread.MIN_PRIORITY);

                    mLog.info("Deleting expired TV listings...");
                    TvDataBase.getInstance().deleteExpiredFiles(1, false);

                    // first reset "starting" flag of mainframe
                    mainFrame.handleTvBrowserStartFinished();

                    // initialize program info for fast reaction to program table click
                    ProgramInfo.getInstance().handleTvBrowserStartFinished();

                    // load reminders and favorites
                    ReminderPlugin.getInstance().handleTvBrowserStartFinished();
                    FavoritesPlugin.getInstance().handleTvBrowserStartFinished();

                    // now handle all plugins and services
                    GlobalPluginProgramFormatingManager.getInstance();
                    PluginProxyManager.getInstance().fireTvBrowserStartFinished();
                    TvDataServiceProxyManager.getInstance().fireTvBrowserStartFinished();

                    // finally submit plugin caused updates to database
                    TvDataBase.getInstance().handleTvBrowserStartFinished();

                    startPeriodicSaveSettings();

                }
            }.start();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    ChannelList.completeChannelLoading();
                    initializeAutomaticDownload();
                    if (Launch.isOsWindowsNtBranch()) {
                        try {
                            RegistryKey desktopSettings = new RegistryKey(RootKey.HKEY_CURRENT_USER,
                                    "Control Panel\\Desktop");
                            RegistryValue autoEnd = desktopSettings.getValue("AutoEndTasks");

                            if (autoEnd.getData().equals("1")) {
                                RegistryValue killWait = desktopSettings.getValue("WaitToKillAppTimeout");

                                int i = Integer.parseInt(killWait.getData().toString());

                                if (i < 5000) {
                                    JOptionPane pane = new JOptionPane();

                                    String cancel = mLocalizer.msg("registryCancel", "Close TV-Browser");
                                    String dontDoIt = mLocalizer.msg("registryJumpOver", "Not this time");

                                    pane.setOptions(new String[] { Localizer.getLocalization(Localizer.I18N_OK),
                                            dontDoIt, cancel });
                                    pane.setOptionType(JOptionPane.YES_NO_CANCEL_OPTION);
                                    pane.setMessageType(JOptionPane.WARNING_MESSAGE);
                                    pane.setMessage(mLocalizer.msg("registryWarning",
                                            "The fast shutdown of Windows is activated.\nThe timeout to wait for before Windows is closing an application is too short,\nto give TV-Browser enough time to save all settings.\n\nThe setting hasn't the default value. It was changed by a tool or by you.\nTV-Browser will now try to change the timeout.\n\nIf you don't want to change this timeout select 'Not this time' or 'Close TV-Browser'."));

                                    pane.setInitialValue(mLocalizer.msg("registryCancel", "Close TV-Browser"));

                                    JDialog d = pane.createDialog(UiUtilities.getLastModalChildOf(mainFrame),
                                            UIManager.getString("OptionPane.messageDialogTitle"));
                                    d.setModal(true);
                                    UiUtilities.centerAndShow(d);

                                    if (pane.getValue() == null || pane.getValue().equals(cancel)) {
                                        mainFrame.quit();
                                    } else if (!pane.getValue().equals(dontDoIt)) {
                                        try {
                                            killWait.setData("5000");
                                            desktopSettings.setValue(killWait);
                                            JOptionPane.showMessageDialog(
                                                    UiUtilities.getLastModalChildOf(mainFrame),
                                                    mLocalizer.msg("registryChanged",
                                                            "The timeout was changed successfully.\nPlease reboot Windows!"));
                                        } catch (Exception registySetting) {
                                            JOptionPane.showMessageDialog(
                                                    UiUtilities.getLastModalChildOf(mainFrame),
                                                    mLocalizer.msg("registryNotChanged",
                                                            "<html>The Registry value couldn't be changed. Maybe you haven't the right to do it.<br>If it is so contact you Administrator and let him do it for you.<br><br><b><Attention:/b> The following description is for experts. If you change or delete the wrong value in the Registry you could destroy your Windows installation.<br><br>To get no warning on TV-Browser start the Registry value <b>WaitToKillAppTimeout</b> in the Registry path<br><b>HKEY_CURRENT_USER\\Control Panel\\Desktop</b> have to be at least <b>5000</b> or the value for <b>AutoEndTasks</b> in the same path have to be <b>0</b>.</html>"),
                                                    Localizer.getLocalization(Localizer.I18N_ERROR),
                                                    JOptionPane.ERROR_MESSAGE);
                                        }
                                    }
                                }
                            }
                        } catch (Throwable registry) {
                        }
                    }

                    if (currentVersion != null && currentVersion.compareTo(new Version(2, 71, false)) < 0) {
                        if (Settings.propProgramPanelMarkedMinPriorityColor.getColor()
                                .equals(Settings.propProgramPanelMarkedMinPriorityColor.getDefaultColor())) {
                            Settings.propProgramPanelMarkedMinPriorityColor.setColor(new Color(255, 0, 0, 30));
                        }
                        if (Settings.propProgramPanelMarkedMediumPriorityColor.getColor()
                                .equals(Settings.propProgramPanelMarkedMediumPriorityColor.getDefaultColor())) {
                            Settings.propProgramPanelMarkedMediumPriorityColor
                                    .setColor(new Color(140, 255, 0, 60));
                        }
                        if (Settings.propProgramPanelMarkedHigherMediumPriorityColor.getColor().equals(
                                Settings.propProgramPanelMarkedHigherMediumPriorityColor.getDefaultColor())) {
                            Settings.propProgramPanelMarkedHigherMediumPriorityColor
                                    .setColor(new Color(255, 255, 0, 60));
                        }
                        if (Settings.propProgramPanelMarkedMaxPriorityColor.getColor()
                                .equals(Settings.propProgramPanelMarkedMaxPriorityColor.getDefaultColor())) {
                            Settings.propProgramPanelMarkedMaxPriorityColor
                                    .setColor(new Color(255, 180, 0, 110));
                        }
                    }

                    // check if user should select picture settings
                    if (currentVersion != null && currentVersion.compareTo(new Version(2, 22)) < 0) {
                        TvBrowserPictureSettingsUpdateDialog.createAndShow(mainFrame);
                    } else if (currentVersion != null
                            && currentVersion.compareTo(new Version(2, 51, true)) < 0) {
                        Settings.propAcceptedLicenseArrForServiceIds.setStringArray(new String[0]);
                    }

                    if (currentVersion != null && currentVersion.compareTo(new Version(2, 60, true)) < 0) {
                        int startOfDay = Settings.propProgramTableStartOfDay.getInt();
                        int endOfDay = Settings.propProgramTableEndOfDay.getInt();

                        if (endOfDay - startOfDay < -1) {
                            Settings.propProgramTableEndOfDay.setInt(startOfDay);

                            JOptionPane.showMessageDialog(UiUtilities.getLastModalChildOf(mainFrame),
                                    mLocalizer.msg("timeInfoText",
                                            "The time range of the program table was corrected because the defined day was shorter than 24 hours.\n\nIf the program table should show less than 24h use a time filter for that. That time filter can be selected\nto be the default filter by selecting it in the filter settings and pressing on the button 'Default'."),
                                    mLocalizer.msg("timeInfoTitle", "Times corrected"),
                                    JOptionPane.INFORMATION_MESSAGE);
                            Settings.handleChangedSettings();
                        }
                    }
                    MainFrame.getInstance().getProgramTableScrollPane().requestFocusInWindow();
                }
            });
        }
    });

    // register the shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread("Shutdown hook") {
        public void run() {
            deleteLockFile();
            MainFrame.getInstance().quit(false);
        }
    });
}