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:ch.fork.AdHocRailway.ui.AdHocRailway.java

public AdHocRailway(org.apache.commons.cli.CommandLine parsedCommandLine) {
    super(TITLE);
    try {/*from   w ww.  ja  v a2 s. c  om*/

        appContext = new ApplicationContext();
        appContext.getMainBus().register(appContext);
        appContext.getMainBus().register(this);
        appContext.setMainApp(this);
        appContext.setMainFrame(this);
        setUpLogging();

        LOGGER.info("****************************************");
        LOGGER.info("AdHoc-Railway starting up!!!");
        LOGGER.info("****************************************");

        PlasticLookAndFeel.setTabStyle(PlasticLookAndFeel.TAB_STYLE_DEFAULT_VALUE);
        PlasticLookAndFeel.setHighContrastFocusColorsEnabled(false);

        UIManager.setLookAndFeel(new PlasticXPLookAndFeel());

        splash = new SplashWindow(createImageIconFromCustom("splash.png"), this, 500, 12);
        setIconImage(createImageIconFromCustom("2-Hot-Train-icon 128.png").getImage());

        initProceeded("Loading Persistence Layer (Preferences)");

        preferences = Preferences.getInstance();
        preferences.loadPreferences(parsedCommandLine.hasOption("c"));
        appContext.setPreferences(preferences);

        railwayDeviceManager = new RailwayDeviceManager(appContext);
        appContext.setRailwayDeviceManager(railwayDeviceManager);
        railwayDeviceManager.loadControlLayer();

        persistenceManager = new PersistenceManager(appContext);
        persistenceManager.loadPersistenceLayer();

        initProceeded("Creating GUI ...");

        initGUI();
        disableEnableMenuItems();
        LOGGER.info("Finished Creating GUI");
        splash.setVisible(false);

        persistenceManager.loadLastFileOrLoadDataFromAdHocServerIfRequested();

        updateGUI();
        railwayDeviceManager.autoConnectToRailwayDeviceIfRequested();

        setSize(1600, 1000);

        initProceeded("AdHoc-Railway started");
        updateCommandHistory("AdHoc-Railway started");
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(final Thread t, final Throwable e) {
                handleException(e);
            }
        });
        setLocationByPlatform(true);
        setVisible(true);
    } catch (final Exception e) {
        handleException(e);
    }
}

From source file:dk.dma.epd.ship.EPDShip.java

/**
 * Constructor//  www  .j  a  va2 s . c  om
 * 
 * @param path
 *            the home path to use
 */
private EPDShip(String path) throws IOException {
    super();

    if (!StringUtils.isEmpty(path)) {
        homePath = Paths.get(path);

        try {
            optionalTitle = " - " + path.split("epd-ship")[1];
        } catch (Exception e) {

        }
    } else {
        homePath = determineHomePath(Paths.get(System.getProperty("user.home"), ".epd-ship"));
    }

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

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

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

    // Determine version
    LOG.info("Starting eNavigation Prototype Display Ship - version " + VersionInfo.getVersionAndBuild());
    LOG.info("Copyright (C) 2011 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();

    // Load settings or get defaults and add to bean context
    settings = new EPDSettings();
    LOG.info("Using settings file: " + getSettings().getSettingsFile());
    settings.loadFromFile();
    mapHandler.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();
    }

    // start riskHandler
    startRiskHandler();

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

    // Start position handler and add to bean context
    pntHandler = new PntHandler();
    mapHandler.add(pntHandler);

    // Start the multi-source PNT handler and add to bean context
    msPntHandler = new MultiSourcePntHandler();
    msPntHandler.addPntListener(pntHandler);
    mapHandler.add(msPntHandler);

    // Start AIS target monitoring
    aisHandler = new AisHandler(settings.getSensorSettings(), settings.getAisSettings());
    aisHandler.loadView();
    EPD.startThread(aisHandler, "AisHandler");
    mapHandler.add(aisHandler);

    // Start own-ship handler
    ownShipHandler = new OwnShipHandler(settings.getAisSettings());
    ownShipHandler.loadView();
    ownShipHandler.addListener(this);
    mapHandler.add(ownShipHandler);

    // Start dynamic predictor handler
    dynamicPredictorHandler = new DynamicPredictorHandler();
    mapHandler.add(dynamicPredictorHandler);

    // Start dynamic predictor sensor sentence parser
    dynamicPredictorParser = new DynamicPredictorSentenceParser();
    mapHandler.add(dynamicPredictorParser);

    // Maybe start dynamic prediction generator
    if (settings.getSensorSettings().isStartPredictionGenerator()) {
        dynamicPredictor = new DynamicPredictor();
        mapHandler.add(dynamicPredictor);
    }

    // Load routeManager and register as GPS data listener
    routeManager = RouteManager.loadRouteManager();
    mapHandler.add(routeManager);

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

    voctManager = VOCTManager.loadVOCTManager();
    mapHandler.add(voctManager);

    // Create shore services
    shoreServices = new ShoreServices(getSettings().getEnavSettings());
    mapHandler.add(shoreServices);

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

    // Create NoGo handler
    nogoHandler = new NogoHandler();
    mapHandler.add(nogoHandler);

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

    strategicRouteHandler = new StrategicRouteHandler();
    mapHandler.add(strategicRouteHandler);

    // Create intended route handler
    intendedRouteHandler = new IntendedRouteHandler();
    intendedRouteHandler.updateSettings(settings.getEnavSettings());
    mapHandler.add(intendedRouteHandler);

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

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

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

    // Create voyage event dispatcher
    voyageEventDispatcher = new VoyageEventDispatcher();

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

    // Create VOCT handler
    voctHandler = new VoctHandler();
    mapHandler.add(voctHandler);

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

    // Start sensors
    startSensors();

    // Create plugin components

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

    // pluginLoader.createPluginComponents(comp -> mapHandler.add(comp));

    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 embedded transponder frame
    transponderFrame = new TransponderFrame(getHomePath().resolve("transponder.xml").toString(), true,
            mainFrame);
    mapHandler.add(transponderFrame);

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

}

From source file:ch.cyberduck.cli.Terminal.java

protected Exit execute() {
    final Console console = new Console();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/*from w  w w  .j  a  v  a  2 s  . co m*/
        public void uncaughtException(final Thread t, final Throwable e) {
            console.printf("Uncaught failure with error message %s. Quitting application", e.getMessage());
            System.exit(1);
        }
    });
    if (input.hasOption(TerminalAction.help.name())) {
        TerminalHelpPrinter.print(options);
        return Exit.success;
    }
    if (input.hasOption(TerminalAction.version.name())) {
        TerminalVersionPrinter.print(preferences);
        return Exit.success;
    }
    if (!new TerminalOptionsInputValidator().validate(input)) {
        console.printf("Try '%s' for more options.%n", "duck --help");
        return Exit.failure;
    }
    this.configure(input);
    SessionPool source = SessionPool.DISCONNECTED;
    SessionPool destination = SessionPool.DISCONNECTED;
    try {
        final TerminalAction action = TerminalActionFinder.get(input);
        if (null == action) {
            return Exit.failure;
        }
        final String uri = input.getOptionValue(action.name());
        final Host host = new CommandLineUriParser(input).parse(uri);
        final LoginConnectionService connect = new LoginConnectionService(
                new TerminalLoginService(input, new TerminalLoginCallback(reader)),
                new TerminalHostKeyVerifier(reader), progress);
        source = SessionPoolFactory.create(connect, transcript, cache, host,
                new CertificateStoreX509TrustManager(new DefaultTrustManagerHostnameCallback(host),
                        new TerminalCertificateStore(reader)),
                new PreferencesX509KeyManager(host, new TerminalCertificateStore(reader)),
                VaultRegistryFactory.create(new TerminalPasswordCallback()));
        final Path remote;
        if (new CommandLinePathParser(input).parse(uri).getAbsolute().startsWith(TildePathExpander.PREFIX)) {
            final Home home = source.getFeature(Home.class);
            remote = new TildePathExpander(home.find()).expand(new CommandLinePathParser(input).parse(uri));
        } else {
            remote = new CommandLinePathParser(input).parse(uri);
        }
        switch (action) {
        case edit:
            return this.edit(source, remote);
        case list:
        case longlist:
            return this.list(source, remote, input.hasOption(TerminalOptionsBuilder.Params.longlist.name()));
        case mount:
            return this.mount(source);
        case delete:
            return this.delete(source, remote);
        }
        switch (action) {
        case download:
        case upload:
        case synchronize:
            return this.transfer(
                    new TerminalTransferFactory().create(input, host, remote,
                            new ArrayList<TransferItem>(
                                    new SingleTransferItemFinder().find(input, action, remote))),
                    source, SessionPool.DISCONNECTED);
        case copy:
            final Host target = new CommandLineUriParser(input).parse(input.getOptionValues(action.name())[1]);
            destination = SessionPoolFactory.create(connect, transcript, cache, target,
                    new CertificateStoreX509TrustManager(new DefaultTrustManagerHostnameCallback(target),
                            new TerminalCertificateStore(reader)),
                    new PreferencesX509KeyManager(target, new TerminalCertificateStore(reader)),
                    VaultRegistryFactory.create(new TerminalPasswordCallback()));
            return this.transfer(
                    new CopyTransfer(host, target,
                            Collections.singletonMap(remote,
                                    new CommandLinePathParser(input)
                                            .parse(input.getOptionValues(action.name())[1]))),
                    source, destination);
        default:
            throw new BackgroundException(LocaleFactory.localizedString("Unknown"),
                    String.format("Unknown transfer type %s", action.name()));
        }
    } catch (ConnectionCanceledException e) {
        log.warn("Connection canceled", e);
        return Exit.success;
    } catch (BackgroundException e) {
        final StringAppender b = new StringAppender();
        b.append(e.getMessage());
        b.append(e.getDetail());
        console.printf("%n%s", b.toString());
    } finally {
        this.disconnect(source);
        this.disconnect(destination);
        console.printf("%n%s", StringUtils.EMPTY);
    }
    return Exit.failure;
}

From source file:com.esofthead.mycollab.jetty.GenericServerRunner.java

private void execute() throws Exception {
    server = new Server((port > 0) ? port : 8080);
    contexts = new ContextHandlerCollection();

    if (!checkConfigFileExist()) {
        System.err.println(/*from w  w  w . j  ava 2 s  .  c o m*/
                "It seems this is the first time you run MyCollab. For complete installation, you must open the brower and type address http://localhost:"
                        + port + " and complete the steps to install MyCollab.");
        installationContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
        installationContextHandler.setContextPath("/");

        installServlet = new InstallationServlet();
        installationContextHandler.addServlet(new ServletHolder(installServlet), "/install");
        installationContextHandler.addServlet(new ServletHolder(new DatabaseValidate()), "/validate");
        installationContextHandler.addServlet(new ServletHolder(new EmailValidationServlet()),
                "/emailValidate");

        installationContextHandler.addServlet(new ServletHolder(new AssetHttpServletRequestHandler()),
                "/assets/*");
        installationContextHandler.addServlet(new ServletHolder(new SetupServlet()), "/*");
        installationContextHandler.addLifeCycleListener(new ServerLifeCycleListener());

        server.setStopAtShutdown(true);
        contexts.setHandlers(new Handler[] { installationContextHandler });
    } else {
        WebAppContext appContext = initWebAppContext();
        ServletContextHandler upgradeContextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
        upgradeContextHandler.setServer(server);
        upgradeContextHandler.setContextPath("/it");
        upgradeContextHandler.addServlet(new ServletHolder(new UpgradeServlet()), "/upgrade");
        upgradeContextHandler.addServlet(new ServletHolder(new UpgradeStatusServlet()), "/upgrade_status");
        contexts.setHandlers(new Handler[] { upgradeContextHandler, appContext });
    }

    server.setHandler(contexts);
    server.start();

    ShutdownMonitor.getInstance().start();

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            LOG.error("There is uncatch exception", e);
        }
    });

    server.join();
}

From source file:com.nkahoang.screenstandby.Main.java

@SuppressLint("NewApi")
@Override/*www.  ja  v a2 s .  com*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (!prefs.getBoolean("wizardRun", false)) {
        Intent i = new Intent(this, com.nkahoang.screenstandby.AutoSettingWizard.class);
        this.startActivity(i);
        this.finish();
    }

    animFlippingWholePage = (ObjectAnimator) AnimatorInflater.loadAnimator(Main.this,
            R.animator.flipping_whole_page);

    animFlippingRight = (ObjectAnimator) AnimatorInflater.loadAnimator(Main.this, R.animator.flipping_right);
    animFlippingLeft = (ObjectAnimator) AnimatorInflater.loadAnimator(Main.this, R.animator.flipping_left);

    animFlippingBack = (ObjectAnimator) AnimatorInflater.loadAnimator(Main.this, R.animator.flipping_back);
    animFlippingBackFromLeft = (ObjectAnimator) AnimatorInflater.loadAnimator(Main.this,
            R.animator.flipping_back_from_left);

    animZoomingOut = (AnimatorSet) AnimatorInflater.loadAnimator(Main.this, R.animator.zoomout);
    animZoomingIn = (AnimatorSet) AnimatorInflater.loadAnimator(Main.this, R.animator.zoomin);

    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

    setContentView(useMetro ? R.layout.activity_main : R.layout.activity_main_alt);
    View rootView = this.findViewById(R.id.rootView);
    animFlippingWholePage.setTarget(rootView);
    if (!useMetro)
        animFlippingWholePage.setDuration(0);
    if (android.os.Build.VERSION.SDK_INT >= 11) {
        rootView.setPivotX(0);
        rootView.setPivotY(0);
    }
    AnimatorProxy.wrap(rootView).setPivotX(0);
    AnimatorProxy.wrap(rootView).setPivotY(0);

    mPager = (ViewPager) findViewById(R.id.mainpager);
    mPagerAdapter = new MainPagerAdapter(this.getSupportFragmentManager());
    mPager.setAdapter(mPagerAdapter);

    final TextView txtTitle = ((TextView) this.findViewById(R.id.txtTitle));
    txtTitle.setTypeface(useMetro ? typefaceLight : typeface);
    final Button txtTitleNext = ((Button) this.findViewById(R.id.txtTitleNex));
    txtTitleNext.setTypeface(typefaceLight);
    txtTitleNext.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mPager.getCurrentItem() < (NUM_PAGES - 1)) {
                mPager.setCurrentItem(mPager.getCurrentItem() + 1);
            }
        }
    });

    final View indicator1 = Main.this.findViewById(R.id.indicator1);
    final View indicator2 = Main.this.findViewById(R.id.indicator2);
    final View indicator3 = Main.this.findViewById(R.id.indicator3);

    mPager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageSelected(int arg0) {
            txtTitle.setText(mPagerAdapter.getPageTitle(arg0));
            txtTitleNext.setText(mPagerAdapter.getPageTitle(arg0 + 1));
            int selected = useMetro ? R.drawable.circleindicator_selected : R.drawable.barindicator_selected;
            int normal = useMetro ? R.drawable.circleindicator : R.drawable.barindicator;
            indicator1.setBackgroundResource(arg0 == 0 ? selected : normal);
            indicator2.setBackgroundResource(arg0 == 1 ? selected : normal);
            indicator3.setBackgroundResource(arg0 == 2 ? selected : normal);
        }
    });

    if (!useMetro) {
        ((ImageButton) this.findViewById(R.id.btnBackToMain)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mPager.setCurrentItem(0);
            }
        });
    }
    ImageButton btnOverflows = (ImageButton) this.findViewById(R.id.btnOverflows);
    btnOverflows.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Main.this.openOptionsMenu();
        }
    });

    ImageButton btnSettings = (ImageButton) this.findViewById(R.id.btnSettings);
    btnSettings.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            openSettings();
        }
    });

    ImageButton btnVideoClip = (ImageButton) this.findViewById(R.id.btnVidClip);
    btnVideoClip.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            openVideoClip();
        }
    });

    ImageButton btnTroubleshooting = (ImageButton) this.findViewById(R.id.btntroubleshooting);
    btnTroubleshooting.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            animFlippingWholePage.start();
            animFlippingWholePage.removeAllListeners();
            animFlippingWholePage.addListener(new AnimatorListener() {

                @Override
                public void onAnimationCancel(Animator arg0) {
                }

                @Override
                public void onAnimationEnd(Animator arg0) {
                    Intent intent = new Intent(Main.this, TroubleshootingActivity.class);
                    startActivity(intent);
                    animFlippingWholePage.reverse();
                }

                @Override
                public void onAnimationRepeat(Animator arg0) {
                }

                @Override
                public void onAnimationStart(Animator arg0) {
                }
            });
        }
    });

    /*
    if (!ChangeLogHandler.IsChangeLogRead(this))
    {
       ChangeLogHandler.ShowChangelog(this);
    }
    */
    //warning();
}

From source file:org.apache.lens.server.LensServer.java

/** Registering a default uncaught exception handler. */
private static void registerDefaultExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/*  w w w  . jav a 2s  . c o  m*/
        public void uncaughtException(Thread t, Throwable e) {
            LOG.fatal("Uncaught exception in Thread " + t, e);
        }
    });
}

From source file:org.centum.android.MainActivity.java

/**
 * Report uncaught exceptions (crashes) to Analytics
 *///  ww w .  j a  va2 s .c o  m
private void setupUncaughtExceptionHandler() {
    ExceptionReporter myHandler = new ExceptionReporter(EasyTracker.getInstance(this),
            GAServiceManager.getInstance(), Thread.getDefaultUncaughtExceptionHandler(), this);

    StandardExceptionParser exceptionParser = new StandardExceptionParser(getApplicationContext(), null) {
        @Override
        public String getDescription(String threadName, Throwable t) {
            return "{" + threadName + "} " + "{" + Build.MODEL + "} " + "{" + Build.VERSION.SDK_INT + "} "
                    + Log.getStackTraceString(t);
        }
    };

    myHandler.setExceptionParser(exceptionParser);
    Thread.setDefaultUncaughtExceptionHandler(myHandler);
}

From source file:com.twitter.heron.metricsmgr.MetricsManager.java

/**
 * Metrics manager constructor/*from w w w  .  ja v a 2 s  .  c  o  m*/
 */
public MetricsManager(String topologyName, String cluster, String role, String environment, String serverHost,
        int serverPort, String metricsmgrId, SystemConfig systemConfig, MetricsSinksConfig config)
        throws IOException {
    this.topologyName = topologyName;
    this.cluster = cluster;
    this.role = role;
    this.environment = environment;
    this.metricsmgrId = metricsmgrId;
    this.config = config;
    this.metricsManagerServerLoop = new NIOLooper();

    // Init the Internal Metrics Export related stuff
    this.metricsManagerPublisher = Metrics.MetricPublisher.newBuilder().setHostname(getLocalHostName())
            .setPort(serverPort).setComponentName(METRICS_MANAGER_COMPONENT_NAME).setInstanceId(metricsmgrId)
            .setInstanceIndex(METRICS_MANAGER_INSTANCE_ID).build();
    this.jvmMetrics = new JVMMetrics();
    this.metricsQueue = new Communicator<Metrics.MetricPublisherPublishMessage>(null,
            this.metricsManagerServerLoop);
    this.metricsCollector = new MetricsCollector(metricsManagerServerLoop, metricsQueue);
    this.heronMetricsExportInterval = systemConfig.getHeronMetricsExportInterval();

    this.mainThreadId = Thread.currentThread().getId();

    // Init the ErrorReportHandler
    ErrorReportLoggingHandler.init(metricsCollector, heronMetricsExportInterval,
            systemConfig.getHeronMetricsMaxExceptionsPerMessageCount());

    // Set up the internal Metrics Export routine
    setupInternalMetricsExport();

    // Set up JVM metrics
    // TODO -- change the config name
    setupJVMMetrics(systemConfig.getInstanceMetricsSystemSampleInterval());

    // Init the HeronSocketOptions
    HeronSocketOptions serverSocketOptions = new HeronSocketOptions(
            systemConfig.getMetricsMgrNetworkWriteBatchSize(),
            systemConfig.getMetricsMgrNetworkWriteBatchTime(), systemConfig.getMetricsMgrNetworkReadBatchSize(),
            systemConfig.getMetricsMgrNetworkReadBatchTime(),
            systemConfig.getMetricsMgrNetworkOptionsSocketSendBufferSize(),
            systemConfig.getMetricsMgrNetworkOptionsSocketReceivedBufferSize(),
            systemConfig.getMetricsMgrNetworkOptionsMaximumPacketSize());

    // Set the MultiCountMetric for MetricsManagerServer
    MultiCountMetric serverCounters = new MultiCountMetric();
    metricsCollector.registerMetric(METRICS_MANAGER_COMPONENT_NAME, serverCounters,
            (int) heronMetricsExportInterval.getSeconds());

    // Construct the MetricsManagerServer
    metricsManagerServer = new MetricsManagerServer(metricsManagerServerLoop, serverHost, serverPort,
            serverSocketOptions, serverCounters);

    executors = Executors.newFixedThreadPool(config.getNumberOfSinks());
    sinkExecutors = new ConcurrentHashMap<>(config.getNumberOfSinks());
    sinksRetryAttempts = new ConcurrentHashMap<>(config.getNumberOfSinks());
    // Add exception handler for any uncaught exception here.
    Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());

    // Init the Sinks
    for (String sinkId : config.getSinkIds()) {
        // Instantiate a new instance by using reflection
        SinkExecutor sinkExecutor = initSinkExecutor(sinkId);

        // Update the SinkExecutor in sinkExecutors
        sinkExecutors.put(sinkId, sinkExecutor);

        // Set the retry attempts
        Object restartAttempts = config.getConfigForSink(sinkId)
                .get(MetricsSinksConfig.CONFIG_KEY_SINK_RESTART_ATTEMPTS);
        // Supply with default value is config is null
        sinksRetryAttempts.put(sinkId,
                restartAttempts == null ? MetricsSinksConfig.DEFAULT_SINK_RESTART_ATTEMPTS
                        : TypeUtils.getInteger(restartAttempts));

        // Update the list of Communicator in Metrics Manager Server
        metricsManagerServer.addSinkCommunicator(sinkExecutor.getCommunicator());
    }
}

From source file:org.aitools.programd.Core.java

/**
 * Initializes and starts up the Core./*from  w w  w.ja  v a 2s. c o m*/
 */
@SuppressWarnings("boxing")
protected void start() {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler());

    // Set up the XML parsing feature settings.
    this._xmlParserFeatureSettings = new HashMap<String, Boolean>(6);
    this._xmlParserFeatureSettings.put("http://xml.org/sax/features/use-entity-resolver2",
            this._settings.xmlParserUseEntityResolver2());
    this._xmlParserFeatureSettings.put("http://xml.org/sax/features/validation",
            this._settings.xmlParserUseValidation());
    this._xmlParserFeatureSettings.put("http://apache.org/xml/features/validation/schema",
            this._settings.xmlParserUseSchemaValidation());
    this._xmlParserFeatureSettings.put("http://apache.org/xml/features/honour-all-schemaLocations",
            this._settings.xmlParserHonourAllSchemaLocations());
    this._xmlParserFeatureSettings.put("http://apache.org/xml/features/xinclude",
            this._settings.xmlParserUseXInclude());
    this._xmlParserFeatureSettings.put("http://apache.org/xml/features/validate-annotations",
            this._settings.xmlParserValidateAnnotations());

    // Use the stdout and stderr appenders in a special way, if they are defined.
    ConsoleStreamAppender stdOutAppender = ((ConsoleStreamAppender) Logger.getLogger("programd")
            .getAppender("stdout"));
    if (stdOutAppender != null) {
        if (!stdOutAppender.isWriterSet()) {
            stdOutAppender.setWriter(new OutputStreamWriter(System.out));
        }
    }

    ConsoleStreamAppender stdErrAppender = ((ConsoleStreamAppender) Logger.getLogger("programd")
            .getAppender("stderr"));
    if (stdErrAppender != null) {
        if (!stdErrAppender.isWriterSet()) {
            stdErrAppender.setWriter(new OutputStreamWriter(System.err));
        }
    }

    // Set up an interception of calls to the JDK logging system and re-route to log4j.
    JDKLogHandler.setupInterception();

    this._logger.info(String.format("Base URL for Program D Core: \"%s\".", this._baseURL));

    this._aimlProcessorRegistry = new AIMLProcessorRegistry();

    this._graphmapper = Classes.getSubclassInstance(Graphmapper.class,
            this._settings.getGraphmapperImplementation(), "Graphmapper implementation", this);
    this._bots = new Bots();
    this._processes = new ManagedProcesses(this);

    // Get an instance of the settings-specified PredicateManager.
    this._predicateManager = Classes.getSubclassInstance(PredicateManager.class,
            this._settings.getPredicateManagerImplementation(), "PredicateManager", this);

    // Get the hostname (used occasionally).
    try {
        this._hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        this._hostname = "unknown hostname";
    }

    // Load the plugin config.
    URL pluginConfigURL = this._settings.getPluginConfigURL();
    if (pluginConfigURL != null) {
        pluginConfigURL = URLTools.contextualize(this._baseURL, pluginConfigURL);
        try {
            if (pluginConfigURL.openStream() != null) {
                this._pluginConfig = JDOM.getDocument(pluginConfigURL, this._logger);
            }
        } catch (IOException e) {
            // Don't load plugin config.
        }
    }

    // TODO: Make this work even if the classes aren't in a jar.
    Package pkg = Package.getPackage("org.aitools.programd");
    this._logger.info(String.format("Starting %s version %s [%s].", pkg.getSpecificationTitle(),
            pkg.getSpecificationVersion(), pkg.getImplementationVersion()));
    this._logger.info(UserSystem.jvmDescription());
    this._logger.info(UserSystem.osDescription());
    this._logger.info(UserSystem.memoryReport());
    this._logger.info("Predicates with no values defined will return: \""
            + this._settings.getPredicateEmptyDefault() + "\".");

    try {
        // Create the AIMLWatcher if configured to do so.
        if (this._settings.useAIMLWatcher()) {
            this._aimlWatcher = new AIMLWatcher(this);
        }

        // Setup a JavaScript interpreter if supposed to.
        setupInterpreter();

        // Start the AIMLWatcher if configured to do so.
        startWatcher();

        this._logger.info("Starting up the Graphmaster.");

        // Start loading bots.
        URL botConfigURL = this._settings.getBotConfigURL();
        if (botConfigURL != null) {
            loadBotConfig(botConfigURL);
        } else {
            this._logger.warn("No bot config URL specified; no bots will be loaded.");
        }

        // Request garbage collection.
        System.gc();

        this._logger.info(UserSystem.memoryReport());

        // Start the heart, if enabled.
        startHeart();
    } catch (DeveloperError e) {
        alert("developer error", e);
    } catch (UserError e) {
        alert("user error", e);
    } catch (RuntimeException e) {
        alert("unforeseen runtime exception", e);
    } catch (Throwable e) {
        alert("unforeseen problem", e);
    }

    // Set the status indicator.
    this._status = Status.READY;

    // Exit immediately if configured to do so (for timing purposes).
    if (this._settings.exitImmediatelyOnStartup()) {
        shutdown();
    }
}

From source file:de.unidue.inf.is.ezdl.gframedl.EzDL.java

private static void initLogging() {
    System.setProperty("appDir", SystemUtils.getPropertyDir().getAbsolutePath());

    URL logConfigUrl = null;//from w ww.j  ava  2 s.  com
    File logConfigFile = new File(SystemUtils.getPropertyDir(), "/logging.properties");

    if (logConfigFile.exists()) {
        try {
            logConfigUrl = logConfigFile.toURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    } else {
        logConfigUrl = EzDL.class.getResource("/log/logging.properties");
    }

    if (logConfigUrl != null) {
        PropertyConfigurator.configure(logConfigUrl);
    } else {
        System.err.println("no logger config found!");
    }

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            logger.error("Uncaught exception in Thread " + t.getName(), e);
        }
    });
    System.err.close();
}