Example usage for java.util.logging Logger addHandler

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

Introduction

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

Prototype

public void addHandler(Handler handler) throws SecurityException 

Source Link

Document

Add a log Handler to receive logging messages.

Usage

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  .j av  a2s .  co  m*/

    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:shuffle.fwk.ShuffleController.java

/**
 * The main which starts the program.//from ww w.ja  va2 s. c o  m
 * 
 * @param args
 *           unused.
 */
public static void main(String... args) {
    String userHomeArg = null;
    String levelToSetArg = null;

    if (args != null && args.length > 0) {
        userHomeArg = args[0];
        if (args.length > 1) {
            levelToSetArg = args[1];
        }
    }

    if (userHomeArg == null) {
        userHomeArg = System.getProperty("user.home") + File.separator + "Shuffle-Move";
    }
    setUserHome(userHomeArg);
    try {
        FileHandler handler = new FileHandler();
        Logger toRoot = LOG;
        while (toRoot.getParent() != null) {
            toRoot = toRoot.getParent();
        }
        toRoot.addHandler(handler);
    } catch (SecurityException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    if (levelToSetArg != null) {
        try {
            Level levelToSet = Level.parse(args[1]);
            Logger.getLogger(SimulationTask.class.getName()).setLevel(levelToSet);
            SimulationTask.setLogFiner(levelToSet.intValue() <= Level.FINER.intValue());
            Logger.getLogger(ShuffleModel.class.getName()).setLevel(levelToSet);
        } catch (Exception e) {
            LOG.fine("Cannot set simulation logging to that level: " + StringUtils.join(args));
        }
    }

    ShuffleController ctrl = new ShuffleController();
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            ctrl.getFrame().launch();
        }
    });
}

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

/**
 * The entrypoint.//  w ww  .  jav  a2s .  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./*from w  w w. j  a  va  2  s . c o  m*/
 */
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/*from w  w w  . j  a  v  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);
        }
    });
}

From source file:Main.java

public static void setLoggerhandler(Logger logger) {
    Handler handler = new ExceptionHandler();
    logger.addHandler(handler);

    logger.setLevel(Level.ALL);/*from www.  j a va2s  .c o  m*/
}

From source file:Main.java

/**
 * Tells Java's Logging infrastructure to output whatever it possibly can, this is only needed
 * in Java, not in Android.//from  www  . ja v a2s . c o  m
 */
public static void outputAsMuchLoggingAsPossible() {
    Logger log = Logger.getLogger("com.couchbase.lite");
    ConsoleHandler handler = new ConsoleHandler();
    handler.setLevel(Level.ALL);
    log.addHandler(handler);
    log.setLevel(Level.ALL);
}

From source file:com.elasticbox.jenkins.k8s.cfg.TestDiscoverLocalKubernetesCloud.java

@Initializer(after = InitMilestone.EXTENSIONS_AUGMENTED)
public static void initTestBeforePluginInitializer() throws Exception {
    testLogHandler.clear();/*  w ww. ja  v  a2s  . c  om*/

    Logger logger = Logger.getLogger("com.elasticbox.jenkins.k8s");
    logger.setUseParentHandlers(false);
    logger.addHandler(testLogHandler);

    Mockito.when(kubernetesRepositoryMock.testConnection(Mockito.anyString())).thenReturn(true);
    PluginInitializer.kubeRepository = kubernetesRepositoryMock;
    PluginInitializer.KUBE_TOKEN_PATH = PluginInitializer.class.getResource("fakeToken").getFile();
}

From source file:jshm.logging.Log.java

public static void configTestLogging() {
    Handler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(Level.ALL);
    consoleHandler.setFormatter(new OneLineFormatter());

    Logger cur = Logger.getLogger("");
    removeHandlers(cur);//from ww  w .  java 2s. c o  m
    //      cur.setLevel(Level.ALL);

    cur.addHandler(consoleHandler);

    cur = Logger.getLogger("jshm");
    cur.setLevel(Level.ALL);

    cur = Logger.getLogger("httpclient.wire.header");
    cur.setLevel(Level.ALL);

    //      cur = Logger.getLogger("org.hibernate");
    //      removeHandlers(cur);
    //      
    //      cur.setLevel(Level.INFO);
}

From source file:com.google.oacurl.util.LoggingConfig.java

public static void enableWireLog() {
    // For clarity, override the formatter so that it doesn't print the
    // date and method name for each line, and then munge the output a little
    // bit to make it nicer and more curl-like.
    Formatter wireFormatter = new Formatter() {
        @Override//from   www  .  jav a2  s  .c o  m
        public String format(LogRecord record) {
            String message = record.getMessage();
            String trimmedMessage = message.substring(">> \"".length(), message.length() - 1);
            if (trimmedMessage.matches("[0-9a-f]+\\[EOL\\]")) {
                return "";
            }

            trimmedMessage = trimmedMessage.replace("[EOL]", "");
            if (trimmedMessage.isEmpty()) {
                return "";
            }

            StringBuilder out = new StringBuilder();
            out.append(message.charAt(0));
            out.append(" ");
            out.append(trimmedMessage);
            out.append(System.getProperty("line.separator"));
            return out.toString();
        }
    };

    ConsoleHandler wireHandler = new ConsoleHandler();
    wireHandler.setLevel(Level.FINE);
    wireHandler.setFormatter(wireFormatter);

    Logger wireLogger = Logger.getLogger("org.apache.http.wire");
    wireLogger.setLevel(Level.FINE);
    wireLogger.setUseParentHandlers(false);
    wireLogger.addHandler(wireHandler);
}