Example usage for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler

List of usage examples for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler

Introduction

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

Prototype

Thread.UncaughtExceptionHandler

Source Link

Usage

From source file:org.ethereum.config.DefaultConfig.java

@PostConstruct
public void init() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/*  w  w  w.jav a 2s  .c o  m*/
        public void uncaughtException(Thread t, Throwable e) {
            logger.error("Uncaught exception", e);
        }
    });
}

From source file:be.neutrinet.ispng.VPN.java

@Override
public void init(DaemonContext dc) throws Exception {
    Logger root = Logger.getRootLogger();
    root.setLevel(Level.INFO);/*w  w  w  .j a va2 s .co m*/
    root.addAppender(new ConsoleAppender(LAYOUT));

    cfg = new Properties();
    cfg.load(new FileInputStream("config.properties"));

    root.addAppender(
            new DailyRollingFileAppender(LAYOUT, cfg.getProperty("log.file", "ispng.log"), "'.'yyyy-MM-dd"));

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            Logger.getLogger(getClass()).error("Unhandled exception", e);
        }
    });

    Zookeeper.boot(cfg.getProperty("zookeeper.connectionString"));
    Config.get().boot();
    generator = new Generator();

    Config.get().getAndWatch("log/level", "INFO", level -> root.setLevel(Level.toLevel(level)));

    Optional<String> dbUser = Config.get("db/user");
    if (!dbUser.isPresent()) {
        cs = new JdbcConnectionSource(Config.get("db/uri").get());
    } else {
        if (cfg.get("db.uri").toString().contains("mariadb")) {
            cs = new JdbcConnectionSource(cfg.getProperty("db.uri"), cfg.getProperty("db.user"),
                    cfg.getProperty("db.password"), new MariaDBType());
        } else if (cfg.get("db.uri").toString().contains("mysql")) {
            cs = new JdbcConnectionSource(cfg.getProperty("db.uri"), cfg.getProperty("db.user"),
                    cfg.getProperty("db.password"), new MySQLDBType());
        } else {
            cs = new JdbcConnectionSource(cfg.getProperty("db.uri"), cfg.getProperty("db.user"),
                    cfg.getProperty("db.password"));
        }
    }
}

From source file:org.imdea.panel.MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/*from   w w  w  .  ja  v a 2s .co m*/
        public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
            Log.e("Alert", "UNCAUGHT EXCEPTION", paramThrowable);
            System.exit(1);
        }
    });
    Thread.setDefaultUncaughtExceptionHandler(onRuntimeError);

    /*
    ParseObject testObject = new ParseObject("TestObject");
    testObject.put("foo", "bar");
    testObject.saveInBackground();*/

    SP = PreferenceManager.getDefaultSharedPreferences(this);

    //Abrimos la base de datos 'DBUsuarios' en modo escritura
    DBHelper msg_database = new DBHelper(this, "messages.db", null, 1);
    Global.db = msg_database.getWritableDatabase();

    enableBt();

    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    setContentView(R.layout.activity_main);

    // Initilization
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionbar = getActionBar();

    try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if (menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception ex) {
        // Ignore
    }
    checkUsername();

    TabsPagerAdapter mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
    fm = getSupportFragmentManager();

    viewPager.setAdapter(mAdapter);
    actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionbar.addTab(actionbar.newTab().setText("General").setTabListener(this));
    actionbar.addTab(actionbar.newTab().setText("Tags").setTabListener(this));

    /**
     * on swiping the viewpager make respective tab selected
     * */
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        public void onPageSelected(int position) {
            // on changing the page
            // make respected tab selected
            actionbar.setSelectedNavigationItem(position);
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        public void onPageScrollStateChanged(int arg0) {
        }
    });

    /* EXPERIMENTAL SERVICES */

    //this.startService(new Intent(this, WifiService.class));
    //this.startService(new Intent(this, BtWizService.class));
    //this.startService(new Intent(this, MeshService.class));
    this.startService(new Intent(this, commService.class));
    //if (Global.mqtt) this.startService(new Intent(this, mqttService.class));
    //else this.startService(new Intent(this, BtService.class));
    //this.startService(new Intent(this, smoothService.class));

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            handleSendText(intent); // Handle text being sent
        } else if (type.startsWith("image/")) {
            handleSendImage(intent); // Handle single image being sent
        }

    }

}

From source file:org.tinymediamanager.core.movie.MovieModuleManager.java

@Override
public void startUp() throws Exception {
    // do a DB backup, and keep last 15 copies
    Path db = Paths.get(Settings.getInstance().getSettingsFolder(), MOVIE_DB);
    Utils.createBackupFile(db);/*w w w.j  a va 2s  . co  m*/
    Utils.deleteOldBackupFile(db, 15);

    // configure database
    mvStore = new MVStore.Builder()
            .fileName(Paths.get(Settings.getInstance().getSettingsFolder(), MOVIE_DB).toString()).compressHigh()
            .backgroundExceptionHandler(new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    LOGGER.error("Error in the background thread of the persistent cache", e);
                }
            }).autoCommitBufferSize(4096).open();
    mvStore.setAutoCommitDelay(2000); // 2 sec
    mvStore.setRetentionTime(0);
    mvStore.setReuseSpace(true);

    // configure JSON
    objectMapper = new ObjectMapper();
    objectMapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    objectMapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
    objectMapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
    objectMapper.configure(MapperFeature.AUTO_DETECT_FIELDS, false);
    objectMapper.setTimeZone(TimeZone.getDefault());
    objectMapper.setSerializationInclusion(Include.NON_DEFAULT);

    movieObjectWriter = objectMapper.writerFor(Movie.class);
    movieSetObjectWriter = objectMapper.writerFor(MovieSet.class);

    movieMap = mvStore.openMap("movies");
    movieSetMap = mvStore.openMap("movieSets");

    MovieList.getInstance().loadMoviesFromDatabase(movieMap, objectMapper);
    MovieList.getInstance().loadMovieSetsFromDatabase(movieSetMap, objectMapper);
    MovieList.getInstance().initDataAfterLoading();
    enabled = true;
}

From source file:org.tinymediamanager.core.tvshow.TvShowModuleManager.java

@Override
public void startUp() throws Exception {
    // do a DB backup, and keep last 15 copies
    Path db = Paths.get(Settings.getInstance().getSettingsFolder(), TV_SHOW_DB);
    Utils.createBackupFile(db);/*w  ww . java  2  s . c  o  m*/
    Utils.deleteOldBackupFile(db, 15);

    // configure database
    mvStore = new MVStore.Builder()
            .fileName(Paths.get(Settings.getInstance().getSettingsFolder(), TV_SHOW_DB).toString())
            .compressHigh().backgroundExceptionHandler(new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    LOGGER.error("Error in the background thread of the persistent cache", e);
                }
            }).autoCommitBufferSize(4096).open();
    mvStore.setAutoCommitDelay(2000); // 2 sec
    mvStore.setRetentionTime(0);
    mvStore.setReuseSpace(true);

    // configure JSON
    objectMapper = new ObjectMapper();
    objectMapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    objectMapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
    objectMapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
    objectMapper.configure(MapperFeature.AUTO_DETECT_FIELDS, false);
    objectMapper.setTimeZone(TimeZone.getDefault());
    objectMapper.setSerializationInclusion(Include.NON_DEFAULT);

    tvShowObjectWriter = objectMapper.writerFor(TvShow.class);
    episodeObjectWriter = objectMapper.writerFor(TvShowEpisode.class);

    tvShowMap = mvStore.openMap("tvshows");
    episodeMap = mvStore.openMap("episodes");

    TvShowList.getInstance().loadTvShowsFromDatabase(tvShowMap, objectMapper);
    TvShowList.getInstance().loadEpisodesFromDatabase(episodeMap, objectMapper);
    TvShowList.getInstance().initDataAfterLoading();
    enabled = true;
}

From source file:org.spoutcraft.launcher.entrypoint.SpoutcraftLauncher.java

protected static Logger setupLogger() {
    final Logger logger = Utils.getLogger();
    File logDirectory = new File(Utils.getLauncherDirectory(), "logs");
    if (!logDirectory.exists()) {
        logDirectory.mkdir();/*from w w w .  ja v a2 s  .  c om*/
    }
    File logs = new File(logDirectory, "techniclauncher_%D.log");
    RotatingFileHandler fileHandler = new RotatingFileHandler(logs.getPath());

    fileHandler.setFormatter(new TechnicLogFormatter());

    for (Handler h : logger.getHandlers()) {
        logger.removeHandler(h);
    }
    logger.addHandler(fileHandler);

    SpoutcraftLauncher.handler = fileHandler;

    if (params != null && !params.isDebugMode()) {
        logger.setUseParentHandlers(false);

        System.setOut(new PrintStream(new LoggerOutputStream(console, Level.INFO, logger), true));
        System.setErr(new PrintStream(new LoggerOutputStream(console, Level.SEVERE, logger), true));
    }

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            logger.log(Level.SEVERE, "Unhandled Exception in " + t, e);

            if (errorDialog == null) {
                LauncherFrame frame = null;

                try {
                    frame = Launcher.getFrame();
                } catch (Exception ex) {
                    //This can happen if we have a very early crash- before Launcher initializes
                }

                errorDialog = new ErrorDialog(frame, e);
                errorDialog.setVisible(true);
            }
        }
    });

    return logger;
}

From source file:cx.ring.client.HomeActivity.java

private static void setDefaultUncaughtExceptionHandler() {
    try {// w w w.  ja va  2 s.  c o m
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                Log.e(TAG, "Uncaught Exception detected in thread ", e);
                //e.printStackTrace();
            }
        });
    } catch (SecurityException e) {
        Log.e(TAG, "Could not set the Default Uncaught Exception Handler");
    }
}

From source file:au.com.cybersearch2.classyjpa.entity.LoaderTaskImpl.java

/**
 * Execute persistence work in  background thread
 * Called on a worker thread to perform the actual load. 
 * @return Boolean object - Boolean.TRUE indicates successful result
 *//*from w  w  w . j a  v  a 2 s.  co  m*/
@Override
public Boolean loadInBackground() {
    // Hook into UncaughtExceptionHandler chain 
    final UncaughtExceptionHandler chain = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable uncaughtException) { // Save exception for post-execution error handling
            LoaderTaskImpl.this.uncaughtException = uncaughtException;
            chain.uncaughtException(t, uncaughtException);
        }
    });
    return persistenceContainer.executeInBackground(persistenceWork, transactionInfo);
}

From source file:org.stenerud.kscrash.KSCrash.java

/** Install the crash reporter.
 *
 * @param context The application context.
 *///from w w w.  jav a  2 s .  c om
public void install(Context context) throws IOException {
    String appName = context.getApplicationInfo().processName;
    File installDir = new File(context.getCacheDir().getAbsolutePath(), "KSCrash");
    install(appName, installDir.getCanonicalPath());

    // TODO: Put this elsewhere
    oldUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            KSCrash.this.reportJavaException(e);
            KSCrash.oldUncaughtExceptionHandler.uncaughtException(t, e);
        }
    });
}

From source file:com.cosmicsubspace.nerdyaudio.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    final Thread.UncaughtExceptionHandler orig = Thread.getDefaultUncaughtExceptionHandler();
    final Context c = getApplicationContext();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/*from  w  w  w . ja v a 2s  . c  o m*/
        public void uncaughtException(Thread thread, Throwable e) {
            Log2.log(0, this, "UncaughtException logged:", Log2.logToString(e));
            //Toast.makeText(c, ErrorLogger.logToString(e), Toast.LENGTH_SHORT).show();
            FileWriter f;
            try {
                f = new FileWriter(new File(Environment.getExternalStorageDirectory() + "/AFN_exceptions.txt"),
                        true);
                f.write("\n\n\n" + DateFormat.getDateTimeInstance().format(new Date()) + "\n");
                f.write(Log2.logToString(e));
                f.flush();
                f.close();
            } catch (IOException e1) {
                Log2.log(e1);
            } //Double exception?

            Log2.dumpLogsAsync();

            orig.uncaughtException(thread, e);
        }
    });

    requestPermission();

    Log2.log(1, this, "MainActivity Created!");

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    sf = getPreferences(Context.MODE_PRIVATE);

    String[] files = fileList();
    for (String i : files) {
        Log2.log(1, this, "File: " + i);
    }

    qm = QueueManager.getInstance();
    ap = AudioPlayer.getInstance();
    vb = VisualizationBuffer.getInstance();
    fm = FileManager.getInstance();
    wf = Waveform.getInstance();
    sbs = SidebarSettings.instantiate(getApplicationContext());
    vm = VisualizationManager.getInstance();

    volCtrl = new VolumeControls(getApplicationContext(), qm);

    //ap.setBufferFeedListener(vb);

    qm.passContext(getApplicationContext());
    fm.loadFromFile(this);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Library"));
    tabLayout.addTab(tabLayout.newTab().setText("Queue"));
    tabLayout.addTab(tabLayout.newTab().setText("Filters"));
    tabLayout.addTab(tabLayout.newTab().setText("Now Playing"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            int pos = tab.getPosition();
            if (pos == 0)
                ft.replace(R.id.tab_area, new LibraryFragment());
            else if (pos == 1)
                ft.replace(R.id.tab_area, new QueueFragment());
            else if (pos == 2)
                ft.replace(R.id.tab_area, new FiltersFragment());
            else if (pos == 3)
                ft.replace(R.id.tab_area, new NowPlayingFragment());

            ft.commit();
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
    getSupportFragmentManager().beginTransaction().replace(R.id.tab_area, new LibraryFragment()).commit();

    wfv = (PlayControlsView) findViewById(R.id.waveform);
    wfv.setSpacing(0);
    wfv.setTimestampVisibility(true);
    wfv.setTimestampSize(16);
    wfv.setTimestampColor(Color.WHITE);

    wfv.setTimestampOffset(30, 10);
    wfv.setTimestampBackgroundColor(Color.argb(128, 0, 0, 0));

    wfv.setWaveform(wf);
    qm.addQueueListener(wfv);
    qm.addProgressStringListener(wfv);

    vv = (VisualizationView) findViewById(R.id.visualization);

    dl = (DrawerLayout) findViewById(R.id.drawer_layout);

    dl.setDrawerListener(this);

    settingBtn = (RelativeLayout) findViewById(R.id.settings_btn);
    settingBtn.setOnClickListener(this);

    //statusText=(TextView)findViewById(R.id.status);

    sideContainer = (ScrollView) findViewById(R.id.drawer_scroll);
    sideContainer.addView(sbs.getView(getLayoutInflater(), sideContainer, null));

}