List of usage examples for java.lang Thread setDefaultUncaughtExceptionHandler
public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh)
From source file:org.ut.biolab.medsavant.MedSavantClient.java
private static void setExceptionHandler() { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override/*from w w w. ja va 2 s. com*/ public void uncaughtException(Thread t, Throwable e) { LOG.info("Global exception handler caught: " + t.getName() + ": " + e); if (e instanceof InvocationTargetException) { e = ((InvocationTargetException) e).getCause(); } if (e instanceof SessionExpiredException) { SessionExpiredException see = (SessionExpiredException) e; MedSavantExceptionHandler.handleSessionExpiredException(see); return; } if (e instanceof LockException) { DialogUtils.displayMessage("Cannot modify database", "<html>Another process is making changes.<br/>Please try again later.</html>"); return; } e.printStackTrace(); DialogUtils.displayException("Error", e.getLocalizedMessage(), e); } }); }
From source file:net.sourceforge.kalimbaradio.androidapp.util.Util.java
public static void setUncaughtExceptionHandler(Context context) { Thread.UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler(); if (!(handler instanceof SubsonicUncaughtExceptionHandler)) { Thread.setDefaultUncaughtExceptionHandler(new SubsonicUncaughtExceptionHandler(context)); }//from ww w . j av a2 s. c o m }
From source file:eu.intermodalics.tango_ros_streamer.activities.RunningActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { Log.e(TAG, "Uncaught exception of type " + e.getClass()); e.printStackTrace();/*w w w .j a v a 2 s . c o m*/ } }); // The following piece of code allows networking in main thread. // e.g. Restart Tango button calls a ROS service in UI thread. if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } mSharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); mRunLocalMaster = mSharedPref.getBoolean(getString(R.string.pref_master_is_local_key), false); mMasterUri = mSharedPref.getString(getString(R.string.pref_master_uri_key), getResources().getString(R.string.pref_master_uri_default)); mCreateNewMap = mSharedPref.getBoolean(getString(R.string.pref_create_new_map_key), false); String logFileName = mSharedPref.getString(getString(R.string.pref_log_file_key), getString(R.string.pref_log_file_default)); setupUI(); mLogger = new Logger(this, mLogTextView, TAGS_TO_LOG, logFileName, LOG_TEXT_MAX_LENGTH); }
From source file:pt.ua.tm.neji.cli.Main.java
private static void installUncaughtExceptionHandler() { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override//from w ww . j a v a 2 s . c o m public void uncaughtException(Thread thread, Throwable thrwbl) { if (thrwbl instanceof ThreadDeath) { logger.warn("Ignoring uncaught ThreadDead exception."); return; } logger.error("Uncaught exception on cli thread, aborting.", thrwbl); System.exit(0); } }); }
From source file:edu.brown.hstore.HStoreSite.java
/** * Constructor//from www. j a va 2s .co m * @param coordinators * @param p_estimator */ protected HStoreSite(int site_id, CatalogContext catalogContext, HStoreConf hstore_conf) { assert (hstore_conf != null); assert (catalogContext != null); this.hstore_conf = hstore_conf; this.catalogContext = catalogContext; this.catalog_site = this.catalogContext.getSiteById(site_id); if (this.catalog_site == null) throw new RuntimeException("Invalid site #" + site_id); this.catalog_host = this.catalog_site.getHost(); this.site_id = this.catalog_site.getId(); this.site_name = HStoreThreadManager.getThreadName(this.site_id, null); final int num_partitions = this.catalogContext.numberOfPartitions; this.local_partitions.addAll(CatalogUtil.getLocalPartitionIds(catalog_site)); int num_local_partitions = this.local_partitions.size(); for (Status s : Status.values()) { this.deletable_txns.put(s, new ConcurrentLinkedQueue<Long>()); } // FOR this.executors = new PartitionExecutor[num_partitions]; this.executor_threads = new Thread[num_partitions]; this.depTrackers = new DependencyTracker[num_partitions]; // Get the hasher we will use for this HStoreSite this.hasher = ClassUtil.newInstance(hstore_conf.global.hasher_class, new Object[] { this.catalogContext, num_partitions }, new Class<?>[] { CatalogContext.class, int.class }); this.p_estimator = new PartitionEstimator(this.catalogContext, this.hasher); this.remoteTxnEstimator = new RemoteEstimator(this.p_estimator); // ARIES if (hstore_conf.site.aries) { // Don't use both recovery modes assert (hstore_conf.site.snapshot == false); LOG.warn("Starting ARIES recovery at site"); String siteName = HStoreThreadManager.formatSiteName(this.getSiteId()); String ariesSiteDirPath = hstore_conf.site.aries_dir + File.separatorChar + siteName + File.separatorChar; this.m_ariesLogFileName = ariesSiteDirPath + m_ariesDefaultLogFileName; int numPartitionsPerSite = this.catalog_site.getPartitions().size(); int numSites = this.catalogContext.numberOfSites; LOG.warn("ARIES : Log Native creation :: numSites : " + numSites + " numPartitionsPerSite : " + numPartitionsPerSite); this.m_ariesLog = new AriesLogNative(numSites, numPartitionsPerSite, this.m_ariesLogFileName); this.m_recoveryLog = new VoltLogger("RECOVERY"); } // **IMPORTANT** // Always clear out the CatalogUtil and BatchPlanner before we start our new HStoreSite // TODO: Move this cache information into CatalogContext CatalogUtil.clearCache(this.catalogContext.database); BatchPlanner.clear(this.catalogContext.numberOfPartitions); TransactionCounter.resetAll(this.catalogContext); // Only preload stuff if we were asked to if (hstore_conf.site.preload) { if (debug.val) LOG.debug("Preloading cached objects"); try { // Don't forget our CatalogUtil friend! CatalogUtil.preload(this.catalogContext.database); // Load up everything the QueryPlanUtil PlanNodeUtil.preload(this.catalogContext.database); // Then load up everything in the PartitionEstimator this.p_estimator.preload(); } catch (Exception ex) { throw new RuntimeException("Failed to prepare HStoreSite", ex); } } // Offset Hack this.local_partition_offsets = new int[num_partitions]; Arrays.fill(this.local_partition_offsets, HStoreConstants.NULL_PARTITION_ID); int offset = 0; for (int partition : this.local_partitions) { this.local_partition_offsets[partition] = offset++; } // FOR // ------------------------------- // THREADS // ------------------------------- EventObserver<Pair<Thread, Throwable>> observer = new EventObserver<Pair<Thread, Throwable>>() { @Override public void update(EventObservable<Pair<Thread, Throwable>> o, Pair<Thread, Throwable> arg) { Thread thread = arg.getFirst(); Throwable error = arg.getSecond(); String threadName = "<unknown>"; if (thread != null) threadName = thread.getName(); LOG.fatal(String.format("Thread %s had a fatal error: %s", threadName, (error != null ? error.getMessage() : null))); error.printStackTrace(); hstore_coordinator.shutdownClusterBlocking(error); } }; this.exceptionHandler.addObserver(observer); Thread.setDefaultUncaughtExceptionHandler(this.exceptionHandler); // HStoreSite Thread Manager (this always get invoked first) this.threadManager = new HStoreThreadManager(this); // Distributed Transaction Queue Manager this.txnQueueManager = new TransactionQueueManager(this); // One Transaction Cleaner for every eight partitions int numCleaners = (int) Math.ceil(num_local_partitions / 8.0); for (int i = 0; i < numCleaners; i++) { this.txnCleaners.add(new TransactionCleaner(this)); } // FOR // MapReduce Transaction helper thread if (catalogContext.getMapReduceProcedures().isEmpty() == false) { this.mr_helper = new MapReduceHelperThread(this); } else { this.mr_helper = null; } // Separate TransactionIdManager per partition if (hstore_conf.site.txn_partition_id_managers) { this.txnIdManagers = new TransactionIdManager[num_partitions]; for (int partition : this.local_partitions) { this.txnIdManagers[partition] = new TransactionIdManager(partition); } // FOR } // Single TransactionIdManager for the entire site else { this.txnIdManagers = new TransactionIdManager[] { new TransactionIdManager(this.site_id) }; } // Command Logger if (hstore_conf.site.commandlog_enable) { // It would be nice if we could come up with a unique name for this // invocation of the system (like the cluster instanceId). But for now // we'll just write out to our directory... java.util.Date date = new java.util.Date(); Timestamp current = new Timestamp(date.getTime()); String nonce = Long.toString(current.getTime()); File logFile = new File(hstore_conf.site.commandlog_dir + File.separator + this.getSiteName().toLowerCase() + "_" + nonce + CommandLogWriter.LOG_OUTPUT_EXT); this.commandLogger = new CommandLogWriter(this, logFile); } else { this.commandLogger = null; } // AdHoc Support if (hstore_conf.site.exec_adhoc_sql) { this.asyncCompilerWorkThread = new AsyncCompilerWorkThread(this, this.site_id); } else { this.asyncCompilerWorkThread = null; } // The AntiCacheManager will allow us to do special things down in the EE // for evicted tuples if (hstore_conf.site.anticache_enable) { this.anticacheManager = new AntiCacheManager(this); } else { this.anticacheManager = null; } // ------------------------------- // NETWORK SETUP // ------------------------------- this.voltNetwork = new VoltNetwork(this); this.clientInterface = new ClientInterface(this, this.catalog_site.getProc_port()); // ------------------------------- // TRANSACTION ESTIMATION // ------------------------------- // Transaction Properties Initializer this.txnInitializer = new TransactionInitializer(this); // CACHED MESSAGES this.REJECTION_MESSAGE = "Transaction was rejected by " + this.getSiteName(); // ------------------------------- // STATS SETUP // ------------------------------- this.initTxnProcessors(); this.initStatSources(); // Profiling if (hstore_conf.site.profiling) { this.profiler = new HStoreSiteProfiler(); if (hstore_conf.site.status_exec_info) { this.profiler.network_idle.resetOnEventObservable(this.startWorkload_observable); } } else { this.profiler = null; } this.status_monitor = new HStoreSiteStatus(this, hstore_conf); LoggerUtil.refreshLogging(hstore_conf.global.log_refresh); }
From source file:ibme.sleepap.recording.SignalsRecorder.java
/** * Called when the activity is first created. onStart() is called * immediately afterwards.//from w ww . ja va2s . c om */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.signals_recorder); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // Log both handled and unhandled issues. if (sharedPreferences.getBoolean(Constants.PREF_WRITE_LOG, Constants.DEFAULT_WRITE_LOG)) { String bugDirPath = Environment.getExternalStorageDirectory().toString() + "/" + getString(R.string.app_name) + "/" + Constants.FILENAME_LOG_DIRECTORY; File bugDir = new File(bugDirPath); if (!bugDir.exists()) { bugDir.mkdirs(); } String handledFileName = bugDirPath + "/logcat" + System.currentTimeMillis() + ".trace"; String unhandledFileName = bugDirPath + "/unhandled" + System.currentTimeMillis() + ".trace"; // Log any warning or higher, and write it to handledFileName. String[] cmd = new String[] { "logcat", "-f", handledFileName, "*:W" }; try { Runtime.getRuntime().exec(cmd); } catch (IOException e1) { Log.e(Constants.CODE_APP_TAG, "Error creating bug files", e1); } Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(unhandledFileName)); } bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); extras = getIntent().getBundleExtra(Constants.EXTRA_RECORDING_SETTINGS); actigraphyEnabled = extras.getBoolean(Constants.EXTRA_COLLECT_ACTIGRAPHY, false); audioEnabled = extras.getBoolean(Constants.EXTRA_COLLECT_AUDIO, false); ppgEnabled = extras.getBoolean(Constants.EXTRA_COLLECT_PPG, false); dateTimeString = DateFormat.format(Constants.PARAM_DATE_FORMAT, System.currentTimeMillis()).toString(); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); String appDirPath = Environment.getExternalStorageDirectory().toString() + "/" + getString(R.string.app_name); filesDirPath = appDirPath + "/" + dateTimeString + "/"; lastAccelerometerRecordedTime = 0; lastPositionChangeTime = System.currentTimeMillis(); PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.CODE_APP_TAG); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); actigraphyQueue = new LinkedList<Double>(); positionDisplay = (TextView) findViewById(R.id.position); recordingSign = (ImageView) findViewById(R.id.recordingSign); for (int i = 0; i < 5; ++i) { totalPositionTime[i] = 0; } // Battery check receiver. registerReceiver(this.batteryLevelReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); // Button to stop the recording. Button stopButton = (Button) findViewById(R.id.buttonStop); stopButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View viewNext) { stopRecording(); } }); // Button to reconnect the bluetooth. reconnectButton = (Button) findViewById(R.id.reconnectButton); reconnectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View viewNext) { String macAddress = sharedPreferences.getString(Constants.PREF_MAC_ADDRESS, Constants.DEFAULT_MAC_ADDRESS); noninManager = null; noninManager = new NoninManager(getApplicationContext(), bluetoothAdapter, macAddress, new PpgHandler(SignalsRecorder.this)); noninManager.start(); reconnectButton.setEnabled(false); reconnectButton.setClickable(false); } }); // Create a folder for the recordings, and delete any extra recordings. File dir = new File(filesDirPath); if (!dir.exists()) { dir.mkdirs(); File appDir = new File(appDirPath); // Create a list of recordings in the app directory. These // are named by the date on which they were formed and so can be in // date order (earliest first). String[] recordingDirs = appDir.list(); Arrays.sort(recordingDirs); // How many more recordings do we have in the app directory than are // specified in the settings? Should account for questionnaires // file, // which must exist for the user to have gotten to this stage // (checklist). int numberRecordings = 0; for (String folderOrFileName : recordingDirs) { if (!folderOrFileName.equals(Constants.FILENAME_QUESTIONNAIRE) && !folderOrFileName.equals(Constants.FILENAME_LOG_DIRECTORY) && !folderOrFileName.equals(Constants.FILENAME_FEEDBACK_DIRECTORY)) { numberRecordings++; } } int extraFiles = numberRecordings - Integer.parseInt(sharedPreferences .getString(Constants.PREF_NUMBER_RECORDINGS, Constants.DEFAULT_NUMBER_RECORDINGS)); if (extraFiles > 0) { // Too many recordings. Delete the earliest n, where n is the // number of extra files. boolean success; int nDeleted = 0; for (String candidateFolderName : recordingDirs) { if (nDeleted >= extraFiles) { // We've deleted enough already. break; } if (candidateFolderName.equals(Constants.FILENAME_QUESTIONNAIRE) || candidateFolderName.equals(Constants.FILENAME_LOG_DIRECTORY) || candidateFolderName.equals(Constants.FILENAME_FEEDBACK_DIRECTORY)) { // Don't delete questionnaire file or log/feedback // directory. continue; } // See if the path is a directory, and skip it if it isn't. File candidateFolder = new File(appDir, candidateFolderName); if (!candidateFolder.isDirectory()) { continue; } // If we've got to this stage, the file is the earliest // recording and should be deleted. Delete files in // recording first. success = Utils.deleteDirectory(candidateFolder); if (success) { nDeleted++; } } } } // Copy latest questionnaire File try { File latestQuestionnaireFile = new File(appDirPath, Constants.FILENAME_QUESTIONNAIRE); InputStream in = new FileInputStream(latestQuestionnaireFile); OutputStream out = new FileOutputStream(new File(filesDirPath, Constants.FILENAME_QUESTIONNAIRE)); // Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (FileNotFoundException e) { Log.e(Constants.CODE_APP_TAG, "FileNotFoundException copying Questionnaire file."); } catch (IOException e) { Log.e(Constants.CODE_APP_TAG, "IOException copying Questionnaire file."); } // Create txt files. orientationFile = new File(filesDirPath, Constants.FILENAME_ORIENTATION); accelerationFile = new File(filesDirPath, Constants.FILENAME_ACCELERATION_RAW); actigraphyFile = new File(filesDirPath, Constants.FILENAME_ACCELERATION_PROCESSED); audioProcessedFile = new File(filesDirPath, Constants.FILENAME_AUDIO_PROCESSED); bodyPositionFile = new File(filesDirPath, Constants.FILENAME_POSITION); ppgFile = new File(filesDirPath, Constants.FILENAME_PPG); spo2File = new File(filesDirPath, Constants.FILENAME_SPO2); audioRawFile = new File(filesDirPath, Constants.FILENAME_AUDIO_RAW); /** Recording starts here. */ // Log start time so recording can begin in 30 minutes. startTime = Calendar.getInstance(Locale.getDefault()); finishRecordingFlag = false; recordingStartDelayMs = Constants.CONST_MILLIS_IN_MINUTE * Integer.parseInt(sharedPreferences .getString(Constants.PREF_RECORDING_START_DELAY, Constants.DEFAULT_RECORDING_START_DELAY)); recordingDurationMs = Constants.CONST_MILLIS_IN_MINUTE * Integer.parseInt(sharedPreferences .getString(Constants.PREF_RECORDING_DURATION, Constants.DEFAULT_RECORDING_DURATION)); if (recordingStartDelayMs > 0) { startRecordingFlag = false; AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); dialogBuilder.setTitle(getString(R.string.delayAlertTitle)) .setMessage(getString(R.string.delayAlertMessage1) + " " + sharedPreferences.getString(Constants.PREF_RECORDING_START_DELAY, Constants.DEFAULT_RECORDING_START_DELAY) + " " + getString(R.string.delayAlertMessage2)) .setPositiveButton(getString(R.string.ok), null); delayAlertDialog = dialogBuilder.create(); delayAlertDialog.show(); } else { startRecordingFlag = true; // Notify user Intent notificationIntent = new Intent(SignalsRecorder.this, SignalsRecorder.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); if (sharedPreferences.getBoolean(Constants.PREF_NOTIFICATIONS, Constants.DEFAULT_NOTIFICATIONS)) { NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()) .setSmallIcon(R.drawable.notification_icon) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.deviceaccessmic)) .setContentTitle("SleepAp").setContentText(getString(R.string.startedRecordingNotification)) .setAutoCancel(false).setOngoing(true).setContentIntent(pendingIntent); notificationManager.notify(Constants.CODE_APP_NOTIFICATION_ID, builder.build()); recordingSign.setVisibility(View.VISIBLE); } } // Start audio recording. if (audioEnabled) { extAudioRecorder = new ExtAudioRecorder(this); extAudioRecorder.setOutputFile(audioRawFile); extAudioRecorder.setShouldWrite(startRecordingFlag); extAudioRecorder.setAudioProcessedFile(audioProcessedFile); extAudioRecorder.prepare(); extAudioRecorder.start(); } // Start PPG recording. if (ppgEnabled && bluetoothAdapter != null) { String macAddress = sharedPreferences.getString(Constants.PREF_MAC_ADDRESS, Constants.DEFAULT_MAC_ADDRESS); noninManager = new NoninManager(this, bluetoothAdapter, macAddress, new PpgHandler(SignalsRecorder.this)); noninManager.start(); } // Start actigraphy recording. if (actigraphyEnabled) { sensorManager.registerListener(this, accelerometer, 1000000 / (Constants.PARAM_SAMPLERATE_ACCELEROMETER * Constants.PARAM_UPSAMPLERATE_ACCELEROMETER)); sensorManager.registerListener(this, magnetometer, 1000000 / Constants.PARAM_SAMPLERATE_ACCELEROMETER); } wakeLock.acquire(); // Set up listener so that if Bluetooth connection is lost we set give // the user an option to reconnect. if (ppgEnabled) { IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(bluetoothDisconnectReceiver, filter); } // Start graphs update. graphUpdateTask = new UserInterfaceUpdater(); graphUpdateTask.execute(); }
From source file:org.mailster.MailsterSWT.java
private static void startApplication(String[] args) { MailsterSWT main = getInstance();// w w w.jav a 2 s .c o m main.smtpService = new MailsterSmtpService(); MailsterPrefStore store = ConfigurationManager.CONFIG_STORE; try { store.load(); } catch (IOException e) { LOG.debug("Unable to read preferences file. Loading defaults ..."); // Set default preferences store.setValue(ConfigurationManager.MAIL_QUEUE_REFRESH_INTERVAL_KEY, "300000"); //$NON-NLS-1$ store.setValue(ConfigurationManager.ASK_ON_REMOVE_MAIL_KEY, true); store.setValue(ConfigurationManager.APPLY_MAIN_WINDOW_PARAMS_KEY, true); store.setValue(ConfigurationManager.PREFERRED_BROWSER_KEY, Messages.getString("MailsterSWT.default.browser")); //$NON-NLS-1$ store.setValue(ConfigurationManager.PREFERRED_CONTENT_TYPE_KEY, "text/html"); //$NON-NLS-1$ store.setValue(ConfigurationManager.NOTIFY_ON_NEW_MESSAGES_RECEIVED_KEY, true); store.setValue(ConfigurationManager.AUTO_HIDE_NOTIFICATIONS_KEY, true); store.setValue(ConfigurationManager.LANGUAGE_KEY, "en"); store.setValue(ConfigurationManager.EXECUTE_ENCLOSURE_ON_CLICK_KEY, true); store.setValue(ConfigurationManager.DEFAULT_ENCLOSURES_DIRECTORY_KEY, System.getProperty("user.home")); //$NON-NLS-1$ store.setValue(ConfigurationManager.START_POP3_ON_SMTP_START_KEY, true); store.setValue(ConfigurationManager.POP3_SERVER_KEY, ""); store.setValue(ConfigurationManager.POP3_PORT_KEY, MailsterPop3Service.POP3_PORT); store.setValue(ConfigurationManager.POP3_SPECIAL_ACCOUNT_KEY, MailBoxManager.POP3_SPECIAL_ACCOUNT_LOGIN); store.setValue(ConfigurationManager.POP3_ALLOW_APOP_AUTH_METHOD_KEY, true); store.setValue(ConfigurationManager.POP3_REQUIRE_SECURE_AUTH_METHOD_KEY, true); store.setValue(ConfigurationManager.POP3_PASSWORD_KEY, UserManager.DEFAULT_PASSWORD); store.setValue(ConfigurationManager.POP3_CONNECTION_TIMEOUT_KEY, Pop3ProtocolHandler.DEFAULT_TIMEOUT_SECONDS); store.setValue(ConfigurationManager.AUTH_SSL_CLIENT_KEY, true); store.setValue(ConfigurationManager.PREFERRED_SSL_PROTOCOL_KEY, SSLProtocol.TLS.toString()); store.setValue(ConfigurationManager.CRYPTO_STRENGTH_KEY, 512); store.setValue(ConfigurationManager.SMTP_SERVER_KEY, ""); store.setValue(ConfigurationManager.SMTP_PORT_KEY, MailsterSMTPServer.DEFAULT_SMTP_PORT); store.setValue(ConfigurationManager.SMTP_CONNECTION_TIMEOUT_KEY, MailsterSMTPServer.DEFAULT_TIMEOUT / 1000); } String localeInfo = store.getString(ConfigurationManager.LANGUAGE_KEY); if (localeInfo != null && !"".equals(localeInfo)) { if (localeInfo.indexOf('_') != -1) Messages.setLocale(new Locale(localeInfo.substring(0, 2), localeInfo.substring(3))); else Messages.setLocale(new Locale(localeInfo)); } main.smtpService .setQueueRefreshTimeout(store.getLong(ConfigurationManager.SMTP_CONNECTION_TIMEOUT_KEY) / 1000); main.smtpService.setAutoStart(store.getBoolean(ConfigurationManager.START_SMTP_ON_STARTUP_KEY)); if (args.length > 3) usage(); { for (int i = 0, max = args.length; i < max; i++) { if ("-autostart".equals(args[i])) main.smtpService.setAutoStart(true); else if (args[i].startsWith("-lang=")) { Messages.setLocale(new Locale(args[i].substring(6))); } else { try { main.smtpService.setQueueRefreshTimeout(Long.parseLong(args[i])); } catch (NumberFormatException e) { usage(); } } } } final MailsterSWT _main = main; Thread.UncaughtExceptionHandler exHandler = new Thread.UncaughtExceptionHandler() { public void uncaughtException(final Thread t, final Throwable ex) { ex.printStackTrace(); Display.getDefault().asyncExec(new Runnable() { public void run() { _main.log(Messages.getString("MailsterSWT.exception.log1") + t.getName() //$NON-NLS-1$ + Messages.getString("MailsterSWT.exception.log2") //$NON-NLS-1$ + ex.getMessage()); } }); _main.smtpService.shutdownServer(false); } }; Thread.setDefaultUncaughtExceptionHandler(exHandler); Thread.currentThread().setUncaughtExceptionHandler(exHandler); LOG.debug("Creating shell ..."); main.createSShell(); main.applyPreferences(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { _main.smtpService.shutdownServer(true); if (_main.trayItem != null) _main.trayItem.dispose(); } catch (Exception ex) { ex.printStackTrace(); } }; }); }
From source file:view.EditorView.java
@FXML // This method is called by the FXMLLoader when initialization is complete void initialize() { assert insertRoom != null : "fx:id=\"insertRoom\" was not injected: check your FXML file 'EditorMain.fxml'."; assert drawing != null : "fx:id=\"drawing\" was not injected: check your FXML file 'EditorMain.fxml'."; assert insertPath != null : "fx:id=\"insertPath\" was not injected: check your FXML file 'EditorMain.fxml'."; currentEditorInstance = this; // modify the default exception handler to show the ReportingDialog on every uncaught exception final Thread.UncaughtExceptionHandler currentUncaughtExceptionHandler = Thread .getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler((thread, exception) -> { if (currentUncaughtExceptionHandler != null) { // execute current handler as we only want to append it currentUncaughtExceptionHandler.uncaughtException(thread, exception); }/*from www . j a va2 s . c o m*/ Platform.runLater(() -> { new ExceptionAlert(exception).showAndWait(); new ReportingDialog(stage.getScene()).show(AppConfig.gitHubUserName, AppConfig.gitHubRepoName, exception); }); }); currentGame.addListener((observable, oldValue, newValue) -> { if (newValue != null) { newValue.modifiedProperty().addListener((observable1, oldValue1, newValue1) -> { this.menuItemSave.setDisable(!newValue1); setWindowTitle(newValue); }); } setWindowTitle(newValue); }); initGame(); scrollPane.hvalueProperty().addListener((observable, oldValue, newValue) -> unselectingDisabled = true); scrollPane.vvalueProperty().addListener((observable, oldValue, newValue) -> unselectingDisabled = true); // add button icons insertRoom.setGraphic(new ImageView(new Image(EditorView.class.getResourceAsStream("add-room.png")))); moveButton.setGraphic(new ImageView(new Image(EditorView.class.getResourceAsStream("move-arrows.png")))); insertPath.setGraphic( new ImageView(new Image(EditorView.class.getResourceAsStream("connecting-points.png")))); autoLayoutButton .setGraphic(new ImageView(new Image(EditorView.class.getResourceAsStream("autoLayout.png")))); refreshViewButton .setGraphic(new ImageView(new Image(EditorView.class.getResourceAsStream("refreshView.png")))); // add tooltips insertRoom.setTooltip(new Tooltip("Insert a new room")); moveButton.setTooltip(new Tooltip("Move rooms")); insertPath.setTooltip(new Tooltip("Connect rooms to create walk paths")); autoLayoutButton.setTooltip(new Tooltip("Automatically rearrange the rooms in the view below")); refreshViewButton.setTooltip(new Tooltip("Refresh the current view")); // forward events to all selected items // drawing.setOnMouseClicked(forwardEventsToSelectableNodesHandler); // drawing.setOnMousePressed(forwardEventsToSelectableNodesHandler); // drawing.setOnMouseReleased(forwardEventsToSelectableNodesHandler); // drawing.setOnDragDetected(forwardEventsToSelectableNodesHandler); // drawing.setOnMouseDragged(forwardEventsToSelectableNodesHandler); scrollPane.setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.DELETE)) { for (Node child : new ArrayList<>(drawing.getChildren())) { if (child instanceof Disposable) { if (((Disposable) child).isSelected() && event.getTarget() != child) { FOKLogger.fine(EditorView.class.getName(), "Sending disposal command to child, Child is: " + child.toString() + "\ntarget is: " + event.getTarget().toString()); try { ((Disposable) child).dispose(); } catch (IllegalStateException e) { FOKLogger.log(EditorView.class.getName(), Level.INFO, "User tried to remove the current room (not allowed)", e); new Alert(Alert.AlertType.ERROR, "Could not perform delete operation: \n\n" + ExceptionUtils.getRootCauseMessage(e)).show(); } } } } } else if (event.getCode().equals(KeyCode.A) && event.isControlDown()) { // select everything for (Node child : new ArrayList<>(drawing.getChildren())) { if (child instanceof Selectable) { ((Selectable) child).setSelected(true); } } } }); }
From source file:org.apache.tez.dag.app.DAGAppMaster.java
public static void main(String[] args) { try {//from w w w .j ava 2s .com Thread.setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler()); // TODO: Deprecated keys? //DeprecatedKeys.init(); String containerIdStr = System.getenv(Environment.CONTAINER_ID.name()); String nodeHostString = System.getenv(Environment.NM_HOST.name()); String nodePortString = System.getenv(Environment.NM_PORT.name()); String nodeHttpPortString = System.getenv(Environment.NM_HTTP_PORT.name()); String appSubmitTimeStr = System.getenv(ApplicationConstants.APP_SUBMIT_TIME_ENV); validateInputParam(appSubmitTimeStr, ApplicationConstants.APP_SUBMIT_TIME_ENV); ContainerId containerId = ConverterUtils.toContainerId(containerIdStr); ApplicationAttemptId applicationAttemptId = containerId.getApplicationAttemptId(); long appSubmitTime = Long.parseLong(appSubmitTimeStr); TezConfiguration conf = new TezConfiguration(new YarnConfiguration()); DAGPlan dagPlan = null; // Read the protobuf DAG DAGPlan.Builder dagPlanBuilder = DAGPlan.newBuilder(); FileInputStream dagPBBinaryStream = null; try { dagPBBinaryStream = new FileInputStream(TezConfiguration.TEZ_AM_PLAN_PB_BINARY); dagPlanBuilder.mergeFrom(dagPBBinaryStream); } finally { if (dagPBBinaryStream != null) { dagPBBinaryStream.close(); } } dagPlan = dagPlanBuilder.build(); if (LOG.isDebugEnabled()) { LOG.debug("Running a DAG with " + dagPlan.getVertexCount() + " vertices "); for (VertexPlan v : dagPlan.getVertexList()) { LOG.debug("DAG has vertex " + v.getName()); } } String jobUserName = System.getenv(ApplicationConstants.Environment.USER.name()); // Do not automatically close FileSystem objects so that in case of // SIGTERM I have a chance to write out the job history. I'll be closing // the objects myself. conf.setBoolean("fs.automatic.close", false); Map<String, String> config = DagTypeConverters .createSettingsMapFromDAGPlan(dagPlan.getJobSettingList()); for (Entry<String, String> entry : config.entrySet()) { conf.set(entry.getKey(), entry.getValue()); } DAGAppMaster appMaster = new DAGAppMaster(applicationAttemptId, containerId, nodeHostString, Integer.parseInt(nodePortString), Integer.parseInt(nodeHttpPortString), appSubmitTime, dagPlan); ShutdownHookManager.get().addShutdownHook(new DAGAppMasterShutdownHook(appMaster), SHUTDOWN_HOOK_PRIORITY); initAndStartAppMaster(appMaster, conf, jobUserName); } catch (Throwable t) { LOG.fatal("Error starting DAGAppMaster", t); System.exit(1); } }
From source file:org.javaswift.cloudie.CloudiePanel.java
public void bind() { containersList.addListSelectionListener(new ListSelectionListener() { @Override//from ww w . ja v a 2 s. com public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) { return; } else { int idx = containersList.getSelectedIndex(); if (idx >= 0) { refreshFiles((Container) containers.get(idx)); } } } }); // Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable ex) { if (ex instanceof CommandException) { showError((CommandException) ex); } else { ex.printStackTrace(); } } }); // containersList.getInputMap().put(KeyStroke.getKeyStroke("F5"), "refresh"); containersList.getActionMap().put("refresh", containerRefreshAction); // storedObjectsList.getInputMap().put(KeyStroke.getKeyStroke("F5"), "refresh"); storedObjectsList.getActionMap().put("refresh", containerRefreshAction); // }