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:net.freifunk.android.discover.Main.java

private static void setDefaultUncaughtExceptionHandler() {
    try {/*  w w  w.j  a  v a 2 s .  co  m*/
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread t, Throwable e) {

                Log.e("EXCEPTION", "Uncaught Exception detected in thread {}" + t + " -- " + e);
                Log.e("EXCEPTION", "STACK", e);

                //e.getStackTrace()
            }
        });
    } catch (SecurityException e) {
        Log.e("EXCEPTION", "Could not set the Default Uncaught Exception Handler", e);
    }
}

From source file:org.apache.pulsar.proxy.server.ProxyServiceStarter.java

public ProxyServiceStarter(String[] args) throws Exception {
    // setup handlers
    removeHandlersForRootLogger();//from w ww . ja va2 s  .  co  m
    install();

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
    Thread.setDefaultUncaughtExceptionHandler((thread, exception) -> {
        System.out.println(String.format("%s [%s] error Uncaught exception in thread %s: %s",
                dateFormat.format(new Date()), thread.getContextClassLoader(), thread.getName(),
                exception.getMessage()));
    });

    JCommander jcommander = new JCommander();
    try {
        jcommander.addObject(this);
        jcommander.parse(args);
        if (help || isBlank(configFile)) {
            jcommander.usage();
            return;
        }
    } catch (Exception e) {
        jcommander.usage();
        System.exit(-1);
    }

    // load config file
    final ProxyConfiguration config = PulsarConfigurationLoader.create(configFile, ProxyConfiguration.class);

    if (!isBlank(zookeeperServers)) {
        // Use zookeeperServers from command line
        config.setZookeeperServers(zookeeperServers);
    }

    if (!isBlank(globalZookeeperServers)) {
        // Use globalZookeeperServers from command line
        config.setConfigurationStoreServers(globalZookeeperServers);
    }
    if (!isBlank(configurationStoreServers)) {
        // Use configurationStoreServers from command line
        config.setConfigurationStoreServers(configurationStoreServers);
    }

    if ((isBlank(config.getBrokerServiceURL()) && isBlank(config.getBrokerServiceURLTLS()))
            || config.isAuthorizationEnabled()) {
        checkArgument(!isEmpty(config.getZookeeperServers()), "zookeeperServers must be provided");
        checkArgument(!isEmpty(config.getConfigurationStoreServers()),
                "configurationStoreServers must be provided");
    }

    if ((!config.isTlsEnabledWithBroker() && isBlank(config.getBrokerWebServiceURL()))
            || (config.isTlsEnabledWithBroker() && isBlank(config.getBrokerWebServiceURLTLS()))) {
        checkArgument(!isEmpty(config.getZookeeperServers()), "zookeeperServers must be provided");
    }

    java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    AuthenticationService authenticationService = new AuthenticationService(
            PulsarConfigurationLoader.convertFrom(config));
    // create proxy service
    ProxyService proxyService = new ProxyService(config, authenticationService);
    // create a web-service
    final WebServer server = new WebServer(config, authenticationService);

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            proxyService.close();
            server.stop();
        } catch (Exception e) {
            log.warn("server couldn't stop gracefully {}", e.getMessage(), e);
        }
    }));

    proxyService.start();

    // Setup metrics
    DefaultExports.initialize();
    addWebServerHandlers(server, config, proxyService.getDiscoveryProvider());

    // start web-service
    server.start();
}

From source file:com.jwork.spycamera.SpyCamActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    int v = 0;/* w ww . j a  va 2  s. c o m*/
    try {
        v = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
    } catch (NameNotFoundException e) {
    }
    log.v(this, "onCreate(): " + this.getString(R.string.app_versionName) + "(" + v + ")");
    Utility.setGlobalContext(this);

    defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    crashHandler = CrashHandler.getInstance(this, defaultUEH);
    Thread.setDefaultUncaughtExceptionHandler(crashHandler);
    setContentView(R.layout.activity_main);
    fragment = (MainFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentMain);

    getDefaultOrientation();
    String action = getIntent().getAction();

    log.d(this, "action:" + action);
    if (action == null || action.equals("android.intent.action.MAIN") || action.equals(ACTION_WIDGET[0])) {
        fragment.setVisible();
    } else {
        for (int i = 1; i < ACTION_WIDGET.length; i++) {
            if (action.equals(ACTION_WIDGET[i])) {
                if (ConfigurationUtility.getInstance(this).isDisableBackgroundService()) {
                    fragment.setVisible();
                } else {
                    fragment.setVisibleForWidget();
                }
                fragment.callWidgetAction(i);
                return;
            }
        }
        fragment.setVisible();
    }
}

From source file:com.rukiasoft.androidapps.comunioelpuntal.crashlogs.ExceptionHandler.java

public static boolean register(Context _context) {
    Log.i(TAG, "Registering default exceptions handler");
    context = _context;/*  www .j a  v a 2 s . c  om*/
    // Get information about the Package
    PackageManager pm = context.getPackageManager();
    try {
        PackageInfo pi;
        // Version
        pi = pm.getPackageInfo(context.getPackageName(), 0);
        G.APP_VERSION = pi.versionName;
        // Package name
        G.APP_PACKAGE = pi.packageName;
        // Files dir for storing the stack traces
        G.FILES_PATH = context.getFilesDir().getAbsolutePath();
        // Device model
        G.PHONE_MODEL = android.os.Build.MODEL;
        // Android version
        G.ANDROID_VERSION = android.os.Build.VERSION.RELEASE;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    /*Log.d(TAG, "APP_VERSION: " + G.APP_VERSION);
      Log.d(TAG, "APP_PACKAGE: " + G.APP_PACKAGE);
    Log.d(TAG, "FILES_PATH: " + G.FILES_PATH);*/

    boolean stackTracesFound = false;
    // We'll return true if any stack traces were found
    if (searchForStackTraces().length > 0) {
        stackTracesFound = true;
    }

    new Thread() {
        @Override
        public void run() {
            // First of all transmit any stack traces that may be lying around
            submitStackTraces();
            UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
            if (currentHandler != null) {
                Log.d(TAG, "current handler class=" + currentHandler.getClass().getName());
            }
            // don't register again if already registered
            if (!(currentHandler instanceof DefaultExceptionHandler)) {
                Log.d(TAG, "Register default exceptions handler");
                Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler(currentHandler));
            }
        }
    }.start();

    return stackTracesFound;
}

From source file:fi.iki.dezgeg.matkakorttiwidget.gui.MatkakorttiWidgetApp.java

@Override
public void onCreate() {
    super.onCreate();
    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    try {//from www . j  a v  a 2  s. com
        packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    prevUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable e) {
            try {
                reportException("UncaughtExceptionHandler", e).get(8, TimeUnit.SECONDS);
            } catch (Throwable t) {
                // ignore
            }

            if (prevUncaughtExceptionHandler != null)
                prevUncaughtExceptionHandler.uncaughtException(thread, e);
        }
    });
}

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

@PostConstruct
public void init() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/*  www  . ja va 2 s. co m*/
        public void uncaughtException(Thread t, Throwable e) {
            logger.error("Uncaught exception", e);
        }
    });
}

From source file:zxmax.tools.timerreview.Main.java

public Main() throws Exception {

    MyUncaughtExceptionHandler myUncaughtExceptionHandler = new MyUncaughtExceptionHandler(LOGGER);

    Thread.setDefaultUncaughtExceptionHandler(myUncaughtExceptionHandler);
    final TrayIcon trayIcon = getTrayIcon();
    final TrayIconMouseMotionListener listener = new TrayIconMouseMotionListener(trayIcon);
    trayIcon.addMouseMotionListener(listener);

    Register.put(TrayIcon.class, trayIcon);
    Register.put(TrayIconMouseMotionListener.class, listener);
    String implementationVersion = zxmax.tools.timerreview.Main.class.getPackage().getImplementationVersion();
    Register.put(ApplicationInfo.class, new ApplicationInfo(implementationVersion));

    // ObjectValidator[] validators = new ObjectValidator[] {
    // new TomatoValidator(), new TomatoReviewValidator() };

    Map<Class, ObjectValidator> validationCommands = new HashedMap();
    validationCommands.put(Tomato.class, new TomatoValidator());
    validationCommands.put(TomatoReview.class, new TomatoReviewValidator());

    Register.put(ValidatorService.class, new ValidatorService(validationCommands));

    for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
            UIManager.setLookAndFeel(info.getClassName());
            break;
        }/*www .  j a v a2  s .  c  o m*/
    }

    final StartTimerWindow timer = new StartTimerWindow();
    timer.setVisible(true);
    timer.createBufferStrategy(1);

    // HibernateBasicDaoImpl basicDao = new HibernateBasicDaoImpl();
    // Register.put(HibernateBasicDaoImpl.class, basicDao);

}

From source file:uk.ac.horizon.ug.exploding.client.logging.LoggingUtils.java

/** init */
public static synchronized void init(Context context) {
    String packageName = context.getApplicationInfo().packageName;
    if (applicationDirName != null) {
        if (applicationDirName.equals(packageName))
            // no-op
            return;
        // close and re-initialise?
        Log.w(TAG, "Re-initialise logging with different package name: " + packageName + " vs "
                + applicationDirName);/*from   ww w  .j a v  a 2 s  .co  m*/
        // TODO Log
        return;
    }
    applicationDirName = packageName;
    String fileName = "log_" + System.currentTimeMillis() + ".json";
    File dir = new File(LOG_ROOT_DIR, applicationDirName);
    if (dir.mkdir())
        Log.i(TAG, "Created log directory " + dir);
    if (!dir.exists()) {
        Log.e(TAG, "Log directory does not exist: " + dir + " - cannot log");
        return;
    }
    if (!dir.isDirectory()) {
        Log.e(TAG, "Log directory is not a directory: " + dir + " - cannot log");
        return;
    }
    File file = new File(LOG_ROOT_DIR + applicationDirName, fileName);
    if (file.exists())
        Log.w(TAG, "Appending to existing log: " + file);
    try {
        logWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(file, true), Charset.forName("UTF-8")));
        Log.i(TAG, "Logging to " + file);
        logFile = file;
    } catch (Exception e) {
        Log.e(TAG, "Opening log file " + file + " - cannot log", e);
        logWriter = null;
    }
    logHeader(context);

    // dump exceptions!
    final UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            // TODO Auto-generated method stub
            try {
                JSONStringer js = new JSONStringer();
                js.object();
                js.key("thread");
                js.value(thread.getName());
                js.key("exception");
                js.value(ex.toString());
                js.key("stackTrace");
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                ex.printStackTrace(pw);
                js.value(sw.getBuffer().toString());
                js.endObject();
                log(LOGTYPE_UNCAUGHT_EXCEPTION, js.toString());
            } catch (Exception e) {
                Log.e(TAG, "Logging uncaught exception", e);
            }
            // cascade
            if (handler != null)
                handler.uncaughtException(thread, ex);
        }
    });
}

From source file:at.wada811.dayscounter.view.activity.SettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // catch UncaughtException
    Thread.setDefaultUncaughtExceptionHandler(new CrashExceptionHandler(getApplicationContext()));
    super.onCreate(savedInstanceState);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    setContentView(R.layout.activity_settings);
    ButterKnife.inject(this);
    // Window size dialog
    WindowManager.LayoutParams params = getWindow().getAttributes();
    params.width = WindowManager.LayoutParams.MATCH_PARENT;
    params.height = WindowManager.LayoutParams.MATCH_PARENT;
    getWindow().setAttributes(params);//  w w w.j av a  2 s  .co  m
    LogUtils.d();
    // check Crash report
    File file = ResourceUtils.getFile(this, CrashExceptionHandler.FILE_NAME);
    if (file.exists()) {
        startActivity(new Intent(this, CrashReportActivity.class));
        finish();
        return;
    }
    // AppWidgetId
    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if (extras != null) {
        appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
    }
    LogUtils.d("appWidgetId: " + appWidgetId);

    WidgetModel model = new WidgetModel(this, appWidgetId);
    viewModel = new Widget1x1ViewModel(this, model);
    // Title
    new EditTextBinding(titleEditText).bind(new Func<EditText, String>() {
        @Override
        public String apply(EditText editText) {
            return editText.getText().toString();
        }
    }, viewModel.getTitle(), new EditTextTextChanged() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            titleTextView.setText(viewModel.getTitle().getValue());
        }
    });
    titleEditText.setText(viewModel.getTitle().getValue());
    // Date
    String date = viewModel.getDate().getValue();
    LogUtils.d("date: " + date);
    LocalDateTime dateTime = date != null ? new LocalDateTime(date) : LocalDateTime.now();
    DatePickerBinding datePickerBinding = new DatePickerBinding(datePicker);
    datePickerBinding.bind(new Func<DatePicker, String>() {
        @Override
        public String apply(DatePicker datePicker) {
            return DatePickerUtils.format(datePicker);
        }
    }, viewModel.getDate(), new OnDateChangedListener() {
        @Override
        public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            diffTextView.setText(viewModel.getDiff().getValue());
            diffTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, viewModel.getDiffTextSize().getValue());
            daysTextView.setText(viewModel.getComparison().getValue());
        }
    });
    datePicker.init(dateTime.getYear(), dateTime.getMonthOfYear() - 1, dateTime.getDayOfMonth(),
            datePickerBinding.getOnDateChangedListener());
    diffTextView.setText(viewModel.getDiff().getValue());
    diffTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, viewModel.getDiffTextSize().getValue());
    daysTextView.setText(viewModel.getComparison().getValue());

    // Button
    submitButton.setOnClickListener(this);
}

From source file:com.shigengyu.hyperion.scenarios.concurrent.TransitionParameterSetTest.java

@Test
public void setAndGetParameterValues() {
    TransitionParameterSet parameters = TransitionParameterSet.create();

    ThreadUncaughtExceptionHandler exceptionHandler = new ThreadUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);

    Set<Thread> threads = new HashSet<Thread>();

    for (int i = 0; i < NUM_OF_THREADS; i++) {
        SetAndGetThread thread = new SetAndGetThread(parameters);
        thread.start();/* ww  w . j a  v  a2s. com*/
        threads.add(thread);
    }

    for (Thread thread : threads) {
        try {
            thread.join();
        } catch (InterruptedException e) {
            Assert.fail(ExceptionUtils.getFullStackTrace(e));
        }
    }

    if (exceptionHandler.getExceptions().size() > 0) {
        ExceptionUtils.getFullStackTrace(exceptionHandler.getExceptions().get(0));
    }
}