Example usage for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler

List of usage examples for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler

Introduction

In this page you can find the example usage for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler.

Prototype

Thread.UncaughtExceptionHandler

Source Link

Usage

From source file:fr.iphc.grid.jobmonitor.CeList.java

public static void main(String[] args) throws Exception {

    SessionFactory.createSession(true);/*  w ww.  j  a va 2  s  .  c  o  m*/
    CeList command = new CeList();
    CommandLine line = command.parse(args);
    Integer timeout = 0;
    String TableSql = "monce";
    //      MySQLAccess sql = new MySQLAccess();
    if (line.getOptionValue(OPT_TIMEOUT) == null) {
        timeout = 15;
    } else {
        timeout = Integer.parseInt(line.getOptionValue(OPT_TIMEOUT));
    }
    timeout = timeout * 60; // convertir en secondes
    Date start = new Date();
    String OutDir = line.getOptionValue(OPT_OUTDIR);

    if (OutDir == null) {
        OutDir = "/tmp/thread";
    }
    ArrayList<URL> CeList = null;
    if (line.getOptionValue(OPT_CEPATH) == null) {
        CeList = AvailableLdapCe();
        //         for (URL k : CeList) {
        //            // System.out.println(k);
        //         }
    } else {
        CeList = AvailableCe(line.getOptionValue(OPT_CEPATH));
    }
    Boolean ret = initDirectory(new File(OutDir));
    if (!ret) {
        System.out.println("ERROR: " + OutDir + "STOP");
        System.exit(-1);
    }

    // check if we can connect to the grid
    // try{
    // SessionFactory.createSession(true);
    // }catch(NoSuccessException e){
    // System.err.println("Could not connect to the grid at all
    // ("+e.getMessage()+")");
    // System.err.println("Aborting");
    // System.exit(0);
    //
    // }

    SubmitterThread[] st = new SubmitterThread[CeList.size()];

    Iterator<URL> i = CeList.iterator();
    int index = 0;
    while (i.hasNext()) {
        URL serviceURL = i.next();
        // Ne pas importer dans thread because options.
        Properties prop = new Properties();
        prop.setProperty("Executable", "/bin/hostname");//
        // prop.setProperty("Executable", "touch /dev/null");
        JobDescription desc = createJobDescription(prop);
        desc.setAttribute(JobDescription.INTERACTIVE, "true");
        desc.setAttribute(JobDescription.EXECUTABLE, "/bin/hostname");
        // proxy="/home/dsa/.globus/biomed.txt";
        // Context ctx = ContextFactory.createContext();
        // ctx.setAttribute(Context.TYPE, "VOMS");
        // ctx.setAttribute(Context.USERVO, "biomed");
        // ctx.setAttribute(Context.USERPROXY,proxy);
        // Session session = SessionFactory.createSession(false);
        // session.addContext(ctx);
        Session session = SessionFactory.createSession(true);
        st[index] = new SubmitterThread(serviceURL, session, desc, OutDir, timeout, start);
        st[index].setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                // System.out.println("Error! An exception occured in "
                // + t.getName() + ". Cause: " + e.getMessage());
            }
        });
        st[index].start();
        // Thread.sleep(15*1000);
        // test si fichier exist
        // System.out.println("Alive
        // "+OutDir+"/"+serviceURL.getHost()+"_"+serviceURL.getPath().replaceAll("/cream-","")+".out");
        // while ((!((new
        // File(OutDir+"/"+serviceURL.getHost()+"_"+serviceURL.getPath().replaceAll("/cream-","")+".out").exists())
        // ||
        // (new
        // File(OutDir+"/"+serviceURL.getHost()+"_"+serviceURL.getPath().replaceAll("/cream-","")+".err").exists()))))
        // {
        // Thread.sleep(500);
        // }
        // System.out.println("Alive "+serviceURL.getHost()+"-"+ index+"FILE
        // EXIST");
        index++;

    }
    ;

    // System.out.println("BEGIN LOOP: Max " + index);
    long date_start = System.currentTimeMillis();
    // System.out.println("BEGIN START: " + date_start);
    Integer time_out = (timeout + 180) * 1000; // unit ms value in minute
    // +120
    // =delta par rapport thread
    Boolean Alive = true;
    //      int nb = 0;
    long now = System.currentTimeMillis();
    do {
        now = System.currentTimeMillis();
        Alive = false;
        //         nb = 0;
        for (int j = 0; j < index; j++) {
            if (st[j].isAlive()) {
                // System.out.println("Alive "+j);
                Alive = true;
                //               nb++;
            }
        }
        // System.out.println(nb);
        Thread.sleep(10000);
    } while ((Alive) && ((now - date_start) < time_out));

    for (int j = 0; j < index; j++) {
        if (st[j].isAlive()) {
            st[j].Requeststop();
        }
    }
    BilanCe(OutDir, CeList, TableSql);
    jobManagerLdap jm = new jobManagerLdap();
    jm.updateLdapCe();
    System.out.println("END " + new Date());
    // faire un traitement...
    System.exit(0);
}

From source file:majordodo.task.BrokerTestUtils.java

@Before
public void brokerTestUtilsBefore() throws Exception {
    // Setup exception handler
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override// www . j  av a 2s. com
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
            unhandledExceptions.add(e);
        }
    });

    // Setup Logger
    System.out.println("Setup logger to level " + logLevel.getName());
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(logLevel);
    ch.setFormatter(new Formatter() {
        @Override
        public String format(LogRecord record) {
            return "" + new java.sql.Timestamp(record.getMillis()) + " " + record.getLevel() + " ["
                    + getThreadName(record.getThreadID()) + "<" + record.getThreadID() + ">] "
                    + record.getLoggerName() + ": " + formatMessage(record) + "\n";
        }
    });
    java.util.logging.Logger.getLogger("").setLevel(logLevel);
    java.util.logging.Logger.getLogger("").addHandler(ch);

    // Initialize groupsMap
    groupsMap.clear();
    groupsMap.put(userId, group);

    // Setup workdir
    Path mavenTargetDir = Paths.get("target").toAbsolutePath();
    workDir = Files.createTempDirectory(mavenTargetDir, "test" + System.nanoTime());

    if (startBroker) {
        broker = new Broker(brokerConfig, new FileCommitLog(workDir, workDir, 1024 * 1024),
                new TasksHeap(1000, createTaskPropertiesMapperFunction()));
        broker.startAsWritable();

        server = new NettyChannelAcceptor(broker.getAcceptor());
        server.start();
    }
    if (startReplicatedBrokers) {
        zkServer = new ZKTestEnv(folderZk.getRoot().toPath());
        zkServer.startBookie();

        // Broker 1
        broker1 = new Broker(broker1Config,
                new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(),
                        folderSnapshots.newFolder().toPath(),
                        BrokerHostData.formatHostdata(
                                new BrokerHostData(broker1Host, broker1Port, "", false, null)),
                        false),
                new TasksHeap(1000, createTaskPropertiesMapperFunction()));

        broker1.startAsWritable();

        server1 = new NettyChannelAcceptor(broker1.getAcceptor(), broker1Host, broker1Port);
        server1.start();

        // Broker 2
        broker2 = new Broker(broker2Config,
                new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(),
                        folderSnapshots.newFolder().toPath(),
                        BrokerHostData.formatHostdata(
                                new BrokerHostData(broker2Host, broker2Port, "", false, null)),
                        false),
                new TasksHeap(1000, createTaskPropertiesMapperFunction()));

        broker2.start();

        server2 = new NettyChannelAcceptor(broker2.getAcceptor(), broker2Host, broker2Port);
        server2.start();

        // Broker locator
        brokerLocator = new ZKBrokerLocator(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath());
    }

}

From source file:com.splicemachine.derby.stream.control.ControlDataSet.java

@Override
public DataSet<V> union(DataSet<V> dataSet) {
    ThreadPoolExecutor tpe = null;
    try {//from   ww w.j  a v a  2s.  c  o m

        ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("union-begin-query-%d")
                .setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                    @Override
                    public void uncaughtException(Thread t, Throwable e) {
                        e.printStackTrace();
                    }
                }).build();
        tpe = new ThreadPoolExecutor(2, 2, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), factory,
                new ThreadPoolExecutor.CallerRunsPolicy());
        tpe.allowCoreThreadTimeOut(false);
        tpe.prestartAllCoreThreads();
        Future<Iterator<V>> leftSideFuture = tpe.submit(new NonLazy(iterator));
        Future<Iterator<V>> rightSideFuture = tpe.submit(new NonLazy(((ControlDataSet<V>) dataSet).iterator));

        return new ControlDataSet<>(Iterators.concat(leftSideFuture.get(), rightSideFuture.get()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (tpe != null)
            tpe.shutdown();
    }
}

From source file:org.midonet.midolman.Midolman.java

private void setUncaughtExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override//from  w  w  w.j a v  a2  s.co m
        public void uncaughtException(Thread t, Throwable e) {
            log.error("Unhandled exception: ", e);
            dumpStacks();
            System.exit(MIDOLMAN_ERROR_CODE_UNHANDLED_EXCEPTION);
        }
    });
}

From source file:net.technicpack.launcher.LauncherMain.java

private static void setupLogging(LauncherDirectories directories, ResourceLoader resources) {
    System.out.println("Setting up logging");
    final Logger logger = Utils.getLogger();
    File logDirectory = new File(directories.getLauncherDirectory(), "logs");
    if (!logDirectory.exists()) {
        logDirectory.mkdir();/*ww w .  jav a2s.  c  o  m*/
    }
    File logs = new File(logDirectory, "techniclauncher_%D.log");
    RotatingFileHandler fileHandler = new RotatingFileHandler(logs.getPath());

    fileHandler.setFormatter(new BuildLogFormatter(resources.getLauncherBuild()));

    for (Handler h : logger.getHandlers()) {
        logger.removeHandler(h);
    }
    logger.addHandler(fileHandler);
    logger.setUseParentHandlers(false);

    LauncherMain.consoleFrame = new ConsoleFrame(2500, resources.getImage("icon.png"));
    Console console = new Console(LauncherMain.consoleFrame, resources.getLauncherBuild());

    logger.addHandler(new ConsoleHandler(console));

    System.setOut(new PrintStream(new LoggerOutputStream(console, Level.INFO, logger), true));
    System.setErr(new PrintStream(new LoggerOutputStream(console, Level.SEVERE, logger), true));

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            logger.log(Level.SEVERE, "Unhandled Exception in " + t, e);

            //                if (errorDialog == null) {
            //                    LauncherFrame frame = null;
            //
            //                    try {
            //                        frame = Launcher.getFrame();
            //                    } catch (Exception ex) {
            //                        //This can happen if we have a very early crash- before Launcher initializes
            //                    }
            //
            //                    errorDialog = new ErrorDialog(frame, e);
            //                    errorDialog.setVisible(true);
            //                }
        }
    });
}

From source file:org.apache.rya.streams.client.command.AddQueryAndLoadStatementsStreamsIT.java

@Test
public void testLubm() throws Exception {
    // Arguments that add a query to Rya Streams.
    final String query = "PREFIX lubm: <" + LUBM_PREFIX + "> \n" + "SELECT * WHERE \n" + "{ \n"
            + "  ?graduateStudent a lubm:GraduateStudent . \n" + "  ?underGradUniversity a lubm:University . \n"
            + "  ?graduateStudent lubm:undergraduateDegreeFrom ?underGradUniversity . \n" + "}";

    final String query2 = "PREFIX lubm: <" + LUBM_PREFIX + "> \n" + "SELECT * WHERE \n" + "{ \n"
            + "  ?graduateStudent a lubm:GraduateStudent . \n" + "  ?underGradUniversity a lubm:University . \n"
            + "  ?graduateStudent lubm:undergraduateDegreeFrom ?underGradUniversity . \n" + "}";

    final String[] addArgs = new String[] { "--ryaInstance", "" + ryaInstance, "--kafkaHostname",
            kafka.getKafkaHostname(), "--kafkaPort", kafka.getKafkaPort(), "--query", query, "--isActive",
            "true", "--isInsert", "false" };

    final String[] addArgs2 = new String[] { "--ryaInstance", "" + ryaInstance, "--kafkaHostname",
            kafka.getKafkaHostname(), "--kafkaPort", kafka.getKafkaPort(), "--query", query2, "--isActive",
            "true", "--isInsert", "false" };

    // Execute the command.
    final AddQueryCommand command = new AddQueryCommand();
    command.execute(addArgs);/*w w  w. j  a v a2  s . co m*/
    // Add the same query twice to confirm that joins aren't being performed
    // across both queries.
    command.execute(addArgs2);

    // Show that the query was added to the Query Repository.
    final Set<StreamsQuery> queries = queryRepo.list();
    assertEquals(2, queries.size());
    final StreamsQuery streamsQuery = queries.iterator().next();
    final UUID queryId = streamsQuery.getQueryId();
    assertEquals(query, queries.iterator().next().getSparql());

    // Load a file of statements into Kafka.
    final String visibilities = "";
    final String[] loadArgs = new String[] { "--ryaInstance", "" + ryaInstance, "--kafkaHostname",
            kafka.getKafkaHostname(), "--kafkaPort", kafka.getKafkaPort(), "--statementsFile",
            LUBM_FILE.toString(), "--visibilities", visibilities };

    // Load the file of statements into the Statements topic.
    new LoadStatementsCommand().execute(loadArgs);

    final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance);
    final String resultsTopic = KafkaTopics.queryResultsTopic(ryaInstance, queryId);

    final TopologyFactory factory = new TopologyFactory();
    final TopologyBuilder builder = factory.build(query, statementsTopic, resultsTopic,
            new RandomUUIDFactory());

    // Start the streams program.
    final Properties props = kafka.createBootstrapServerConfig();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, UUID.randomUUID().toString());
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    final AtomicReference<String> errorMessage = new AtomicReference<>();
    final KafkaStreams streams = new KafkaStreams(builder, new StreamsConfig(props));
    streams.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            final String stackTrace = ExceptionUtils.getStackTrace(throwable);
            errorMessage.getAndSet("Kafka Streams threw an uncaught exception in thread (" + thread.getName()
                    + "): " + stackTrace);
        }
    });
    streams.cleanUp();
    try {
        streams.start();

        // Wait for the streams application to start. Streams only see data after their consumers are connected.
        Thread.sleep(6000);

        // Wait for the final results to appear in the output topic and verify the expected Binding Sets were found.
        try (Consumer<String, VisibilityBindingSet> consumer = KafkaTestUtil.fromStartConsumer(kafka,
                StringDeserializer.class, VisibilityBindingSetDeserializer.class)) {
            // Register the topic.
            consumer.subscribe(Arrays.asList(resultsTopic));

            // Poll for the result.
            final Set<VisibilityBindingSet> results = Sets.newHashSet(KafkaTestUtil.pollForResults(500,
                    2 * LUBM_EXPECTED_RESULTS_COUNT, LUBM_EXPECTED_RESULTS_COUNT, consumer));

            System.out.println("LUBM Query Results Count: " + results.size());
            // Show the correct binding sets results from the job.
            assertEquals(LUBM_EXPECTED_RESULTS_COUNT, results.size());
        }
    } finally {
        streams.close();
    }

    if (StringUtils.isNotBlank(errorMessage.get())) {
        fail(errorMessage.get());
    }
}

From source file:ch.fork.AdHocRailway.ui.AdHocRailway.java

public AdHocRailway(org.apache.commons.cli.CommandLine parsedCommandLine) {
    super(TITLE);
    try {//w  w  w  . j a va  2  s .co  m

        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:ch.cyberduck.cli.Terminal.java

protected Exit execute() {
    final Console console = new Console();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/*from w  w w  . ja v  a 2s .  c  om*/
        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.igormaznitsa.ideamindmap.utils.IdeaUtils.java

public static void openInSystemViewer(@Nonnull final DialogProvider dialogProvider,
        @Nullable final VirtualFile theFile) {
    final File file = vfile2iofile(theFile);

    if (file == null) {
        LOGGER.error("Can't find file to open, null provided");
        dialogProvider.msgError("Can't find file to open");
    } else {// w w w  .  ja  va 2 s  . c o m
        final Runnable startEdit = new Runnable() {
            @Override
            public void run() {
                boolean ok = false;
                if (Desktop.isDesktopSupported()) {
                    final Desktop dsk = Desktop.getDesktop();
                    if (dsk.isSupported(Desktop.Action.OPEN)) {
                        try {
                            dsk.open(file);
                            ok = true;
                        } catch (Throwable ex) {
                            LOGGER.error("Can't open file in system viewer : " + file, ex);//NOI18N
                        }
                    }
                }
                if (!ok) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialogProvider.msgError("Can't open file in system viewer! See the log!");//NOI18N
                            Toolkit.getDefaultToolkit().beep();
                        }
                    });
                }
            }
        };
        final Thread thr = new Thread(startEdit, " MMDStartFileEdit");//NOI18N
        thr.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(final Thread t, final Throwable e) {
                LOGGER.error("Detected uncaught exception in openInSystemViewer() for file " + file, e);
            }
        });

        thr.setDaemon(true);
        thr.start();
    }
}

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(// ww  w . jav a2s.c om
                "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();
}