Example usage for java.lang Thread setDefaultUncaughtExceptionHandler

List of usage examples for java.lang Thread setDefaultUncaughtExceptionHandler

Introduction

In this page you can find the example usage for java.lang Thread setDefaultUncaughtExceptionHandler.

Prototype

public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) 

Source Link

Document

Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.

Usage

From source file:com.aerofs.baseline.Service.java

@SuppressWarnings({ "unused", "unchecked" })
public final void run(String[] args) throws Exception {
    // add the uncaught exception handler
    Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler());

    // enable all logging to the console
    Logging.setupErrorConsoleLogging();//from  w w  w.  j  a  v a 2  s.  co  m

    // check that the filename is specified
    if (args.length != 1) {
        LOGGER.error("incorrect number of arguments exp:{} act:{}", 1, args.length);
        System.exit(Constants.INVALID_ARGUMENTS_EXIT_CODE);
    }

    // check that it's a YAML file
    String config = args[0];
    if (!config.endsWith(".yml")) {
        LOGGER.error("yaml configuration file with filename ending with .yml expected");
        System.exit(Constants.INVALID_ARGUMENTS_EXIT_CODE);
    }

    // load the yaml config file (don't validate)
    T configuration = null;
    try {
        configuration = Configuration.loadYAMLConfigurationFromFile(getClass(), config);
    } catch (Exception e) {
        LOGGER.error("fail load {}", config, e);
        System.exit(Constants.INVALID_CONFIGURATION_EXIT_CODE);
    }

    // run baseline with the parsed configuration
    try {
        Preconditions.checkArgument(configuration != null, "%s could not be loaded", config);
        runWithConfiguration(configuration);
    } catch (Exception e) {
        LOGGER.error("fail start server", e);
        System.exit(Constants.FAIL_SERVICE_START_EXIT_CODE);
    }
}

From source file:io.teak.sdk.Raven.java

public void unsetAsUncaughtExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(previousUncaughtExceptionHandler);
    previousUncaughtExceptionHandler = null;
}

From source file:org.geometerplus.android.fbreader.network.AuthenticationActivity.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    Thread.setDefaultUncaughtExceptionHandler(
            new org.geometerplus.zlibrary.ui.android.library.UncaughtExceptionHandler(this));
    setResult(RESULT_CANCELED);/*www. ja v a2 s.  c om*/
    setContentView(R.layout.authentication);

    final Intent intent = getIntent();
    final String host = intent.getStringExtra(HOST_KEY);
    final String area = intent.getStringExtra(AREA_KEY);
    final String username = intent.getStringExtra(USERNAME_KEY);
    final String error = intent.getStringExtra(ERROR_KEY);
    final boolean showSignupLink = intent.getBooleanExtra(SHOW_SIGNUP_LINK_KEY, false);

    myResource = ZLResource.resource("dialog").getResource("AuthenticationDialog");

    setTitle(host != null ? host : myResource.getResource("title").getValue());

    if (area != null && !"".equals(area)) {
        findTextView(R.id.authentication_subtitle).setText(area);
    } else {
        findTextView(R.id.authentication_subtitle).setVisibility(View.GONE);
    }
    final TextView warningView = findTextView(R.id.authentication_unencrypted_warning);
    if ("https".equalsIgnoreCase(intent.getStringExtra(SCHEME_KEY))) {
        warningView.setVisibility(View.GONE);
    } else {
        warningView.setText(myResource.getResource("unencryptedWarning").getValue());
    }
    findTextView(R.id.authentication_username_label).setText(myResource.getResource("login").getValue());
    findTextView(R.id.authentication_password_label).setText(myResource.getResource("password").getValue());

    final TextView usernameView = findTextView(R.id.authentication_username);
    usernameView.setText(username);

    final TextView errorView = findTextView(R.id.authentication_error);
    if (error != null && !"".equals(error)) {
        errorView.setVisibility(View.VISIBLE);
        errorView.setText(error);
    } else {
        errorView.setVisibility(View.GONE);
    }

    if (showSignupLink) {
        findViewById(R.id.authentication_signup_box).setVisibility(View.VISIBLE);
        final TextView signupView = (TextView) findViewById(R.id.authentication_signup);
        signupView.setText(myResource.getResource("register").getValue());
        signupView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                setResult(RESULT_SIGNUP);
                finish();
            }
        });
    } else {
        findViewById(R.id.authentication_signup_box).setVisibility(View.GONE);
    }

    final ZLResource buttonResource = ZLResource.resource("dialog").getResource("button");

    final Button okButton = findButton(R.id.authentication_ok_button);
    okButton.setText(buttonResource.getResource("ok").getValue());
    okButton.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            final Intent data = new Intent();
            data.putExtra(USERNAME_KEY, usernameView.getText().toString());
            data.putExtra(PASSWORD_KEY, findTextView(R.id.authentication_password).getText().toString());
            setResult(RESULT_OK, data);
            finish();
        }
    });

    final Button cancelButton = findButton(R.id.authentication_cancel_button);
    cancelButton.setText(buttonResource.getResource("cancel").getValue());
    cancelButton.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
}

From source file:xtrememp.XtremeMP.java

public static void main(String... args) throws Exception {
    // Load Settings
    Settings.loadSettings();//from  w ww .  java  2  s.  c o  m
    // Configure logback
    Settings.configureLogback();

    // Enable uncaught exception catching.
    Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> {
        logger.error(t.getName(), e);
    });

    // Close error stream
    System.err.close();
    // First, look up for other instances running
    if (!MultipleInstancesHandler.getInstance().isFirstInstance()) {
        MultipleInstancesHandler.getInstance().sendArgumentsToFirstInstance(args);
    } else {
        // NORMAL APPLICATION STARTUP
        // Set language
        Locale locale = Utilities.getLanguages()[Settings.getLanguageIndex()];
        Locale.setDefault(locale);
        LanguageBundle.setLanguage(locale);

        // Animation configurations
        AnimationConfigurationManager.getInstance().disallowAnimations(AnimationFacet.ICON_GLOW, JTable.class);
        AnimationConfigurationManager.getInstance().disallowAnimations(AnimationFacet.ROLLOVER, JTable.class);
        AnimationConfigurationManager.getInstance().disallowAnimations(AnimationFacet.SELECTION, JTable.class);

        // Init
        getInstance().init(args);

        // Check for updates
        if (Settings.isAutomaticUpdatesEnabled()) {
            // wait 5 sec
            SoftwareUpdate.scheduleCheckForUpdates(5 * 1000);
        }
    }
}

From source file:org.geometerplus.android.fbreader.BookmarkFragmentActivity.java

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);

    Thread.setDefaultUncaughtExceptionHandler(
            new org.geometerplus.zlibrary.ui.android.library.UncaughtExceptionHandler(this));

    PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);

    int theme = PreferenceManager.getDefaultSharedPreferences(this).getInt(IConstants.THEME_PREF,
            IConstants.THEME_REDTREE);/*  ww w.ja va  2s . c o m*/
    switch (theme) {
    case IConstants.THEME_MYBLACK:
        setTheme(R.style.Theme_myBlack);
        break;
    case IConstants.THEME_LAMINAT:
        setTheme(R.style.Theme_Laminat);
        break;
    case IConstants.THEME_REDTREE:
        setTheme(R.style.Theme_Redtree);
        break;

    }
    setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);

    final SearchManager manager = (SearchManager) getSystemService(SEARCH_SERVICE);
    manager.setOnCancelListener(null);

    myBook = SerializerUtil.deserializeBook(getIntent().getStringExtra(FullReaderActivity.BOOK_KEY));

    myTabListener = new MyTabListener();
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setSubtitle(ZLResource.resource("menu").getResource("bookmarks").getValue());

}

From source file:io.bifroest.commons.boot.BootLoaderNG.java

/**
 * Constructs a bootloader with supplied environment. If autoSearchSystems
 * is true, the bootloader tries to load the subsystems via SearviceLoader.
 * If set to false, the subsystems must be added through the addSubsystem()-
 * method//from ww w . j  av  a2s  .  c o  m
 *
 * @param env A environment extented from @see Environment
 * @param autoSearchSystems if true, autoload systems, false does not load
 * any system.
 * @throws ConfigurationException
 */
public BootLoaderNG(E env, boolean autoSearchSystems) throws ConfigurationException {
    environment = env;
    loader = new ActualJSONConfigurationLoader<>(environment);
    environment.setConfigurationLoader(loader);
    this.loadConfiguration();
    registerOptionalStatusWriter(env, loader);
    if (autoSearchSystems) {
        findAvailableSubsystems();
    }
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            shutdown();
        }
    });
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            log.error("Exception in thread " + t.getName(), e);
        }
    });

    ProfilingPanic.INSTANCE.addAction(new PanicAnnouncement());
}

From source file:tv.phantombot.cache.TwitchCache.java

@SuppressWarnings("CallToThreadStartDuringObjectConstruction")
private TwitchCache(String channel) {
    if (channel.startsWith("#")) {
        channel = channel.substring(1);//  w  ww .j  a  va  2s. c  o m
    }

    this.channel = channel;
    this.updateThread = new Thread(this, "tv.phantombot.cache.TwitchCache");

    Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance());
    this.updateThread.setUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance());

    updateThread.start();
}

From source file:de.dal33t.powerfolder.PowerFolder.java

/**
 * Starts a PowerFolder controller with the given command line arguments
 *
 * @param args// w w w. ja va 2s  .  com
 */
public static void startPowerFolder(String[] args) {

    // Touch Logger immediately to initialize handlers.
    LoggingManager.isLogToFile();

    // Default exception logger
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            log.log(Level.SEVERE, "Exception in " + t + ": " + e.toString(), e);
        }
    });

    CommandLine commandLine = parseCommandLine(args);
    if (commandLine == null) {
        return;
    }

    // -l --log console log levels (severe, warning, info, fine and finer).
    if (commandLine.hasOption("l")) {
        String levelName = commandLine.getOptionValue("l");
        Level level = LoggingManager.levelForName(levelName);
        if (level != null) {
            LoggingManager.setConsoleLogging(level);
        }
    }

    if (commandLine.hasOption("s")) {
        // Server mode, suppress debug output on console
        // Logger.addExcludeConsoleLogLevel(Logger.DEBUG);
    }

    if (commandLine.hasOption("h")) {
        // Show help
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("PowerFolder", COMMAND_LINE_OPTIONS);
        return;
    }

    int rconPort = Integer.valueOf(ConfigurationEntry.NET_RCON_PORT.getDefaultValue());
    String portStr = commandLine.getOptionValue("k");
    if (StringUtils.isNotBlank(portStr)) {
        try {
            rconPort = Integer.valueOf(portStr.trim());
        } catch (Exception e) {
            log.warning("Unable to parse rcon port: " + portStr + ". " + e);
        }
    }

    boolean runningInstanceFound = RemoteCommandManager.hasRunningInstance(rconPort);

    if (commandLine.hasOption("k")) {
        if (runningInstanceFound) {
            System.out.println("Stopping " + NAME);
            // Send quit command
            RemoteCommandManager.sendCommand(rconPort, RemoteCommandManager.QUIT);
        } else {
            System.err.println("Process not running");
        }

        // stop
        return;
    }

    // set language from commandline to preferences
    if (commandLine.hasOption("g")) {
        Preferences.userNodeForPackage(Translation.class).put("locale", commandLine.getOptionValue("g"));
    }

    if (JavaVersion.systemVersion().isOpenJDK()) {
        Object[] options = { "Open Oracle home page and exit", "Exit" };

        int n = JOptionPane.showOptionDialog(null,
                "You are using OpenJDK which is unsupported.\n"
                        + "Please install the client with bundled JRE or install the Oracle JRE",
                "Unsupported JRE", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
                options[0]);

        if (n == 0) {
            try {
                BrowserLauncher.openURL("http://www.java.com");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        return;
    }

    // The controller.
    Controller controller = Controller.createController();

    String[] files = commandLine.getArgs();
    // Parsing of command line completed

    boolean commandContainsRemoteCommands = files != null && files.length >= 1 || commandLine.hasOption("e")
            || commandLine.hasOption("r") || commandLine.hasOption("a");
    // Try to start controller
    boolean startController = !commandContainsRemoteCommands || !runningInstanceFound;
    try {
        log.info("PowerFolder v" + Controller.PROGRAM_VERSION);

        // Start controller
        if (startController) {
            controller.startConfig(commandLine);
        }

        // Send remote command if there a files in commandline
        if (files != null && files.length > 0) {
            // Parse filenames and build remote command
            StringBuilder openFilesRCommand = new StringBuilder(RemoteCommandManager.OPEN);

            for (String file : files) {
                openFilesRCommand.append(file);
                // FIXME: Add ; separator ?
            }

            // Send remote command to running PowerFolder instance
            RemoteCommandManager.sendCommand(openFilesRCommand.toString());
        }

        if (commandLine.hasOption("e")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.MAKEFOLDER + commandLine.getOptionValue("e"));
        }
        if (commandLine.hasOption("r")) {
            RemoteCommandManager
                    .sendCommand(RemoteCommandManager.REMOVEFOLDER + commandLine.getOptionValue("r"));
        }
        if (commandLine.hasOption("a")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.COPYLINK + commandLine.getOptionValue("a"));
        }
    } catch (Throwable t) {
        t.printStackTrace();
        log.log(Level.SEVERE, "Throwable", t);
        return;
    }

    // Begin monitoring memory usage.
    if (controller.isStarted() && controller.isUIEnabled()) {
        ScheduledExecutorService service = controller.getThreadPool();
        service.scheduleAtFixedRate(new MemoryMonitor(controller), 1, 1, TimeUnit.MINUTES);
    }

    // Not go into console mode if ui is open
    if (!startController) {
        if (runningInstanceFound) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.SHOW_UI);
        }
        return;
    }

    System.out.println("------------ " + NAME + " " + Controller.PROGRAM_VERSION + " started ------------");

    boolean restartRequested = false;
    do {
        // Go into restart loop
        while (controller.isStarted() || controller.isShuttingDown()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.log(Level.WARNING, "InterruptedException", e);
                return;
            }
        }

        restartRequested = controller.isRestartRequested();
        if (restartRequested) {
            Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
            for (Thread thread : threads.keySet()) {
                if (thread.getName().startsWith("PoolThread") || thread.getName().startsWith("Reconnector")
                        || thread.getName().startsWith("ConHandler")) {
                    thread.interrupt();
                }
            }
            log.info("Restarting controller");
            System.out.println(
                    "------------ " + NAME + " " + Controller.PROGRAM_VERSION + " restarting ------------");
            controller = null;
            System.gc();
            controller = Controller.createController();
            // Start controller
            controller.startConfig(commandLine);
        }
    } while (restartRequested);
}

From source file:com.deltadna.android.sdk.ads.core.AdServiceImpl.java

AdServiceImpl(Activity activity, AdServiceListener listener, String sdkVersion) {

    Preconditions.checkArg(activity != null, "activity cannot be null");
    Preconditions.checkArg(listener != null, "listener cannot be null");

    Log.d(BuildConfig.LOG_TAG, "Initialising AdService version " + VERSION);

    String version = "";
    int versionCode = -1;
    try {//from w w w  .  j av  a  2 s . c o m
        final PackageInfo info = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0);

        version = info.versionName;
        versionCode = info.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        Log.w(BuildConfig.LOG_TAG, "Failed to read app versions", e);
    }
    exceptionHandler = new ExceptionHandler(activity.getApplicationContext(), version, versionCode, sdkVersion,
            BuildConfig.VERSION_NAME);
    Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);

    this.activity = activity;
    this.listener = MainThread.redirect(listener, AdServiceListener.class);

    metrics = new AdMetrics(
            activity.getSharedPreferences(Preferences.METRICS.preferencesName(), Context.MODE_PRIVATE));
    broadcasts = LocalBroadcastManager.getInstance(activity.getApplicationContext());
    adAgentListeners = Collections
            .unmodifiableSet(new HashSet<>(Arrays.asList(new AgentListener(), new Broadcaster())));

    // dynamically load the DebugReceiver
    try {
        @SuppressWarnings("unchecked")
        final Class<BroadcastReceiver> cls = (Class<BroadcastReceiver>) Class
                .forName("com.deltadna.android.sdk.ads.debug.DebugReceiver");
        broadcasts.registerReceiver(cls.newInstance(), Actions.FILTER);
        Log.d(BuildConfig.LOG_TAG, "DebugReceiver registered");
    } catch (ClassNotFoundException ignored) {
        Log.d(BuildConfig.LOG_TAG, "DebugReceiver not found in classpath");
    } catch (IllegalAccessException e) {
        Log.w(BuildConfig.LOG_TAG, "Failed to load DebugReceiver", e);
    } catch (InstantiationException e) {
        Log.w(BuildConfig.LOG_TAG, "Failed to load DebugReceiver", e);
    }
}

From source file:com.att.arocollector.AROCollectorActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i(TAG, "onCreate(...)");
    // Setup handler for uncaught exceptions.
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/* w  w w.ja va 2  s . co m*/
        public void uncaughtException(Thread thread, Throwable e) {
            handleUncaughtException(thread, e);
        }
    });

    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);
    final TextView splashText = (TextView) findViewById(R.id.splash_message);
    splashText.setText(String.format(getString(R.string.splashmessageopensource),
            getString(R.string.app_brand_name), getString(R.string.app_url_name)));
    AttenuatorManager.getInstance().init();
    Intent intent = getIntent();
    //delay
    int delayDl = intent.getIntExtra(BundleKeyUtil.DL_DELAY, 0);
    int delayUl = intent.getIntExtra(BundleKeyUtil.UL_DELAY, 0);

    if (delayDl >= 0) {
        AttenuatorManager.getInstance().setDelayDl(delayDl);
    } else {
        Log.i(TAG, "Invalid attenuation delay value" + delayDl + "ms");
    }

    if (delayUl >= 0) {
        AttenuatorManager.getInstance().setDelayUl(delayUl);
    } else {
        Log.i(TAG, "Invalid attenuation delay value" + delayUl + "ms");
    }

    //throttle
    int throttleDl = intent.getIntExtra(BundleKeyUtil.DL_THROTTLE, AttenuatorUtil.DEFAULT_THROTTLE_SPEED);
    int throttleUl = intent.getIntExtra(BundleKeyUtil.UL_THROTTLE, AttenuatorUtil.DEFAULT_THROTTLE_SPEED);

    AttenuatorManager.getInstance().setThrottleDL(throttleDl);
    Log.d(TAG, "Download speed throttle value: " + throttleDl + " kbps");

    AttenuatorManager.getInstance().setThrottleUL(throttleUl);
    Log.d(TAG, "Upload speed throttle value: " + throttleUl + " kbps");

    printLog = intent.getBooleanExtra(BundleKeyUtil.PRINT_LOG, false);

    setVideoOption(intent);

    bitRate = intent.getIntExtra(BundleKeyUtil.BIT_RATE, 0);
    String screenSizeTmp = intent.getStringExtra(BundleKeyUtil.SCREEN_SIZE);
    screenSize = screenSizeTmp == null ? screenSize : screenSizeTmp;

    setVideoOrient(intent);

    Log.i(TAG,
            "get from intent delayTime: " + AttenuatorManager.getInstance().getDelayDl()
                    + "get from intent delayTimeUL: " + AttenuatorManager.getInstance().getDelayUl()
                    + "get from intent throttleDL: " + AttenuatorManager.getInstance().getThrottleDL()
                    + "get from intnetn throttleUL: " + AttenuatorManager.getInstance().getThrottleUL()
                    + " video: " + videoOption + " bitRate: " + bitRate + " screenSize: " + screenSize
                    + " orientation: " + videoOrient);

    context = getApplicationContext();
    launchAROCpuTraceService();
    launchAROCpuTempService();
    if (networkAndAirplaneModeCheck()) {

        // register to listen for close down message
        registerAnalyzerCloseCmdReceiver();
        Log.d(TAG, "register the attenuator delay signal");

        startVPN();
    }

    { // test code
        PackageInfo packageInfo = null;
        try {
            packageInfo = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        boolean valu = (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        // build datetime
        Date buildDate = new Date(BuildConfig.TIMESTAMP);
        String appBuildDate = "";
        if (buildDate != null) {
            appBuildDate = buildDate.toString();
        }

        String display = "App Build Date: " + appBuildDate + "\n"
        //               +" DownStream Delay Time: " + AttenuatorManager.getInstance().getDelayDl() + " ms\n"
        //               +" UpStream Delay Time: " + AttenuatorManager.getInstance().getDelayUl() + " ms\n"
        //               +" DownStream Throttle: " + AttenuatorManager.getInstance().getThrottleDL() + " kbps\n"
        //               +" Upstream Throttle: " + AttenuatorManager.getInstance().getThrottleUL() + " kbps\n"
                + AttenuatorUtil.getInstance().notificationMessage() + "\n" + " Version: "
                + packageInfo.versionName + " (" + (valu ? "Debug" : "Production") + ")";

        ((TextView) findViewById(R.id.version)).setText(display);
    }
}