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.signserver.test.random.cli.Main.java

/**
 * @param args the command line arguments
 *///from   w w w . ja  v  a2  s .c  o  m
public static void main(String[] args) throws RemoteException, InvalidWorkerIdException {
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("(Debug logging is enabled)");
        }

        final CommandLine commandLine = new GnuParser().parse(OPTIONS, args);

        // Test suite
        final TestSuites ts;
        if (commandLine.hasOption(TEST_SUITE)) {
            ts = TestSuites.valueOf(commandLine.getOptionValue(TEST_SUITE));
        } else {
            throw new ParseException("Missing option: -" + TEST_SUITE);
        }

        // Time limit
        final long limitedTime;
        if (commandLine.hasOption(TIME_LIMIT)) {
            limitedTime = Long.parseLong(commandLine.getOptionValue(TIME_LIMIT));
        } else {
            limitedTime = -1;
        }

        // Random seed
        final long seed;
        if (commandLine.hasOption(RANDOM_SEED)) {
            seed = Long.parseLong(commandLine.getOptionValue(RANDOM_SEED));
        } else {
            seed = new Random().nextLong();
        }
        final Random masterRandom = new Random(seed);

        // Worker group 1
        final List<WorkerSpec> workerGroup1;
        if (commandLine.hasOption(WORKER_GROUP_1)) {
            workerGroup1 = new LinkedList<WorkerSpec>();
            final String list = commandLine.getOptionValue(WORKER_GROUP_1);
            String[] ids = list.split(",");
            for (String id : ids) {
                workerGroup1.add(WorkerSpec.fromString(id.trim()));
            }
        } else {
            workerGroup1 = null;
        }

        // Worker group 2
        final List<WorkerSpec> workerGroup2;
        if (commandLine.hasOption(WORKER_GROUP_2)) {
            workerGroup2 = new LinkedList<WorkerSpec>();
            final String list = commandLine.getOptionValue(WORKER_GROUP_2);
            String[] ids = list.split(",");
            for (String id : ids) {
                workerGroup2.add(WorkerSpec.fromString(id.trim()));
            }
        } else {
            workerGroup2 = null;
        }

        // Worker group 3
        final List<WorkerSpec> workerGroup3;
        if (commandLine.hasOption(WORKER_GROUP_3)) {
            workerGroup3 = new LinkedList<WorkerSpec>();
            final String list = commandLine.getOptionValue(WORKER_GROUP_3);
            String[] ids = list.split(",");
            for (String id : ids) {
                workerGroup3.add(WorkerSpec.fromString(id.trim()));
            }
        } else {
            workerGroup3 = null;
        }

        // Thread group 1
        final Integer threadGroup1;
        if (commandLine.hasOption(THREAD_GROUP_1)) {
            threadGroup1 = Integer.parseInt(commandLine.getOptionValue(THREAD_GROUP_1));
        } else {
            threadGroup1 = null;
        }

        // Thread group 2
        final Integer threadGroup2;
        if (commandLine.hasOption(THREAD_GROUP_2)) {
            threadGroup2 = Integer.parseInt(commandLine.getOptionValue(THREAD_GROUP_2));
        } else {
            threadGroup2 = null;
        }

        final AdminCommandHelper helper = new AdminCommandHelper();
        final IRemote workerSession = helper.getWorkerSession();
        final LinkedList<WorkerThread> threads = new LinkedList<WorkerThread>();
        final FailureCallback callback = new FailureCallback() {

            @Override
            public void failed(WorkerThread thread, String message) {
                // Stop
                for (WorkerThread w : threads) {
                    w.stopIt();
                }

                // Wait until all stoped
                try {
                    for (WorkerThread w : threads) {
                        w.join(1000);
                    }
                } catch (InterruptedException ex) {
                    LOG.error("Interrupted: " + ex.getMessage());
                }

                // Print message
                LOG.error(thread + ": " + message);
                exitCode = -1;
            }
        };
        Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread t, Throwable e) {
                LOG.error("Uncaught exception from t", e);
                callback.failed((WorkerThread) t, "Uncaught exception: " + e.getMessage());
            }
        };

        // Init context
        final TestContext context = new TestContext();
        context.setCallback(callback);
        context.setMasterRandom(masterRandom);
        context.setWorkerSession(workerSession);
        context.setPauser(new Pauser());
        context.setWorkerGroup1(workerGroup1);
        context.setThreadsGroup1(threadGroup1);
        context.setWorkerGroup2(workerGroup2);
        context.setThreadsGroup2(threadGroup2);
        context.setWorkerGroup3(workerGroup3);

        // Output information
        final StringBuilder buff = new StringBuilder();
        buff.append("SignServer Random Test\n").append("----------------------\n")
                .append("Random seed:          ").append(seed).append("\n").append("Time limit:           ")
                .append(limitedTime < 0 ? "unlimited" : limitedTime).append(" ms").append("\n")
                .append("Test suite:           ").append(ts).append("\n").append("Worker group 1:       ")
                .append(context.getWorkerGroup1()).append("\n").append("Worker group 2:       ")
                .append(context.getWorkerGroup2()).append("\n").append("Worker group 3:       ")
                .append(context.getWorkerGroup3()).append("\n").append("Thread group 1:       ")
                .append(context.getThreadsGroup1() == null ? "unspecified" : context.getThreadsGroup1())
                .append("\n").append("Thread group 2:       ")
                .append(context.getThreadsGroup2() == null ? "unspecified" : context.getThreadsGroup2())
                .append("\n");
        LOG.info(buff.toString());

        try {
            // First check all workers
            if (context.getWorkerGroup1() == null) {
                if (context.getThreadsGroup1() == null) {
                    throw new ParseException("Missing -workergroup1");
                }
            }
            Collection<WorkerSpec> allWorkers = new LinkedList<WorkerSpec>(context.getWorkerGroup1());
            if (context.getWorkerGroup2() != null) {
                allWorkers.addAll(context.getWorkerGroup2());
            }
            if (context.getWorkerGroup3() != null) {
                allWorkers.addAll(context.getWorkerGroup3());
            }
            for (WorkerSpec worker : allWorkers) {
                List<String> fatalErrors = context.getWorkerSession().getStatus(worker.getWorkerId())
                        .getFatalErrors();
                if (!fatalErrors.isEmpty()) {
                    System.err.println();
                    throw new FailedException("Worker " + worker + ": " + fatalErrors);
                }
            }

            // Init test suite
            switch (ts) {
            case signWhileUpdatingConfig:
                signWhileUpdatingConfig(threads, context);
                break;
            case signAndCountSignings:
                signAndCountSignings(threads, context);
                break;
            case signWhileRenewing:
                signWhileRenewing(threads, context);
                break;
            case signWithRandomUsers: {
                final String userPrefix = commandLine.getOptionValue(USERPREFIX, null);
                if (userPrefix == null) {
                    throw new ParseException("Missing required option: " + USERPREFIX);
                }
                final String userSuffixMin = commandLine.getOptionValue(USERSUFFIXMIN, null);
                if (userSuffixMin == null) {
                    throw new ParseException("Missing required option: " + USERSUFFIXMIN);
                }
                final String userSuffixMax = commandLine.getOptionValue(USERSUFFIXMAX, null);
                if (userSuffixMax == null) {
                    throw new ParseException("Missing required option: " + USERSUFFIXMAX);
                }
                signWithRandomUsers(threads, context, userPrefix, Integer.parseInt(userSuffixMin),
                        Integer.parseInt(userSuffixMax));
                break;
            }
            default:
                throw new Exception("Unsupported test suite: " + ts);
            }

            // Wait 1 second to start
            Thread.sleep(1000);

            // Start all threads
            for (WorkerThread w : threads) {
                w.setUncaughtExceptionHandler(handler);
                w.start();
            }

            // If time limited
            if (limitedTime > 0) {
                try {
                    Thread.sleep(limitedTime);
                } catch (InterruptedException ex) {
                    LOG.error("Interrupted: " + ex.getMessage());
                }
                // Stop all threads
                for (WorkerThread w : threads) {
                    w.stopIt();
                }
            }

            // Wait until all stopped
            try {
                for (WorkerThread w : threads) {
                    w.join();
                    LOG.info(w + ": Operations performed: " + w.getOperationsPerformed());
                }
            } catch (InterruptedException ex) {
                LOG.error("Interrupted: " + ex.getMessage());
            }
        } catch (Exception ex) {
            LOG.error("Failed: " + ex.getMessage(), ex);
            exitCode = -1;
        }
        System.exit(exitCode);
    } catch (ParseException ex) {
        LOG.error("Parse error: " + ex.getMessage());
        printUsage();
        System.exit(-2);
    }
}

From source file:com.webbfontaine.valuewebb.irms.factory.risk.RiskActionFactory.java

private static ExecutorService getExecutorService() {
    return Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),
            new BasicThreadFactory.Builder().namingPattern("RiskRuleHandler-%d")
                    .uncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                        @Override
                        public void uncaughtException(Thread t, Throwable e) {
                            LOGGER.error("", e);
                        }/*from   w ww. ja v  a 2s .  c om*/
                    }).build());
}

From source file:com.simadanesh.isatis.LoginActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); //To change body of generated methods, choose Tools | Templates.
    try {//from   w w w.  java2  s . c  o  m
        CommonPlace.loginActivity = this;
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
                Log.e("Alert", "Lets See if it Works !!!" + paramThrowable.toString());
            }
        });

        setContentView(R.layout.activity_login);
        Utility.InitializeDefatultSettings(this);

        edUserName = (EditText) findViewById(R.id.edUserName);
        edPassword = (EditText) findViewById(R.id.edPassword);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnCancel = (Button) findViewById(R.id.btnCancel);

        btnLogin.setOnClickListener(this);
        btnCancel.setOnClickListener(this);

        edUserName.setTypeface(Utility.getDefaultFont());
        edPassword.setTypeface(Utility.getDefaultFont());
        btnLogin.setTypeface(Utility.getDefaultFont());
        btnCancel.setTypeface(Utility.getDefaultFont());
        edPassword.setImeActionLabel("Login", KeyEvent.KEYCODE_ENTER);
        // edPassword.setImeActionLabel("Login", KeyEvent.IME_ACTION_DONE);
        edPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == KeyEvent.KEYCODE_ENTER) {
                    Login();
                }
                return true;
            }
        });

    } catch (Exception ex) {
        Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show();
    }

}

From source file:com.microsoft.onenote.pickerlib.OneNotePickerActivity.java

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

    // Handle uncaught and system exceptions
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override//ww  w.ja v  a 2  s. com
        public void uncaughtException(Thread thread, Throwable throwable) {
            handleError(throwable);
        }
    });

    // Use the slide in animation
    overridePendingTransition(R.anim.slide_in, R.anim.hold);

    readExtras();

    // Determine the theme to use
    if (mThemeColor == null || mThemeColor == OneNotePickerThemeColor.LIGHT) {
        setTheme(R.style.OneNotePicker_Light);
    } else if (mThemeColor == OneNotePickerThemeColor.DARK) {
        setTheme(R.style.OneNotePicker_Dark);
    }

    setUpActionBar();

    setContentView(R.layout.activity_onenote_picker);

    // Retrieve the controller fragment
    FragmentManager fm = getSupportFragmentManager();
    mControllerFragment = (ControllerFragment) fm.findFragmentByTag("controller");

    if (savedInstanceState == null) {
        mNotebooksFragment = new PickerListFragment(new UiActionBarSettings(getString(R.string.text_notebooks),
                getString(R.string.text_onenote), false));

        mNotebooksFragment.mLoading = true;

        // Create the controller fragment the first time
        if (mControllerFragment == null) {
            mControllerFragment = new ControllerFragment(mAccessToken, mNotebooksFragment);
            fm.beginTransaction().add(mControllerFragment, "controller").commit();
        }

        // Show the first fragment
        addFragment(mNotebooksFragment);
    }

}

From source file:com.google.reviewit.app.ReviewItApp.java

@Override
public void onCreate() {
    registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
        @Override//  ww  w .j a  v a  2  s. co  m
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            currentActivity = (FragmentActivity) activity;
        }

        @Override
        public void onActivityStarted(Activity activity) {
        }

        @Override
        public void onActivityResumed(Activity activity) {
        }

        @Override
        public void onActivityPaused(Activity activity) {
        }

        @Override
        public void onActivityStopped(Activity activity) {
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            currentActivity = null;
        }
    });

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable t) {
            Log.e(TAG, "Application failure", t);
            if (currentActivity != null) {
                FragmentManager fragmentManager = currentActivity.getSupportFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.mainFrame, ErrorFragment.create(t)).commit();
            }
        }
    });
    super.onCreate();
}

From source file:own.projects.lemiroapp.GameModeActivity.java

private void setDefaultUncaughtExceptionHandler() {
    try {/*www.j  a v a2  s . c  o  m*/
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread t, Throwable e) {
                StackTraceElement[] trace = e.getStackTrace();
                String tracem = "";
                for (int i = 0; i < trace.length; i++) {
                    tracem += trace[i] + "\n";
                }
                Log.e("GameModeActivity", "Uncaught Exception detected in thread {}" + t + e + "\n" + tracem);

                final String message = e.getMessage();

                //display message so that the user sees that something went wrong
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new AlertDialog.Builder(THIS).setIcon(android.R.drawable.ic_dialog_info)
                                .setTitle("Error").setMessage(message).setCancelable(false)
                                .setNeutralButton("Quit", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        finish();
                                    }
                                }).show();
                    }
                });

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

From source file:net.freifunk.android.discover.Main.java

private static void setDefaultUncaughtExceptionHandler() {
    try {//  ww w . j ava 2 s. c  o  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.jshybugger.server.DebugServer.java

/**
 * Instantiates a new debug server.//  www.  j  av a2 s . com
 * @param debugPort the tcp listen port number
 * @param context application context
 * @param productName product identifier
 * @param application the application context
 * @throws IOException 
 */
public DebugServer(final int debugPort) throws IOException {

    Thread webServerThread = new Thread(new Runnable() {

        @Override
        public void run() {

            debugSessionsHandler = new DebugSessionsWebSocketHandler(DebugServer.this);
            webServer = WebServers.createWebServer(debugPort).add("/", getRootHandler())
                    .add("/json/version", getVersionHandler()).add("/json", getJsonHandler())
                    .add("/devtools/page/.*", debugSessionsHandler);

            webServer.connectionExceptionHandler(new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread t, Throwable e) {
                    Log.e(TAG, "Debug server terminated unexpected", e);
                }
            });

            // increase content length: default 65k length is sometimes to less
            ((NettyWebServer) webServer).maxContentLength(131072);

            Log.i(TAG, "starting debug server on port: " + debugPort);
            webServer.start();

            debugServerStarted.countDown();
        }

    });

    webServerThread.start();
    webServerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            Log.e(TAG, "Bootstraping debug server terminated unexpected", e);
        }
    });
}

From source file:mx.com.gaby.service.AsynchronousService.java

public void procesar() {
    final Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            System.out.println("Uncaught exception: " + ex);
            System.out.println("TErminar procesamiento aqu: " + ex);

            resultDto.setProcesando(false);
            resultDto.setIndex(0);//from  w  w w. j ava2 s.c o  m
            resultDto.setMessage("Uncaught exception - Error de procesamiento dentro del hilo");
            resultDto.setTotalRecords(0);
        }
    };

    try {
        /*Thread t = */
        (new Thread(new Runnable() {
            public void run() {
                Thread.currentThread().setUncaughtExceptionHandler(h);

                enProceso = true;
                resultDto.setProcesando(true);
                resultDto.setTotalRecords(100);

                try {
                    int h = 0;
                    for (h = 1; h <= 100; h++) {
                        resultDto.setIndex(h);
                        resultDto.setMessage("Enviados " + h + " de 100");

                        System.out.println(h + ".- Ejecutando ...");

                        try {
                            for (int i = 1; i <= 100; i++) {
                                Long maxMemory = Runtime.getRuntime().maxMemory();
                                int[] matrix = new int[(int) (maxMemory + 1)];
                                for (int j = 0; j < matrix.length; ++j) {
                                    matrix[j] = j + 1;
                                }
                            }
                        } catch (OutOfMemoryError e) {
                            System.out.println(" : Memory Use : " + e.getMessage());
                        }
                    }

                    Thread.sleep(2000);

                    resultDto.setProcesando(false);
                } catch (InterruptedException ie) {
                    System.out.println("InterruptedException run");

                    resultDto.setProcesando(false);
                    resultDto.setIndex(0);
                    resultDto.setMessage("InterruptedException - Error de procesamiento dentro del hilo");
                    resultDto.setTotalRecords(0);
                }
            }
        })).start();
        //t.setUncaughtExceptionHandler(h);
        //t.start();
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());

        resultDto.setProcesando(false);
        resultDto.setIndex(0);
        resultDto.setMessage("Exception - Error de procesamiento dentro del hilo");
        resultDto.setTotalRecords(0);
    }

}

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

@Override
public void onCreate() {
    super.onCreate();
    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    try {/*w w  w  .  j  av a 2  s . c  om*/
        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);
        }
    });
}