Example usage for java.util.logging Logger getHandlers

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

Introduction

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

Prototype

public Handler[] getHandlers() 

Source Link

Document

Get the Handlers associated with this logger.

Usage

From source file:de.fosd.jdime.JDimeWrapper.java

public static void main(String[] args) throws IOException, InterruptedException {
    // setup logging
    Logger root = Logger.getLogger(JDimeWrapper.class.getPackage().getName());
    root.setLevel(Level.WARNING);

    for (Handler handler : root.getHandlers()) {
        handler.setLevel(Level.WARNING);
    }/*from  w w  w  . j  ava2  s .  c o  m*/

    // setup JDime using the MergeContext
    MergeContext context = new MergeContext();
    context.setPretend(true);
    context.setQuiet(false);

    // prepare the list of input files
    ArtifactList<FileArtifact> inputArtifacts = new ArtifactList<>();

    for (String filename : args) {
        try {
            File file = new File(filename);

            // the revision name, this will be used as condition for ifdefs
            // as an example, I'll just use the filenames
            Revision rev = new Revision(FilenameUtils.getBaseName(file.getPath()));
            FileArtifact newArtifact = new FileArtifact(rev, file);

            inputArtifacts.add(newArtifact);
        } catch (FileNotFoundException e) {
            System.err.println("Input file not found: " + filename);
        }
    }

    context.setInputFiles(inputArtifacts);

    // setup strategies
    MergeStrategy<FileArtifact> structured = new StructuredStrategy();
    MergeStrategy<FileArtifact> conditional = new NWayStrategy();

    // run the merge first with structured strategy to see whether there are conflicts
    context.setMergeStrategy(structured);
    context.collectStatistics(true);
    Operation<FileArtifact> merge = new MergeOperation<>(context.getInputFiles(), context.getOutputFile(), null,
            null, context.isConditionalMerge());
    merge.apply(context);

    // if there are no conflicts, run the conditional strategy
    if (context.getStatistics().hasConflicts()) {
        context = new MergeContext(context);
        context.collectStatistics(false);
        context.setMergeStrategy(conditional);
        // use regular merging outside of methods
        context.setConditionalOutsideMethods(false);
        // we have to recreate the operation because now we will do a conditional merge
        merge = new MergeOperation<>(context.getInputFiles(), context.getOutputFile(), null, null,
                context.isConditionalMerge());
        merge.apply(context);
    }
}

From source file:com.googlecode.promnetpp.main.Main.java

/**
 * Main function (entry point for the tool).
 *
 * @param args Command-line arguments.//from  www. j av a2  s .c  o m
 */
public static void main(String[] args) {
    //Prepare logging
    try {
        Handler fileHandler = new FileHandler("promnetpp-log.xml");
        Logger logger = Logger.getLogger("");
        logger.removeHandler(logger.getHandlers()[0]);
        logger.addHandler(fileHandler);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    String PROMNeTppHome = System.getenv("PROMNETPP_HOME");
    if (PROMNeTppHome == null) {
        String userDir = System.getProperty("user.dir");
        System.err.println("WARNING: PROMNETPP_HOME environment variable" + " not set.");
        System.err.println("PROMNeT++ will assume " + userDir + " as" + " home.");
        PROMNeTppHome = userDir;
    }
    System.setProperty("promnetpp.home", PROMNeTppHome);

    Logger.getLogger(Main.class.getName()).log(Level.INFO, "PROMNeT++ home" + " set to {0}",
            System.getProperty("promnetpp.home"));
    if (args.length == 1) {
        fileNameOrPath = args[0];
        configurationFilePath = PROMNeTppHome + "/default-configuration.xml";
    } else if (args.length == 2) {
        fileNameOrPath = args[0];
        configurationFilePath = args[1];
    } else {
        System.err.println("Invalid number of command-line arguments.");
        System.err.println("Usage #1: promnetpp.jar <PROMELA model>.pml");
        System.err.println("Usage #2: promnetpp.jar <PROMELA model>.pml" + " <configuration file>.xml");
        System.exit(1);
    }
    //We must have a file name or path at this point
    assert fileNameOrPath != null : "Unspecified file name or" + " path to file!";

    //Log basic info
    Logger.getLogger(Main.class.getName()).log(Level.INFO, "Running" + " PROMNeT++ from {0}",
            System.getProperty("user.dir"));
    //Final steps
    loadXMLFile();
    Verifier verifier = new StandardVerifier(fileNameOrPath);
    verifier.doVerification();
    assert verifier.isErrorFree() : "Errors reported during model" + " verification!";
    verifier.finish();
    buildAbstractSyntaxTree();
    Translator translator = new StandardTranslator();
    translator.init();
    translator.translate(abstractSyntaxTree);
    translator.finish();
}

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 {//  ww  w.ja  v a 2s . c om
        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.pniehus.odal.App.java

public static void main(String[] args) throws IOException {
    List<Filter> filters = new ArrayList<Filter>();
    filters.add(new RegexFilter());
    filters.add(new FileTypeFilter());
    filters.add(new KeywordFilter());
    filters.add(new BlacklistFilter());
    Profile p = parseArgs(args, filters);

    String fileName = "log-" + new Date().toString().replace(":", "-") + ".txt";
    fileName = fileName.replace(" ", "-");
    File logPath = new File(p.getLogDirectory() + fileName);

    if (!logPath.getParentFile().isDirectory() && !logPath.getParentFile().mkdirs()) {
        logPath = new File(fileName);
    }//  w w  w  .  j  av a  2s.  c  o m

    if (logPath.getParentFile().canWrite() || logPath.getParentFile().setWritable(true)) {
        SimpleLoggingSetup.configureRootLogger(logPath.getAbsolutePath(), p.getLogLevel(), !p.isSilent());
    } else {
        Logger root = Logger.getLogger("");

        for (Handler h : root.getHandlers()) { // Removing default console handlers
            if (h instanceof ConsoleHandler) {
                root.removeHandler(h);
            }
        }

        ConsolePrintLogHandler cplh = new ConsolePrintLogHandler();
        cplh.setFormatter(new ScribblerLogFormat(SimpleLoggingSetup.DEFAULT_DATE_FORMAT));
        root.addHandler(cplh);

        System.out.println("Unable to create log: insufficient permissions!");

    }

    Logger.getLogger("").setLevel(p.getLogLevel());
    mainLogger = Logger.getLogger(App.class.getCanonicalName());
    untrustedSSLSetup();
    mainLogger.info("Successfully intitialized ODAL");
    if (!p.isLogging())
        mainLogger.setLevel(Level.OFF);
    if (p.isWindowsConsoleMode() && !p.isLogging()) {
        Logger root = Logger.getLogger("");
        for (Handler h : root.getHandlers()) {
            if (h instanceof FileHandler) {
                root.removeHandler(h); // Removes FileHandler to allow console output through logging
            }
        }
    }
    OdalGui ogui = new OdalGui(p, filters);
}

From source file:primarydatamanager.PrimaryDataManager.java

public static void main(String[] args) {
    // setup logging
    try {/* w  w w . ja va 2 s  .  co m*/
        // 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:net.sf.freecol.FreeCol.java

/**
 * The entrypoint.//  ww w. j a  v  a2s .  c o m
 *
 * @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: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  www.j a v a2s  .c  o m*/
    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:tvbrowser.TVBrowser.java

/**
 * Entry point of the application/*from  ww w  . j  a  v a2 s. co 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);
        }
    });
}

From source file:havocx42.Program.java

private static void initRootLogger() throws SecurityException, IOException {

    FileHandler fileHandler;/*from  w  w  w  . ja  v a  2  s. co  m*/
    fileHandler = new FileHandler("PRWeaponStats.%u.%g.txt", 1024 * 1024 * 8, 3, false);
    fileHandler.setLevel(Level.FINEST);
    fileHandler.setFormatter(new SimpleFormatter());
    Logger rootLogger = Logger.getLogger("");
    Handler[] handlers = rootLogger.getHandlers();
    for (Handler handler : handlers) {
        handler.setLevel(Level.INFO);
    }
    rootLogger.setLevel(Level.FINEST);
    rootLogger.addHandler(fileHandler);
}

From source file:org.jumpmind.metl.StartWebServer.java

protected static void disableJettyLogging() {
    System.setProperty("org.eclipse.jetty.util.log.class", JavaUtilLog.class.getName());
    Logger.getLogger(JavaUtilLog.class.getName()).setLevel(Level.SEVERE);
    Logger rootLogger = Logger.getLogger("org.eclipse.jetty");
    for (Handler handler : rootLogger.getHandlers()) {
        handler.setLevel(Level.SEVERE);
    }//from w w  w . ja  v a 2s  . c o m
    rootLogger.setLevel(Level.SEVERE);
}