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:mobisocial.metrics.MusubiExceptionHandler.java

public static void installHandler(Context context) {
    UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
    if (!(currentHandler instanceof MusubiExceptionHandler)) {
        Thread.setDefaultUncaughtExceptionHandler(new MusubiExceptionHandler(context, currentHandler));
    }/* ww  w.j  a v  a 2 s.  c  om*/
}

From source file:com.vuze.android.remote.VuzeEasyTrackerOld.java

@Override
public void registerExceptionReporter(Context applicationContext) {
    ExceptionReporter myHandler = new ExceptionReporter(easyTracker, GAServiceManager.getInstance(),
            Thread.getDefaultUncaughtExceptionHandler(), applicationContext);
    myHandler.setExceptionParser(new ExceptionParser() {
        @Override/*from   w  w w. j av  a2 s  . co m*/
        public String getDescription(String threadName, Throwable t) {
            String s = "*" + t.getClass().getSimpleName() + " " + AndroidUtils.getCompressedStackTrace(t, 0, 9);
            return s;
        }
    });
    Thread.setDefaultUncaughtExceptionHandler(myHandler);
}

From source file:io.bitsquare.app.BitsquareApp.java

@Override
public void start(Stage stage) throws IOException {
    BitsquareApp.primaryStage = stage;//from ww w.jav a2 s  .  c om

    String logPath = Paths.get(env.getProperty(AppOptionKeys.APP_DATA_DIR_KEY), "bitsquare").toString();
    Log.setup(logPath);
    log.info("Log files under: " + logPath);
    Version.printVersion();
    Utilities.printSysInfo();
    Log.setLevel(Level.toLevel(env.getRequiredProperty(CommonOptionKeys.LOG_LEVEL_KEY)));

    UserThread.setExecutor(Platform::runLater);
    UserThread.setTimerClass(UITimer.class);

    shutDownHandler = this::stop;

    // setup UncaughtExceptionHandler
    Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
        // Might come from another thread 
        if (throwable.getCause() != null && throwable.getCause().getCause() != null
                && throwable.getCause().getCause() instanceof BlockStoreException) {
            log.error(throwable.getMessage());
        } else if (throwable instanceof ClassCastException
                && "sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData"
                        .equals(throwable.getMessage())) {
            log.warn(throwable.getMessage());
        } else {
            log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
            log.error("throwableMessage= " + throwable.getMessage());
            log.error("throwableClass= " + throwable.getClass());
            log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable));
            throwable.printStackTrace();
            UserThread.execute(() -> showErrorPopup(throwable, false));
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(handler);
    Thread.currentThread().setUncaughtExceptionHandler(handler);

    try {
        Utilities.checkCryptoPolicySetup();
    } catch (NoSuchAlgorithmException | LimitedKeyStrengthException e) {
        e.printStackTrace();
        UserThread.execute(() -> showErrorPopup(e, true));
    }

    Security.addProvider(new BouncyCastleProvider());

    try {
        // Guice
        bitsquareAppModule = new BitsquareAppModule(env, primaryStage);
        injector = Guice.createInjector(bitsquareAppModule);
        injector.getInstance(InjectorViewFactory.class).setInjector(injector);

        Version.setBtcNetworkId(injector.getInstance(BitsquareEnvironment.class).getBitcoinNetwork().ordinal());

        if (Utilities.isLinux())
            System.setProperty("prism.lcdtext", "false");

        Storage.setDatabaseCorruptionHandler((String fileName) -> {
            corruptedDatabaseFiles.add(fileName);
            if (mainView != null)
                mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles);
        });

        // load the main view and create the main scene
        CachingViewLoader viewLoader = injector.getInstance(CachingViewLoader.class);
        mainView = (MainView) viewLoader.load(MainView.class);
        mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles);

        /* Storage.setDatabaseCorruptionHandler((String fileName) -> {
        corruptedDatabaseFiles.add(fileName);
        if (mainView != null)
            mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles);
         });*/

        scene = new Scene(mainView.getRoot(), 1200, 700); //740

        Font.loadFont(getClass().getResource("/fonts/Verdana.ttf").toExternalForm(), 13);
        Font.loadFont(getClass().getResource("/fonts/VerdanaBold.ttf").toExternalForm(), 13);
        Font.loadFont(getClass().getResource("/fonts/VerdanaItalic.ttf").toExternalForm(), 13);
        Font.loadFont(getClass().getResource("/fonts/VerdanaBoldItalic.ttf").toExternalForm(), 13);
        scene.getStylesheets().setAll("/io/bitsquare/gui/bitsquare.css", "/io/bitsquare/gui/images.css",
                "/io/bitsquare/gui/CandleStickChart.css");

        // configure the system tray
        SystemTray.create(primaryStage, shutDownHandler);

        primaryStage.setOnCloseRequest(event -> {
            event.consume();
            stop();
        });
        scene.addEventHandler(KeyEvent.KEY_RELEASED, keyEvent -> {
            if (new KeyCodeCombination(KeyCode.W, KeyCombination.SHORTCUT_DOWN).match(keyEvent)
                    || new KeyCodeCombination(KeyCode.W, KeyCombination.CONTROL_DOWN).match(keyEvent)) {
                stop();
            } else if (new KeyCodeCombination(KeyCode.Q, KeyCombination.SHORTCUT_DOWN).match(keyEvent)
                    || new KeyCodeCombination(KeyCode.Q, KeyCombination.CONTROL_DOWN).match(keyEvent)) {
                stop();
            } else if (new KeyCodeCombination(KeyCode.E, KeyCombination.SHORTCUT_DOWN).match(keyEvent)
                    || new KeyCodeCombination(KeyCode.E, KeyCombination.CONTROL_DOWN).match(keyEvent)) {
                showEmptyWalletPopup();
            } else if (new KeyCodeCombination(KeyCode.M, KeyCombination.ALT_DOWN).match(keyEvent)) {
                showSendAlertMessagePopup();
            } else if (new KeyCodeCombination(KeyCode.F, KeyCombination.ALT_DOWN).match(keyEvent)) {
                showFilterPopup();
            } else if (new KeyCodeCombination(KeyCode.F, KeyCombination.ALT_DOWN).match(keyEvent)) {
                showFPSWindow();
            } else if (new KeyCodeCombination(KeyCode.J, KeyCombination.ALT_DOWN).match(keyEvent)) {
                WalletService walletService = injector.getInstance(WalletService.class);
                if (walletService.getWallet() != null)
                    new ShowWalletDataWindow(walletService).information("Wallet raw data").show();
                else
                    new Popup<>().warning("The wallet is not initialized yet").show();
            } else if (new KeyCodeCombination(KeyCode.G, KeyCombination.ALT_DOWN).match(keyEvent)) {
                TradeWalletService tradeWalletService = injector.getInstance(TradeWalletService.class);
                WalletService walletService = injector.getInstance(WalletService.class);
                if (walletService.getWallet() != null)
                    new SpendFromDepositTxWindow(tradeWalletService).information("Emergency wallet tool")
                            .show();
                else
                    new Popup<>().warning("The wallet is not initialized yet").show();
            } else if (DevFlags.DEV_MODE
                    && new KeyCodeCombination(KeyCode.D, KeyCombination.SHORTCUT_DOWN).match(keyEvent)) {
                showDebugWindow();
            }
        });

        // configure the primary stage
        primaryStage.setTitle(env.getRequiredProperty(APP_NAME_KEY));
        primaryStage.setScene(scene);
        primaryStage.setMinWidth(1000); // 1190
        primaryStage.setMinHeight(620);

        // on windows the title icon is also used as task bar icon in a larger size
        // on Linux no title icon is supported but also a large task bar icon is derived from that title icon
        String iconPath;
        if (Utilities.isOSX())
            iconPath = ImageUtil.isRetina() ? "/images/window_icon@2x.png" : "/images/window_icon.png";
        else if (Utilities.isWindows())
            iconPath = "/images/task_bar_icon_windows.png";
        else
            iconPath = "/images/task_bar_icon_linux.png";

        primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(iconPath)));

        // make the UI visible
        primaryStage.show();

        if (!Utilities.isCorrectOSArchitecture()) {
            String osArchitecture = Utilities.getOSArchitecture();
            // We don't force a shutdown as the osArchitecture might in strange cases return a wrong value.
            // Needs at least more testing on different machines...
            new Popup<>()
                    .warning("You probably have the wrong Bitsquare version for this computer.\n"
                            + "Your computer's architecture is: " + osArchitecture + ".\n"
                            + "The Bitsquare binary you installed is: " + Utilities.getJVMArchitecture() + ".\n"
                            + "Please shut down and re-install the correct version (" + osArchitecture + ").")
                    .show();
        }

        UserThread.runPeriodically(() -> Profiler.printSystemLoad(log), LOG_MEMORY_PERIOD_MIN,
                TimeUnit.MINUTES);

    } catch (Throwable throwable)

    {
        showErrorPopup(throwable, false);
    }

}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    CommonPlace.manehCodes = ManehCodeDA.getInstance(this).getAll();
    CommonPlace.inspectionCodes = InspectionCodeDA.getInstance(this).getAll();
    CommonPlace.CurrentRegisterFields = RegisterFieldDA.getInstance(this).getAll("fldPartitionCode=?", "",
            new String[] { CommonPlace.currentCityPartition.getFldPartitionCode() });
    LoadValidationCriterias();//from ww w  .  j  a  va  2s  .  co m

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
            Log.e("Alert", "Lets See if it Works !!!" + paramThrowable.toString());
        }
    });
    Utility.InitializeDefatultSettings(this);
    CommonPlace.slideActivity = this;
    getActionBar().setDisplayHomeAsUpEnabled(true);

    setContentView(R.layout.activity_screen_slide);
    mtextProgress = (TextView) findViewById(R.id.txtProgress);

    Utility.applyFont(findViewById(R.id.reading_page));
    LinearLayout taskbarLayout = (LinearLayout) findViewById(R.id.taskbarpanel);
    taskbarLayout.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Button btnCamera = (Button) findViewById(R.id.btnCamera);
            if (btnCamera.getTextSize() > 0) {
                btnCamera.setTextSize(0);
            } else {
                btnCamera.setTextSize(20);
            }

        }
    });
    progressbar = (ProgressBar) findViewById(R.id.reading_progress);
    progressbar.setProgress(0);

    Button btnSubmit = (Button) findViewById(R.id.btnSubmit);
    btnSubmit.setOnClickListener(new View.OnClickListener() {

        Dialog mydialog;

        public void onClick(View v) {
            ShowSubmitDialog();
        }
    });

    Button btnCamera = (Button) findViewById(R.id.btnCamera);
    btnCamera.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            dispatchTakePictureIntentOrShowPicture();
        }

    });

    Button btnInspection = (Button) findViewById(R.id.btnInspection);
    btnInspection.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            ShowInspectionDialog();
        }

    });

    Button btnonlineControl = (Button) findViewById(R.id.btnOnline_control);
    btnonlineControl.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            ShowOnlineControl();
        }

    });

    Button btnOnlineCalculation = (Button) findViewById(R.id.btnCalculation);
    btnOnlineCalculation.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            ShowOnlineCalculation();
        }

    });

    // Instantiate a ViewPager and a PagerAdapter.
    mPager = (ViewPager) findViewById(R.id.pager);
    mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
    mPager.setAdapter(mPagerAdapter);
    mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {

            // When changing pages, reset the action bar actions since they are dependent
            // on which page is currently active. An alternative approach is to have each
            // fragment expose actions itself (rather than the activity exposing actions),
            // but for simplicity, the activity provides the actions in this sample.
            invalidateOptionsMenu();
        }
    });
    try {
        // int last = mSavedBundle.getInt("Reading-" + CommonPlace.currentReadingList.getId());
        // mPager.setCurrentItem(last);
    } catch (Exception ex) {
        ex.toString();
    }

    final Handler handler1 = new Handler();
    try {
        final int pos = Integer.parseInt(CommonPlace.currentReadingList.Position);
        handler1.postDelayed(new Runnable() {
            @Override
            public void run() {
                mPager.setCurrentItem(pos);
            }
        }, 500);
    } catch (Exception ex) {

    }
}

From source file:cn.sharesdk.analysis.EventManager.java

/** set error listener */
public static void onError(Context context) {
    init(context);//from   ww w.j a  v a2  s.  c o  m
    CrashHandler handler = CrashHandler.getInstance();
    handler.init(context);
    Thread.setDefaultUncaughtExceptionHandler(handler);
}

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

@Override
protected void finalize() throws Throwable {
    super.finalize();
    if (defaultUEH != null) {
        Thread.setDefaultUncaughtExceptionHandler(defaultUEH);
    }//from  ww  w .ja  v  a2s. c om
}

From source file:de.tbuchloh.kiskis.KisKis.java

private static void initThreadMonitors() {
    final UncaughtExceptionHandler eh = new UncaughtExceptionHandler() {

        @Override/*from   w ww. jav  a2 s .co m*/
        public void uncaughtException(Thread t, Throwable e) {
            LOG.debug("Uncaught Exception occurred! e=" + e.getMessage());
            try {
                MessageBox.showException(e);
            } catch (final Throwable throwable) {
                LOG.error(
                        "Uncaught Exception could not be displayed due to another exception! anotherThrowable="
                                + throwable + ", rootCause=" + e,
                        throwable);
            }
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(eh);

    final ThreadDeadlockDetector detector = new ThreadDeadlockDetector();
    detector.addListener(new DefaultDeadlockListener());
    detector.addListener(new DefaultDeadlockListener() {

        private volatile boolean fired = false;

        @Override
        public void deadlockDetected(Thread[] deadlockedThreads) {
            if (fired) {
                return;
            }
            fired = true;

            final File file = new File(System.getProperty("java.io.tmpdir"), "kiskis-deadlock.txt");
            final String msg = format(
                    "Threads were blocked!\nYou need to restart the application.\nPlease mail file \"%2$s\" as bug.\nthreads=%1$s",
                    Arrays.toString(deadlockedThreads), file.getAbsolutePath());
            JOptionPane.showMessageDialog(null, msg, "Deadlock detected!", JOptionPane.ERROR_MESSAGE);
        }
    });
}

From source file:org.datacleaner.bootstrap.Bootstrap.java

private void runInternal() throws FileSystemException {
    logger.info("Welcome to DataCleaner {}", Version.getVersion());

    // determine whether to run in command line interface mode
    final boolean cliMode = _options.isCommandLineMode();
    final CliArguments arguments = _options.getCommandLineArguments();

    logger.info("CLI mode={}, use -usage to view usage options", cliMode);

    if (cliMode) {

        try {/*ww w  .ja va 2 s . co  m*/
            if (!GraphicsEnvironment.isHeadless()) {
                // hide splash screen
                final SplashScreen splashScreen = SplashScreen.getSplashScreen();
                if (splashScreen != null) {
                    splashScreen.close();
                }
            }
        } catch (Exception e) {
            // ignore this condition - may happen rarely on e.g. X windows
            // systems when the user is not authorized to access the
            // graphics environment.
            logger.trace("Swallowing exception caused by trying to hide splash screen", e);
        }

        if (arguments.isUsageMode()) {
            final PrintWriter out = new PrintWriter(System.out);
            try {
                CliArguments.printUsage(out);
            } finally {
                FileHelper.safeClose(out);
            }

            exitCommandLine(null, 1);
            return;
        }

        if (arguments.isVersionMode()) {
            final PrintWriter out = new PrintWriter(System.out);
            try {
                CliArguments.printVersion(out);
            } finally {
                FileHelper.safeClose(out);
            }

            exitCommandLine(null, 1);
            return;
        }
    }

    if (!cliMode) {
        // set up error handling that displays an error dialog
        final DCUncaughtExceptionHandler exceptionHandler = new DCUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);

        // init the look and feel
        LookAndFeelManager.get().init();
    }

    // initially use a temporary non-persistent user preferences object.
    // This is just to have basic settings available for eg. resolving
    // files.
    final UserPreferences initialUserPreferences = new UserPreferencesImpl(null);

    final String configurationFilePath = arguments.getConfigurationFile();
    final FileObject configurationFile = resolveFile(configurationFilePath, "conf.xml", initialUserPreferences);

    Injector injector = Guice.createInjector(new DCModuleImpl(DataCleanerHome.get(), configurationFile));

    // configuration loading can be multithreaded, so begin early
    final DataCleanerConfiguration configuration = injector.getInstance(DataCleanerConfiguration.class);

    // log usage
    final UsageLogger usageLogger = injector.getInstance(UsageLogger.class);
    usageLogger.logApplicationStartup();

    if (cliMode) {
        // run in CLI mode

        int exitCode = 0;
        try (final CliRunner runner = new CliRunner(arguments)) {
            runner.run(configuration);
        } catch (Throwable e) {
            logger.error("Error occurred while running DataCleaner command line mode", e);
            exitCode = 1;
        } finally {
            exitCommandLine(configuration, exitCode);
        }
        return;
    } else {
        // run in GUI mode
        final AnalysisJobBuilderWindow analysisJobBuilderWindow;

        // initialize Mac OS specific settings
        final MacOSManager macOsManager = injector.getInstance(MacOSManager.class);
        macOsManager.init();

        // check for job file
        final String jobFilePath = _options.getCommandLineArguments().getJobFile();
        if (jobFilePath != null) {
            final FileObject jobFile = resolveFile(jobFilePath, null, initialUserPreferences);
            injector = OpenAnalysisJobActionListener.open(jobFile, configuration, injector);
        }

        final UserPreferences userPreferences = injector.getInstance(UserPreferences.class);

        analysisJobBuilderWindow = injector.getInstance(AnalysisJobBuilderWindow.class);

        final Datastore singleDatastore;
        if (_options.isSingleDatastoreMode()) {
            DatastoreCatalog datastoreCatalog = configuration.getDatastoreCatalog();
            singleDatastore = _options.getSingleDatastore(datastoreCatalog);
            if (singleDatastore == null) {
                logger.info("Single datastore mode was enabled, but datastore was null!");
            } else {
                logger.info("Initializing single datastore mode with {}", singleDatastore);
                analysisJobBuilderWindow.setDatastoreSelectionEnabled(false);
                analysisJobBuilderWindow.setDatastore(singleDatastore, true);
            }
        } else {
            singleDatastore = null;
        }

        // show the window
        analysisJobBuilderWindow.open();

        if (singleDatastore != null) {
            // this part has to be done after displaying the window (a lot
            // of initialization goes on there)
            final AnalysisJobBuilder analysisJobBuilder = analysisJobBuilderWindow.getAnalysisJobBuilder();
            try (final DatastoreConnection con = singleDatastore.openConnection()) {
                final InjectorBuilder injectorBuilder = injector.getInstance(InjectorBuilder.class);
                _options.initializeSingleDatastoreJob(analysisJobBuilder, con.getDataContext(),
                        injectorBuilder);
            }
        }

        final Image welcomeImage = _options.getWelcomeImage();
        if (welcomeImage != null) {
            // Ticket #834: make sure to show welcome dialog in swing's
            // dispatch thread.
            WidgetUtils.invokeSwingAction(new Runnable() {
                @Override
                public void run() {
                    final WelcomeDialog welcomeDialog = new WelcomeDialog(analysisJobBuilderWindow,
                            welcomeImage);
                    welcomeDialog.setVisible(true);
                }
            });
        }

        final WindowContext windowContext = injector.getInstance(WindowContext.class);

        // set up HTTP service for ExtensionSwap installation
        loadExtensionSwapService(userPreferences, windowContext, configuration, usageLogger);

        final ExitActionListener exitActionListener = _options.getExitActionListener();
        if (exitActionListener != null) {
            windowContext.addExitActionListener(exitActionListener);
        }
    }
}

From source file:the.joevlc.AudioService.java

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

    // Get libVLC instance
    try {/* ww w.j  a  v  a  2 s . co m*/
        mLibVLC = LibVLC.getInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    Thread.setDefaultUncaughtExceptionHandler(new VlcCrashHandler());

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    mMediaList = new ArrayList<Media>();
    mPrevious = new Stack<Media>();
    mEventManager = EventManager.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(getPackageName(),
            RemoteControlClientReceiver.class.getName());

    // Make sure the audio player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    IntentFilter filter = new IntentFilter();
    filter.setPriority(Integer.MAX_VALUE);
    filter.addAction(ACTION_REMOTE_BACKWARD);
    filter.addAction(ACTION_REMOTE_PLAYPAUSE);
    filter.addAction(ACTION_REMOTE_PLAY);
    filter.addAction(ACTION_REMOTE_PAUSE);
    filter.addAction(ACTION_REMOTE_STOP);
    filter.addAction(ACTION_REMOTE_FORWARD);
    filter.addAction(ACTION_REMOTE_LAST_PLAYLIST);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(VLCApplication.SLEEP_INTENT);
    registerReceiver(serviceReceiver, filter);

    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean stealRemoteControl = pref.getBoolean("steal_remote_control", false);

    if (!Util.isFroyoOrLater() || stealRemoteControl) {
        /* Backward compatibility for API 7 */
        filter = new IntentFilter();
        if (stealRemoteControl)
            filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(Intent.ACTION_MEDIA_BUTTON);
        mRemoteControlClientReceiver = new RemoteControlClientReceiver();
        registerReceiver(mRemoteControlClientReceiver, filter);
    }

    AudioUtil.prepareCacheFolder(this);
}

From source file:dk.dma.epd.shore.EPDShore.java

/**
 * Constructor/* w  w  w.ja  va 2s.  co  m*/
 * 
 * @param path
 *            the home path to use
 */
private EPDShore(String path) throws IOException {
    super();

    if (!StringUtils.isEmpty(path)) {
        homePath = Paths.get(path);
    } else {
        homePath = determineHomePath(Paths.get(System.getProperty("user.home"), ".epd-shore"));
    }

    new Bootstrap().run(this, new String[] { "epd-shore.properties", "settings.properties", "transponder.xml" },
            new String[] { "workspaces", "routes", "shape/GSHHS_shp", "identities" });

    // Set up log4j logging
    LOG = LoggerFactory.getLogger(EPDShore.class);

    // Set default exception handler
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());

    LOG.info("Starting eNavigation Prototype Display Shore - version " + VersionInfo.getVersionAndBuild());
    LOG.info("Copyright (C) 2012 Danish Maritime Authority");
    LOG.info("This program comes with ABSOLUTELY NO WARRANTY.");
    LOG.info("This is free software, and you are welcome to redistribute it under certain conditions.");
    LOG.info("For details see LICENSE file.");

    // Create the bean context (map handler)
    // mapHandler = new MapHandler();
    beanHandler = new BeanContextServicesSupport();

    // Load settings or get defaults and add to bean context
    settings = new EPDSettings();
    LOG.info("Using settings file: " + getSettings().getSettingsFile());
    settings.loadFromFile();
    beanHandler.add(settings);

    // Determine if instance already running and if that is allowed

    OneInstanceGuard guard = new OneInstanceGuard(getHomePath().resolve("epd.lock").toString());
    if (guard.isAlreadyRunning()) {
        handleEpdAlreadyRunning();
    }

    // Enable GPS timer by adding it to bean context
    PntTime.init(settings.getSensorSettings().isUseTimeFromPnt());
    beanHandler.add(PntTime.getInstance());

    // aisHandler = new AisHandlerCommon();
    aisHandler = new AisHandler(settings.getAisSettings());
    aisHandler.loadView();
    EPD.startThread(aisHandler, "AisHandler");
    beanHandler.add(aisHandler);

    // Add StaticImages handler
    staticImages = new StaticImages();
    beanHandler.add(staticImages);

    // Load routeManager
    routeManager = RouteManager.loadRouteManager();
    beanHandler.add(routeManager);

    falManager = FALManager.loadFALManager();
    beanHandler.add(falManager);

    // To be changed to load similar to routeManager
    // voyageManager = new VoyageManager();
    voyageManager = VoyageManager.loadVoyageManager();
    beanHandler.add(voyageManager);

    sruManager = SRUManager.loadSRUManager();
    beanHandler.add(sruManager);

    // Create shore services
    shoreServicesCommon = new ShoreServices(getSettings().getEnavSettings());
    beanHandler.add(shoreServicesCommon);

    // Create mona lisa route exchange
    monaLisaRouteExchange = new MonaLisaRouteOptimization();
    beanHandler.add(monaLisaRouteExchange);

    // Create Maritime Cloud service
    maritimeCloudService = new MaritimeCloudService();
    beanHandler.add(maritimeCloudService);
    maritimeCloudService.start();

    // Create strategic route Handler;
    strategicRouteHandler = new StrategicRouteHandler();
    beanHandler.add(strategicRouteHandler);

    // Create intended route handler
    intendedRouteHandler = new IntendedRouteHandler();
    beanHandler.add(intendedRouteHandler);

    // Create the route suggestion handler
    // routeSuggestionHandler = new RouteSuggestionHandler();
    routeSuggestionHandler = RouteSuggestionHandler.loadRouteSuggestionHandler();
    beanHandler.add(routeSuggestionHandler);

    // Create a new MSI-NM handler
    msiNmHandler = new MsiNmServiceHandlerCommon();
    beanHandler.add(msiNmHandler);

    // Create a chat service handler
    chatServiceHandler = new ChatServiceHandlerCommon();
    beanHandler.add(chatServiceHandler);

    // Create identity handler
    identityHandler = new IdentityHandler();
    beanHandler.add(identityHandler);

    // Start sensors
    startSensors();

    pluginLoader = new PluginLoader(getProperties(), getHomePath(), getPropertyFileName());

    try {
        pluginLoader.createPluginComponents(new Consumer<Object>() {
            public void accept(Object comp) {
                beanHandler.add(comp);
            }
        });
    } catch (Exception e) {
        LOG.error("Failed to load plugin container " + e.getMessage());
    }

    final CountDownLatch guiCreated = new CountDownLatch(1);

    // Create and show GUI
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            createAndShowGUI();
            guiCreated.countDown();
        }
    });

    // Wait for gui to be created
    try {
        guiCreated.await();

    } catch (InterruptedException e) {
        LOG.error("Interrupted while waiting for GUI to be created", e);
    }

    // Create vocthandler
    voctHandler = new VoctHandler();
    beanHandler.add(voctHandler);

    // Create voct manager
    voctManager = new VOCTManager();
    beanHandler.add(voctManager);
    voctManager.loadVOCTManager();

    // Create FAL Handler
    falHandler = new FALHandler();
    beanHandler.add(falHandler);

    // Create embedded transponder frame
    transponderFrame = new TransponderFrame(getHomePath().resolve("transponder.xml").toString(), true,
            mainFrame);
    mainFrame.getTopMenu().setTransponderFrame(transponderFrame);
    beanHandler.add(transponderFrame);

    if (settings.getSensorSettings().isStartTransponder()) {
        transponderFrame.startTransponder();
    }
}