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:edu.jhu.hlt.concrete.ingesters.webposts.WebPostIngester.java

public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler());
    if (args.length < 2) {
        LOGGER.info("Usage: {} {} {} {}", WebPostIngester.class.getName(), "/path/to/output/folder",
                "/path/to/web/.xml/file", "<additional/xml/file/paths>");
        System.exit(1);//from ww  w  .  j av  a  2 s. c  o m
    }

    Path outPath = Paths.get(args[0]);
    Optional.ofNullable(outPath.getParent()).ifPresent(p -> {
        if (!Files.exists(p))
            try {
                Files.createDirectories(p);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
    });

    if (!Files.isDirectory(outPath)) {
        LOGGER.error("Output path must be a directory.");
        System.exit(1);
    }

    WebPostIngester ing = new WebPostIngester();
    for (int i = 1; i < args.length; i++) {
        Path lp = Paths.get(args[i]);
        LOGGER.info("On path: {}", lp.toString());
        try {
            Communication c = ing.fromCharacterBasedFile(lp);
            new WritableCommunication(c).writeToFile(outPath.resolve(c.getId() + ".comm"), true);
        } catch (IngestException | ConcreteException e) {
            LOGGER.error("Caught exception during ingest on file: " + args[i], e);
        }
    }
}

From source file:au.edu.uq.cmm.paul.Paul.java

private void setupDefaultUncaughtExceptionHandler() {
    if (Thread.getDefaultUncaughtExceptionHandler() == null) {
        LOG.info("Setting the uncaught exception handler");
    } else {/* ww w.j a  v  a2 s.  c om*/
        LOG.info("Changing the uncaught exception handler");
    }
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            LOG.error("Thread " + t.getName() + " died with an uncaught exception", e);
        }
    });
}

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

/**
 * The entrypoint./*w  ww. j a  v  a2 s  .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:io.bitsquare.seednode.SeedNodeMain.java

@Override
protected void doExecute(OptionSet options) {
    final BitsquareEnvironment environment = new BitsquareEnvironment(options);
    SeedNode.setEnvironment(environment);

    UserThread.execute(() -> seedNode = new SeedNode());

    Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
        if (throwable.getCause() != null && throwable.getCause().getCause() != null
                && throwable.getCause().getCause() instanceof BlockStoreException) {
            log.error(throwable.getMessage());
        } else {//from   ww w.  j av a2 s  . c  om
            log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
            log.error("throwableMessage= " + throwable.getMessage());
            log.error("throwableClass= " + throwable.getClass());
            log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable));
            throwable.printStackTrace();
            log.error("We shut down the app because an unhandled error occurred");
            // We don't use the restart as in case of OutOfMemory errors the restart might fail as well
            // The run loop will restart the node anyway...
            System.exit(EXIT_FAILURE);
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(handler);
    Thread.currentThread().setUncaughtExceptionHandler(handler);

    String maxMemoryOption = environment.getProperty(AppOptionKeys.MAX_MEMORY);
    if (maxMemoryOption != null && !maxMemoryOption.isEmpty()) {
        try {
            maxMemory = Integer.parseInt(maxMemoryOption);
        } catch (Throwable t) {
            log.error(t.getMessage());
        }
    }

    UserThread.runPeriodically(() -> {
        Profiler.printSystemLoad(log);
        long usedMemoryInMB = Profiler.getUsedMemoryInMB();
        if (!stopped) {
            if (usedMemoryInMB > (maxMemory - 100)) {
                log.warn(
                        "\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
                                + "We are over our memory warn limit and call the GC. usedMemoryInMB: {}"
                                + "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n",
                        usedMemoryInMB);
                System.gc();
                usedMemoryInMB = Profiler.getUsedMemoryInMB();
                Profiler.printSystemLoad(log);
            }

            final long finalUsedMemoryInMB = usedMemoryInMB;
            UserThread.runAfter(() -> {
                if (finalUsedMemoryInMB > maxMemory)
                    restart(environment);
            }, 1);
        }
    }, CHECK_MEMORY_PERIOD_SEC);

    while (true) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException ignore) {
        }
    }
}

From source file:org.apache.bookkeeper.stream.server.StorageServer.java

static int doMain(String[] args) {
    // register thread uncaught exception handler
    Thread.setDefaultUncaughtExceptionHandler((thread, exception) -> log
            .error("Uncaught exception in thread {}: {}", thread.getName(), exception.getMessage()));

    // parse the commandline
    ServerArguments arguments = new ServerArguments();
    JCommander jCommander = new JCommander(arguments);
    jCommander.setProgramName("StorageServer");
    jCommander.parse(args);//from w  w w  .j av a 2  s.com

    if (arguments.help) {
        jCommander.usage();
        return ExitCode.INVALID_CONF.code();
    }

    CompositeConfiguration conf = new CompositeConfiguration();
    if (null != arguments.serverConfigFile) {
        loadConfFile(conf, arguments.serverConfigFile);
    }

    int grpcPort = arguments.port;

    LifecycleComponent storageServer;
    try {
        storageServer = buildStorageServer(conf, grpcPort);
    } catch (ConfigurationException e) {
        log.error("Invalid storage configuration", e);
        return ExitCode.INVALID_CONF.code();
    } catch (UnknownHostException e) {
        log.error("Unknonw host name", e);
        return ExitCode.UNKNOWN_HOSTNAME.code();
    }

    CompletableFuture<Void> liveFuture = ComponentStarter.startComponent(storageServer);
    try {
        liveFuture.get();
    } catch (InterruptedException e) {
        // the server is interrupted.
        Thread.currentThread().interrupt();
        log.info("Storage server is interrupted. Exiting ...");
    } catch (ExecutionException e) {
        log.info("Storage server is exiting ...");
    }
    return ExitCode.OK.code();
}

From source file:io.bitsquare.statistics.StatisticsMain.java

@Override
protected void doExecute(OptionSet options) {
    final BitsquareEnvironment environment = new BitsquareEnvironment(options);
    Statistics.setEnvironment(environment);

    UserThread.execute(() -> statistics = new Statistics());

    Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
        if (throwable.getCause() != null && throwable.getCause().getCause() != null
                && throwable.getCause().getCause() instanceof BlockStoreException) {
            log.error(throwable.getMessage());
        } else {//from   ww w .j a v a2  s.c o  m
            log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
            log.error("throwableMessage= " + throwable.getMessage());
            log.error("throwableClass= " + throwable.getClass());
            log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable));
            throwable.printStackTrace();
            log.error("We shut down the app because an unhandled error occurred");
            // We don't use the restart as in case of OutOfMemory errors the restart might fail as well
            // The run loop will restart the node anyway...
            System.exit(EXIT_FAILURE);
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(handler);
    Thread.currentThread().setUncaughtExceptionHandler(handler);

    String maxMemoryOption = environment.getProperty(AppOptionKeys.MAX_MEMORY);
    if (maxMemoryOption != null && !maxMemoryOption.isEmpty()) {
        try {
            maxMemory = Integer.parseInt(maxMemoryOption);
        } catch (Throwable t) {
            log.error(t.getMessage());
        }
    }

    UserThread.runPeriodically(() -> {
        Profiler.printSystemLoad(log);
        long usedMemoryInMB = Profiler.getUsedMemoryInMB();
        if (!stopped) {
            if (usedMemoryInMB > (maxMemory - 100)) {
                log.warn(
                        "\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"
                                + "We are over our memory warn limit and call the GC. usedMemoryInMB: {}"
                                + "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n",
                        usedMemoryInMB);
                System.gc();
                usedMemoryInMB = Profiler.getUsedMemoryInMB();
                Profiler.printSystemLoad(log);
            }

            final long finalUsedMemoryInMB = usedMemoryInMB;
            UserThread.runAfter(() -> {
                if (finalUsedMemoryInMB > maxMemory) {
                    log.error(
                            "\n\n############################################################\n"
                                    + "We shut down as we are over our memory limit. usedMemoryInMB: {}"
                                    + "\n############################################################\n\n",
                            finalUsedMemoryInMB);
                    System.exit(EXIT_FAILURE);
                }
            }, 1);
        }
    }, CHECK_MEMORY_PERIOD_SEC);

    while (true) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException ignore) {
        }
    }
}

From source file:uk.ac.ucl.excites.sapelli.collector.CollectorApp.java

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

    // Build info:
    this.buildInfo = BuildInfo.GetInstance(getApplicationContext());

    Debug.d("CollectorApp started.\nBuild info:\n" + buildInfo.getAllInfo());

    // Start Crashlytics for bugs reporting
    if (!BuildConfig.DEBUG) {
        Crashlytics.start(this);
        Crashlytics.setString(CRASHLYTICS_VERSION_INFO,
                buildInfo.getNameAndVersion() + " [" + buildInfo.getExtraVersionInfo() + "]");
        Crashlytics.setString(CRASHLYTICS_BUILD_INFO, buildInfo.getBuildInfo());
    }/*from www .  j  av a2 s  .  c o m*/

    // Get collector preferences:
    preferences = new CollectorPreferences(getApplicationContext());

    // Initialise file storage:
    try {
        this.fileStorageProvider = initialiseFileStorage(); // throws FileStorageException
    } catch (FileStorageException fse) {
        this.fileStorageException = fse; // postpone throwing until getFileStorageProvider() is called!
    }

    // Set up a CrashReporter (will use dumps folder):
    if (fileStorageProvider != null)
        Thread.setDefaultUncaughtExceptionHandler(
                new CrashReporter(fileStorageProvider, getResources().getString(R.string.app_name)));

    // Create shortcut to Sapelli Collector on Home Screen:
    if (preferences.isFirstInstallation()) {
        // Create shortcut
        ProjectRunHelpers.createCollectorShortcut(getApplicationContext());
        // Set first installation to false
        preferences.setFirstInstallation(false);
    }
}

From source file:org.nebulaframework.grid.Grid.java

private static void initializeDefaultExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override/* www  . ja  v a 2 s  . c  o m*/
        public void uncaughtException(Thread t, Throwable e) {
            log.fatal("[Uncaught Thread Exception] on Thread " + t.getName() + " - " + e, e);
            e.printStackTrace();
        }

    });
}

From source file:org.mitre.svmp.activities.AppRTCActivity.java

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

    setContentView(R.layout.activity_apprtc);
    getWindow().getDecorView().setBackgroundColor(Color.WHITE);

    ll = (LinearLayout) findViewById(R.id.vsvLinear);
    preparingTextView = (TextView) findViewById(R.id.preparingTextView);
    appLoadingImgVw = (ImageView) findViewById(R.id.appLoadingImgVw);

    // lock the application to the natural "up" orientation of the physical
    // device//w  w  w . j av  a 2 s .  com
    // noinspection MagicConstant
    setRequestedOrientation(getDeviceDefaultOrientation());

    // connect to the database
    dbHandler = new DatabaseHandler(this);

    // adapter that helps record performance measurements
    performanceAdapter = new PerformanceAdapter();

    // Since the error-handling of this demo consists of throwing
    // RuntimeExceptions and we assume that'll terminate the app, we install
    // this default handler so it's applied to background threads as well.
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            System.exit(-1);
        }
    });

    // Get info passed to Intent
    final Intent intent = getIntent();
    connectionInfo = dbHandler.getConnectionInfo(intent.getIntExtra("connectionID", 1));

    if (connectionInfo != null)
        connectToRoom();
    else
        logAndToast(R.string.appRTC_toast_connection_notFound);
}

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

@Override
protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));

    setContentView(R.layout.listview_toc);
    rlLayout = (RelativeLayout) findViewById(R.id.rl_shelf);
    tvBook = (TextView) findViewById(R.id.tv_book);
    mViewPager = (ViewPager) findViewById(R.id.vp_view);
    mTabLayout = (TabLayout) findViewById(R.id.tabs);
    mInflater = LayoutInflater.from(this);

    view1 = mInflater.inflate(R.layout.item_listview, null);
    ListView listView = (ListView) view1.findViewById(R.id.listview);
    kooreader = (FBReaderApp) ZLApplication.Instance();
    final TOCTree root = kooreader.Model.TOCTree;
    tvBook.setText(kooreader.getCurrentBook().getTitle());

    myAdapter = new TOCAdapter(listView, root);
    TOCTree treeToSelect = kooreader.getCurrentTOCElement();
    myAdapter.selectItem(treeToSelect); // ??
    mySelectedItem = treeToSelect;//from   w  ww  .  j a v a  2s  . c  o m

    view2 = mInflater.inflate(R.layout.list_bookmark, null);
    rlBookmark = (RelativeLayout) view2.findViewById(R.id.rl_bookmark);
    thisBookListView = (ListView) view2.findViewById(R.id.bookmark_this_book);

    myBook = FBReaderIntents.getBookExtra(getIntent(), myCollection);
    myBookmark = FBReaderIntents.getBookmarkExtra(getIntent());

    view3 = mInflater.inflate(R.layout.list_note, null);
    rlNote = (RelativeLayout) view3.findViewById(R.id.rl_note);
    emptyRl = (RelativeLayout) view3.findViewById(R.id.rl_null);//
    markLv = (ListView) view3.findViewById(R.id.lv_mark);

    myCollection.bindToService(this, new Runnable() {
        public void run() {
            myThisBookAdapter = new BookmarksAdapter(thisBookListView, myBookmark != null);

            bookmarkAdapter = new BookmarkAdapter(markLv);
            myCollection.addListener(TOCActivity.this);
            updateStyles();
            loadBookmarks();
        }
    });

    /**
     * 
     */
    bgValue = kooreader.ViewOptions.getColorProfile().WallpaperOption.getValue();
    bgValue = "wallpapers/bg_vine_grey.png";
    switch (bgValue) {
    case "wallpapers/bg_green.png":
        listView.setBackgroundResource(R.drawable.bg_green);
        rlLayout.setBackgroundResource(R.drawable.bg_green);
        mTabLayout.setBackgroundResource(R.drawable.bg_green);
        rlBookmark.setBackgroundResource(R.drawable.bg_green);
        rlNote.setBackgroundResource(R.drawable.bg_green);
        break;
    case "wallpapers/bg_grey.png":
        listView.setBackgroundResource(R.drawable.bg_grey);
        rlLayout.setBackgroundResource(R.drawable.bg_grey);
        mTabLayout.setBackgroundResource(R.drawable.bg_grey);
        rlBookmark.setBackgroundResource(R.drawable.bg_grey);
        rlNote.setBackgroundResource(R.drawable.bg_grey);
        break;
    case "wallpapers/bg_night.png":
        listView.setBackgroundResource(R.drawable.bg_white);
        rlLayout.setBackgroundResource(R.drawable.bg_white);
        mTabLayout.setBackgroundResource(R.drawable.bg_white);
        rlBookmark.setBackgroundResource(R.drawable.bg_white);
        rlNote.setBackgroundResource(R.drawable.bg_white);
        break;
    case "wallpapers/bg_vine_grey.png":
        listView.setBackgroundResource(R.drawable.bg_vine_grey);
        rlLayout.setBackgroundResource(R.drawable.bg_vine_grey);
        //            mTabLayout.setBackgroundResource(R.drawable.bg_vine_grey);
        //            rlBookmark.setBackgroundResource(R.drawable.bg_vine_grey);
        //            rlNote.setBackgroundResource(R.drawable.bg_vine_grey);
        break;
    case "wallpapers/bg_vine_white.png":
        listView.setBackgroundResource(R.drawable.bg_vine_white);
        rlLayout.setBackgroundResource(R.drawable.bg_vine_white);
        mTabLayout.setBackgroundResource(R.drawable.bg_vine_white);
        rlBookmark.setBackgroundResource(R.drawable.bg_vine_white);
        rlNote.setBackgroundResource(R.drawable.bg_vine_white);
        break;
    case "wallpapers/bg_white.png":
        listView.setBackgroundResource(R.drawable.bg_white);
        rlLayout.setBackgroundResource(R.drawable.bg_white);
        mTabLayout.setBackgroundResource(R.drawable.bg_white);
        rlBookmark.setBackgroundResource(R.drawable.bg_white);
        rlNote.setBackgroundResource(R.drawable.bg_white);
        break;
    }

    //?
    mViewList.add(view1);
    mViewList.add(view3);
    mViewList.add(view2);
    //?
    mTitleList.add("");
    mTitleList.add("");
    mTitleList.add("");

    mTabLayout.setTabMode(TabLayout.MODE_FIXED);//tab???
    mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(0)));//tab?
    mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(1)));
    mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(2)));

    MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
    mViewPager.setAdapter(mAdapter); // ViewPager?
    mTabLayout.setupWithViewPager(mViewPager); // TabLayoutViewPager??
    mTabLayout.setTabsFromPagerAdapter(mAdapter); // Tabs?
}