Example usage for java.lang Thread setDaemon

List of usage examples for java.lang Thread setDaemon

Introduction

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

Prototype

public final void setDaemon(boolean on) 

Source Link

Document

Marks this thread as either a #isDaemon daemon thread or a user thread.

Usage

From source file:com.limegroup.gnutella.gui.DaapManager.java

/**
 * Starts the DAAP Server//  ww w .  j av  a2s .  c om
 */
public synchronized void start() throws IOException {

    if (!isServerRunning()) {

        try {

            InetAddress addr = InetAddress.getLocalHost();

            if (addr.isLoopbackAddress() || !(addr instanceof Inet4Address)) {
                addr = null;
                Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
                if (interfaces != null) {
                    while (addr == null && interfaces.hasMoreElements()) {
                        NetworkInterface nif = (NetworkInterface) interfaces.nextElement();
                        Enumeration addresses = nif.getInetAddresses();
                        while (addresses.hasMoreElements()) {
                            InetAddress address = (InetAddress) addresses.nextElement();
                            if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                                addr = address;
                                break;
                            }
                        }
                    }
                }
            }

            if (addr == null) {
                stop();
                // No valid IP address -- just ignore, since
                // it's probably the user isn't connected to the
                // internet.  Next time they start, it might work.
                return;
            }

            rendezvous = new RendezvousService(addr);

            map = new SongURNMap();

            maxPlaylistSize = DaapSettings.DAAP_MAX_LIBRARY_SIZE.getValue();

            String name = DaapSettings.DAAP_LIBRARY_NAME.getValue();
            int revisions = DaapSettings.DAAP_LIBRARY_REVISIONS.getValue();
            boolean useLibraryGC = DaapSettings.DAAP_LIBRARY_GC.getValue();
            library = new Library(name, revisions, useLibraryGC);

            database = new Database(name);
            whatsNew = new Playlist(GUIMediator.getStringResource("SEARCH_TYPE_WHATSNEW"));
            creativecommons = new Playlist(GUIMediator.getStringResource("LICENSE_CC"));
            videos = new Playlist(GUIMediator.getStringResource("MEDIA_VIDEO"));

            Transaction txn = library.open(false);
            library.add(txn, database);
            database.add(txn, creativecommons);
            database.add(txn, whatsNew);
            database.add(txn, videos);
            creativecommons.setSmartPlaylist(txn, true);
            whatsNew.setSmartPlaylist(txn, true);
            videos.setSmartPlaylist(txn, true);
            txn.commit();

            LimeConfig config = new LimeConfig(addr);

            final boolean NIO = DaapSettings.DAAP_USE_NIO.getValue();

            server = DaapServerFactory.createServer(library, config, NIO);

            server.setAuthenticator(new LimeAuthenticator());
            server.setStreamSource(new LimeStreamSource());
            server.setFilter(new LimeFilter());

            if (!NIO) {
                server.setThreadFactory(new LimeThreadFactory());
            }

            final int maxAttempts = 10;

            for (int i = 0; i < maxAttempts; i++) {
                try {
                    server.bind();
                    break;
                } catch (BindException bindErr) {
                    if (i < (maxAttempts - 1)) {
                        // try next port...
                        config.nextPort();
                    } else {
                        throw bindErr;
                    }
                }
            }

            Thread serverThread = new ManagedThread(server, "DaapServerThread") {
                protected void managedRun() {
                    try {
                        super.managedRun();
                    } catch (Throwable t) {
                        DaapManager.this.stop();
                        if (!handleError(t)) {
                            GUIMediator.showError("ERROR_DAAP_RUN_ERROR");
                            DaapSettings.DAAP_ENABLED.setValue(false);
                            if (t instanceof RuntimeException)
                                throw (RuntimeException) t;
                            throw new RuntimeException(t);
                        }
                    }
                }
            };

            serverThread.setDaemon(true);
            serverThread.start();

            rendezvous.registerService();

        } catch (IOException err) {
            stop();
            throw err;
        }
    }
}

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

public SessionInfo(final Activity activity, final RemoteProfile _remoteProfile) {
    this.remoteProfile = _remoteProfile;
    this.mapOriginal = new LongSparseArray<>();

    VuzeRemoteApp.getNetworkState().addListener(this);

    // Bind and Open take a while, do it on the non-UI thread
    Thread thread = new Thread("bindAndOpen") {
        public void run() {
            String host = remoteProfile.getHost();
            if (host != null && host.length() > 0
                    && remoteProfile.getRemoteType() != RemoteProfile.TYPE_LOOKUP) {
                open(activity, remoteProfile.getUser(), remoteProfile.getAC(), remoteProfile.getProtocol(),
                        host, remoteProfile.getPort());
            } else {
                bindAndOpen(activity, remoteProfile.getAC(), remoteProfile.getUser());
            }//from   w  w w .  j ava 2 s.c o  m
        }
    };
    thread.setDaemon(true);
    thread.start();

}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.transformationmanager.services.FelixService.java

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

    if (D)//  w w  w.  j a va2s. c om
        Log.d(TAG, "Setting up a thread for felix.");

    Thread felixThread = new Thread() {

        @Override
        public void run() {

            File dexOutputDir = getApplicationContext().getDir("transformationmanager", 0);

            // if default bundles were not installed already, install them
            File f = new File(dexOutputDir.getAbsolutePath() + "/bundle");
            if (!f.isDirectory()) {
                if (D)
                    Log.i(TAG, "Installing default bundles...");
                unzipBundles(FelixService.this.getResources().openRawResource(R.raw.bundles),
                        dexOutputDir.getAbsolutePath() + "/");
            }

            FelixConfig felixConfig = new FelixConfig(dexOutputDir.getAbsolutePath());
            Map<String, String> configProperties = felixConfig.getProperties2();

            try {
                FrameworkFactory frameworkFactory = new org.apache.felix.framework.FrameworkFactory();

                felixFramework = frameworkFactory.newFramework(configProperties);
                felixFramework.init();
                AutoProcessor.process(configProperties, felixFramework.getBundleContext());
                felixFramework.start();

                // Registering the android context as an osgi service
                Hashtable<String, String> properties = new Hashtable<String, String>();
                properties.put("platform", "android");
                felixFramework.getBundleContext().registerService(Context.class.getName(),
                        getApplicationContext(), properties);

            } catch (Exception ex) {
                Log.e(TAG, "Felix could not be started", ex);
                ex.printStackTrace();
            }
        }
    };

    felixThread.setDaemon(true);
    felixThread.start();

    LocalBroadcastManager.getInstance(this).registerReceiver(downloadReceiver,
            new IntentFilter(FELIX_SUCCESSFUL_WEB_REQUEST));
}

From source file:joshie.mariculture.EnchiridionManager.java

@SideOnly(Side.CLIENT)
public void download() {
    final GuiScreenWorking screenWorking = new GuiScreenWorking();
    Minecraft.getMinecraft().displayGuiScreen(screenWorking);

    final Thread downloadThread = new Thread(new Runnable() {
        @Override/*from   w w  w  . j  a  va  2s. c om*/
        public void run() {
            screenWorking.resetProgressAndMessage(I18n.format("enchiridion.downloader.downloading"));
            screenWorking.resetProgresAndWorkingMessage("Starting...");

            File target;
            URL download;
            OutputStream output = null;
            InputStream input = null;
            try {
                target = new File(Minecraft.getMinecraft().mcDataDir + File.separator + "mods" + File.separator
                        + latestFileName);
                download = new URL(downloadLink);
                output = new FileOutputStream(target);
                input = download.openStream();
                DownloadCountingOutputStream countingOutputStream = new DownloadCountingOutputStream(output,
                        screenWorking);

                totalSize = Long.valueOf(download.openConnection().getHeaderField("Content-Length"));
                screenWorking.displayProgressMessage(
                        String.format("Downloading file (%.3f MB)...", totalSize / 1000000F));

                IOUtils.copy(input, countingOutputStream);
            } catch (IOException e) {
                //Delete file on close cause it could be corrupt
                new File(Minecraft.getMinecraft().mcDataDir + File.separator + "mods" + File.separator
                        + latestFileName).deleteOnExit();
                e.printStackTrace();

                proxy.showFailedScreen();
            } finally {
                IOUtils.closeQuietly(output);
                IOUtils.closeQuietly(input);
            }
        }
    }, "Enchiridion Downloader");

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

From source file:kihira.tails.common.FoxLibManager.java

@SideOnly(Side.CLIENT)
public void downloadFoxlib() {
    final GuiScreenWorking screenWorking = new GuiScreenWorking();
    Minecraft.getMinecraft().displayGuiScreen(screenWorking);

    final Thread downloadThread = new Thread(new Runnable() {
        @Override/*from   w  w w. j a va2 s.c o m*/
        public void run() {
            screenWorking.resetProgressAndMessage(I18n.format("foxlib.downloader.downloading"));
            screenWorking.resetProgresAndWorkingMessage("Starting...");

            File target;
            URL download;
            OutputStream output = null;
            InputStream input = null;
            try {
                target = new File(Minecraft.getMinecraft().mcDataDir + File.separator + "mods" + File.separator
                        + foxlibFileName);
                download = new URL(foxlibDownloadLink);
                output = new FileOutputStream(target);
                input = download.openStream();
                DownloadCountingOutputStream countingOutputStream = new DownloadCountingOutputStream(output,
                        screenWorking);

                totalSize = Long.valueOf(download.openConnection().getHeaderField("Content-Length"));
                screenWorking.displayProgressMessage(
                        String.format("Downloading file (%.3f MB)...", totalSize / 1000000F));

                IOUtils.copy(input, countingOutputStream);
            } catch (IOException e) {
                //Delete file on close cause it could be corrupt
                new File(Minecraft.getMinecraft().mcDataDir + File.separator + "mods" + File.separator
                        + foxlibFileName).deleteOnExit();
                e.printStackTrace();

                proxy.showFailedScreen();
            } finally {
                IOUtils.closeQuietly(output);
                IOUtils.closeQuietly(input);
            }
        }
    }, "FoxLib Downloader");
    downloadThread.setDaemon(true);
    downloadThread.start();
}

From source file:com.dell.asm.asmcore.asmmanager.app.AsmManagerApp.java

private void initAsmManagerApp() {
    try {// ww  w .java 2  s . c o  m
        Properties props = ConfigurationUtils.resolveAndReadPropertiesFile(ASM_MANAGER_CONFIG_FILE,
                this.getClass().getClassLoader());

        ASM_REPO_LOCATION = props.getProperty("asm_repo_location");
        razorApiUrl = props.getProperty(RAZOR_API_URL_PROPERTY);
        razorRepoStoreLocation = props.getProperty(RAZOR_REPO_STORE_PROPERTY);
        _logger.info("razorApiUrl = " + razorApiUrl);
        razorCron = props.getProperty(RAZOR_JOB_CRON_PROPERTY);
        _logger.info("razorCron = " + razorCron);
        asmDeployerApiUrl = props.getProperty(ASM_DEPLOYER_URL_PROPERTY);
        _logger.info("asmDeployerApiUrl = " + asmDeployerApiUrl);
        scheduledInventoryCron = props.getProperty(SCHEDULEDINVENTORY_JOB_CRON_PROPERTY);
        _logger.info("Scheduled Inventory cron expression =" + scheduledInventoryCron);
        fileSystemMaintenanceCron = props.getProperty(FILE_SYSTEM_MAINTENANCE_JOB_CRON_PROPERTY);
        _logger.info("Scheduled File SystemMaintenance cron expression =" + fileSystemMaintenanceCron);

        // must call as soon as we read URLs from property file
        ProxyUtil.initAsmDeployerProxy();

        final GenericDAO genericDAO = GenericDAO.getInstance();
        SettingEntity portsToPingSetting = genericDAO.getByName(ASM_PORTS_TO_PING, SettingEntity.class);
        if (portsToPingSetting == null) {
            String value = props.getProperty(PORTS_TO_PING_PROPERTY);
            if (value == null) {
                value = "22,80,135";
            }
            portsToPingSetting = new SettingEntity();
            portsToPingSetting.setName(ASM_PORTS_TO_PING);
            portsToPingSetting.setValue(value);
            genericDAO.create(portsToPingSetting);
        }
        List<String> items = Arrays.asList(portsToPingSetting.getValue().split("\\s*,\\s*"));
        _logger.info("Ports to ping configured to " + Arrays.toString(items.toArray()) + " ("
                + portsToPingSetting.getValue() + ")");

        setAsmManagerAppConfig(new AsmManagerAppConfig());

        String sConnectTimeout = props.getProperty(DISCOVERY_THREAD_CONNECT_TIMEOUT_PROPERTY);
        _logger.info("sConnectTimeout = " + sConnectTimeout);
        try {
            CONNECT_TIMEOUT = Integer.parseInt(sConnectTimeout);
            CONNECT_TIMEOUT = CONNECT_TIMEOUT * 1000;
        } catch (Exception e) {
            _logger.error("Unable to parse CONNECT_TIMEOUT", e);
        }

        String staggerDeploymentsSecs = props.getProperty(MULTI_DEPLOYMENTS_STAGGER_SECS_KEY);
        try {
            MULTI_DEPLOYMENTS_STAGGER_SECS = Integer.parseInt(staggerDeploymentsSecs);
        } catch (NumberFormatException nfe) {
            _logger.error("Unable to parse MULTI_DEPLOYMENTS_STAGGER_SECS_KEY: " + staggerDeploymentsSecs
                    + ", defaulting to 30 minutes");
            MULTI_DEPLOYMENTS_STAGGER_SECS = 30 * 60;
        }

        String sPuppetModulestoFilter = props.getProperty(PUPPET_MODULE_FILTER_PROPERTY);
        _logger.info("sPuppetModulestoFilter = " + sPuppetModulestoFilter);
        String[] parts = sPuppetModulestoFilter.split(",");
        if (parts != null) {
            for (String sModule : parts) {
                if (sModule != null) {
                    puppetModulesToFilter.add(sModule.trim());
                    _logger.info("Puppet module to filter:" + sModule.trim());
                }
            }
        }

        // this prevents exceptions on copyProperties with null Date
        ConvertUtilsBean convertUtilsBean = BeanUtilsBean.getInstance().getConvertUtils();
        convertUtilsBean.register(false, true, -1);
    } catch (IOException e) {
        _logger.info("Exception while parsing asmmanager properties file", e);
        throw new AsmManagerRuntimeException(e);
    }

    try {
        registerJobClasses();
        createDefaultRazorSyncJob();
    } catch (Exception t) {
        _logger.error("Unable to initialize AsmManagerApp. Register Jobs Failed.", t);
    }

    // Perform all initialization on a new thread to avoid holding up server initialization.
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            _logger.info("Starting AsmManagerApp initialization thread.");

            AsmManagerInitLifecycleListener.setStatus(AsmManagerInitLifecycleListener.UPDATING_INVENTORY);

            // Install Quartz Job Listeners
            try {
                FirmwareUpdateScheduleListener scheduleListener = new FirmwareUpdateScheduleListener();
                JobManager.getInstance().getScheduler().getListenerManager()
                        .addSchedulerListener(scheduleListener);

                GroupMatcher<JobKey> groupMatcher = GroupMatcher
                        .groupEquals(FirmwareUpdateJob.class.getSimpleName());
                JobManager.getInstance().getScheduler().getListenerManager().addJobListener(scheduleListener,
                        groupMatcher);

            } catch (Exception t) {
                _logger.error("Failed to install FirmwareUpdateScheduleListener", t);
            }

            try {
                setServiceContextUser(DBInit.DEFAULT_USER);
            } catch (Exception t) {
                _logger.error(
                        "Unable to initialize AsmManagerApp. Set service context default user to Admin failed.",
                        t);
            }

            try {
                // On Startup - Where we check to see if it exists (reverse) - If file does NOT exist - Run Inventory and create the file
                if (isRestore() || isRestartAfterApplianceUpdate()) {
                    // Run inventory on all Devices
                    runInventory();
                }
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp.  Running Inventory Failed.", t);
            }

            AsmManagerInitLifecycleListener.setStatus(AsmManagerInitLifecycleListener.UPDATING_TEMPLATES);

            try {
                createDefaultIOMCredential();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Creation of Default IOM Credential Failed.",
                        t);
            }

            try {
                updateExistingAddOnModules();
                updateAddOnModules();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Updating AddOnModules Failed.", t);
            }

            try {
                loadDefaultTemplates();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Loading of Default Templates Failed.", t);
            }

            try {
                updateFirmwareRepositoryBundleComponents();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Updating Firmware Bundle Components Failed.",
                        t);
            }
            try {
                loadEmbeddedFirmware();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Load embedded Firmware Failed.", t);
            }
            try {
                failCopyingAndPendingFirmwareRepositories();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Cleanup of rogue Firmware states Failed.",
                        t);
            }

            try {
                cleanUpDevices();
                cleanUpJobs();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp. Cleanup of Devices and Jobs Failed.", t);
            }

            try {
                ensureRazorReposExist();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp.  Ensuring Razor Repos Exist Failed.", t);
            }

            try {
                syncAppStateVars();
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp.  Sync Application State Variables Failed.",
                        t);
            }

            /**
             * Important to run this prior to revalidating ServiceTemplates since a broken OS
             * repository would then invalidate the template, which is the desired behavior.
             */
            try {
                cleanUpOsRepositories();
            } catch (Exception t) {
                _logger.error("Problem initializing AsmManagerApp.  Cleaning up OSRepositories failed.", t);
            }

            try {
                final ServiceTemplate defaultTemplate = getServiceTemplateService().getDefaultTemplate();
                //build a map of add on module components for future use.
                final List<AddOnModuleComponentEntity> addOnModuleComponentEntities = getAddOnModuleComponentsDAO()
                        .getAll(true);
                Map<String, ServiceTemplateComponent> addOnModuleComponentsMap = new HashMap<>();
                for (AddOnModuleComponentEntity entity : addOnModuleComponentEntities) {
                    ServiceTemplateComponent component = MarshalUtil.unmarshal(ServiceTemplateComponent.class,
                            entity.getMarshalledData());
                    addOnModuleComponentsMap.put(component.getId(), component);
                }

                // Correct differences between entity object values and entity marshaledTemplateData values
                reconcileServiceTemplateEntityData();
                revalidateStoredTemplates(defaultTemplate, addOnModuleComponentsMap);
                revalidateDeployedTemplates(defaultTemplate, addOnModuleComponentEntities,
                        addOnModuleComponentsMap);
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp.  Revalidating Templates Failed.", t);
            }

            try {
                createDefaultScheduledInventoryJob();
                createDefaultFileSystemMaintenanceJob();
                // please make sure there that all update deployment DAO calls made _before_ this line!!!
                createScheduledDeploymentStatusSyncJob(JOB_DELAY_SECS);
            } catch (Exception t) {
                _logger.error("Unable to initialize AsmManagerApp.  Creation of default jobs failed.", t);
            }

            AsmManagerInitLifecycleListener.setStatus(AsmManagerInitLifecycleListener.READY);
            _logger.info("Finished AsmManagerApp initialization.");

        }
    };

    // Run the initialization code in our thread group.
    Thread initThread = new Thread(new ThreadGroup(AsmManagerApp_THREADGROUP_NAME), runnable);
    initThread.setName(AsmManagerApp_INIT_THREAD_NAME);
    initThread.setDaemon(true);
    initThread.start();
}

From source file:com.thoughtworks.go.server.dao.PipelineSqlMapDaoIntegrationTest.java

@Test
public void shouldLoadAllActivePipelinesEvenWhenThereIsStageStatusChange() throws Exception {
    PipelineConfig twistConfig = PipelineMother.twoBuildPlansWithResourcesAndMaterials("twist", "dev", "ft");
    goConfigDao.addPipeline(twistConfig, "pipelinesqlmapdaotest");
    Pipeline twistPipeline = dbHelper.newPipelineWithAllStagesPassed(twistConfig);
    PipelineConfig mingleConfig = PipelineMother.twoBuildPlansWithResourcesAndMaterials("mingle", "dev", "ft");
    goConfigDao.addPipeline(mingleConfig, "pipelinesqlmapdaotest");
    final Pipeline firstPipeline = dbHelper.newPipelineWithAllStagesPassed(mingleConfig);
    final Pipeline secondPipeline = dbHelper.newPipelineWithFirstStagePassed(mingleConfig);
    dbHelper.scheduleStage(secondPipeline, mingleConfig.get(1));
    Pipeline thirdPipeline = dbHelper.newPipelineWithFirstStageScheduled(mingleConfig);
    Thread stageStatusChanger = new Thread() {
        @Override/*from  w w w . ja v a2  s . c om*/
        public void run() {
            for (;;) {
                pipelineDao.stageStatusChanged(secondPipeline.findStage("dev"));
                if (super.isInterrupted()) {
                    break;
                }
            }
        }
    };
    stageStatusChanger.setDaemon(true);
    stageStatusChanger.start();
    PipelineInstanceModels pipelineHistories = pipelineDao.loadActivePipelines();
    assertThat(pipelineHistories.size(), is(3));
    assertThat(pipelineHistories.get(0).getId(), is(thirdPipeline.getId()));
    assertThat(pipelineHistories.get(1).getId(), is(secondPipeline.getId()));
    assertThat(pipelineHistories.get(2).getId(), is(twistPipeline.getId()));
    assertThat(pipelineHistories.get(0).getBuildCause().getMaterialRevisions().isEmpty(), is(false));
    stageStatusChanger.interrupt();
}

From source file:com.mobicage.rogerthat.registration.RegistrationActivity2.java

private void tryConnect(final ProgressDialog pd, final int attempt, final String statusMessage,
        final RegistrationInfo info) {
    T.UI();/*from   w w  w  .  j a v  a2 s. c o m*/
    final Pausable pausable = this;

    if (attempt > XMPP_MAX_NUM_ATTEMPTS) {
        pd.dismiss();

        new AlertDialog.Builder(RegistrationActivity2.this).setMessage(getString(R.string.registration_error))
                .setCancelable(true).setPositiveButton(R.string.try_again, null).create().show();
        mWiz.reInit();
        mWiz.goBackToPrevious();
        return;
    }
    pd.setMessage(statusMessage + attempt);
    if (!pd.isShowing())
        pd.show();
    L.d("Registration attempt #" + attempt);

    final String xmppServiceName = info.mCredentials.getXmppServiceName();
    final String xmppAccount = info.mCredentials.getXmppAccount();
    final String xmppPassword = info.mCredentials.getPassword();

    final ConfigurationProvider cp = mService.getConfigurationProvider();
    Configuration cfg = cp.getConfiguration(RegistrationWizard2.CONFIGKEY);
    final String invitorCode = (cfg == null) ? null : cfg.get(INVITOR_CODE_CONFIGKEY, null);
    final String invitorSecret = (cfg == null) ? null : cfg.get(INVITOR_SECRET_CONFIGKEY, null);

    Runnable runnable = new SafeRunnable() {

        @Override
        public void safeRun() {
            T.REGISTRATION();
            try {

                if (CloudConstants.USE_XMPP_KICK_CHANNEL) {

                    final ConnectionConfiguration xmppConfig = new XMPPConfigurationFactory(cp,
                            mService.getNetworkConnectivityManager(), null)
                                    .getSafeXmppConnectionConfiguration(xmppServiceName);
                    final XMPPConnection xmppCon = new XMPPConnection(xmppConfig);

                    xmppCon.setLogger(new Logger() {
                        @Override
                        public void log(String message) {
                            L.d(message);
                        }
                    });
                    xmppCon.connect();
                    xmppCon.login(xmppAccount, xmppPassword);

                    final Thread t2 = new Thread(new SafeRunnable() {
                        @Override
                        protected void safeRun() throws Exception {
                            L.d("REG Before disconnect (on separate thread) - xmpp-" + xmppCon.hashCode());
                            xmppCon.disconnect();
                            L.d("REG After disconnect (on separate thread) - xmpp-" + xmppCon.hashCode());
                        }
                    });
                    t2.setDaemon(true);
                    t2.start();

                }

                postFinishRegistration(info.mCredentials.getUsername(), info.mCredentials.getPassword(),
                        invitorCode, invitorSecret);

                mUIHandler.post(new SafeRunnable(pausable) {

                    @Override
                    protected void safeRun() throws Exception {
                        T.UI();
                        mWiz.setCredentials(info.mCredentials);

                        if (CloudConstants.USE_GCM_KICK_CHANNEL && !"".equals(mGCMRegistrationId)) {
                            GoogleServicesUtils.saveGCMRegistrationId(mService, mGCMRegistrationId);
                        }

                        mService.setCredentials(mWiz.getCredentials());
                        mService.setRegisteredInConfig(true);

                        final Intent launchServiceIntent = new Intent(RegistrationActivity2.this,
                                MainService.class);
                        launchServiceIntent.putExtra(MainService.START_INTENT_JUST_REGISTERED, true);
                        launchServiceIntent.putExtra(MainService.START_INTENT_MY_EMAIL, mWiz.getEmail());
                        RegistrationActivity2.this.startService(launchServiceIntent);
                        stopRegistrationService();
                        pd.dismiss();

                        mWiz.finish(); // finish
                    }
                });

            } catch (Exception e) {
                L.d("Exception while trying to end the registration process", e);
                mUIHandler.post(new SafeRunnable(pausable) {

                    @Override
                    protected void safeRun() throws Exception {
                        T.UI();
                        tryConnect(pd, attempt + 1, statusMessage, info);
                    }
                });
            }
        }
    };
    if (attempt == 1) {
        mWorkerHandler.post(runnable);
    } else {
        mWorkerHandler.postDelayed(runnable, XMPP_CHECK_DELAY_MILLIS);
    }
}

From source file:org.nebulaframework.ui.swing.cluster.ClusterMainUI.java

/**
 * Updates UI and displays the Cluster Information.
 *//*from  w w  w .  ja v  a 2 s.c om*/
private void showClusterInfo() {
    ClusterManager mgr = ClusterManager.getInstance();

    // ClusterID
    final JLabel clusterId = getUIElement("general.stats.clusterid");
    clusterId.setText(mgr.getClusterId().toString());

    // HostInfo
    JLabel hostInfo = getUIElement("general.stats.hostinfo");
    hostInfo.setText(mgr.getClusterInfo().getHostInfo());

    // Protocols
    JLabel protocols = getUIElement("general.stats.protocols");
    protocols.setText(mgr.getClusterInfo().getProtocolInfo());

    // Uptime Initial Value
    JLabel upTime = getUIElement("general.stats.uptime");
    upTime.setText("");

    // Peer Clusters
    final JLabel clusters = getUIElement("general.stats.peerclusters");
    clusters.setText("0");

    // Peer Clusters Update Hook
    ServiceEventsSupport.addServiceHook(new ServiceHookCallback() {
        public void onServiceEvent(ServiceMessage message) {

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        int peers = ClusterManager.getInstance().getPeerService().getPeerCount();
                        clusters.setText(String.valueOf(peers));
                    } catch (Exception e) {
                        log.warn("[UI] Exception while accessing peer information", e);
                    }
                }
            });
        }
    }, ServiceMessageType.PEER_CONNECTION, ServiceMessageType.PEER_DISCONNECTION);

    // Local Nodes
    final JLabel nodes = getUIElement("general.stats.nodes");
    nodes.setText(String.valueOf(ClusterManager.getInstance().getClusterRegistrationService().getNodeCount()));

    // Local Nodes Update Hook
    ServiceEventsSupport.addServiceHook(new ServiceHookCallback() {
        public void onServiceEvent(ServiceMessage message) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    int count = ClusterManager.getInstance().getClusterRegistrationService().getNodeCount();
                    nodes.setText(String.valueOf(count));
                }
            });
        }
    }, ServiceMessageType.NODE_REGISTERED, ServiceMessageType.NODE_UNREGISTERED);

    // Completed Jobs
    final JLabel jobsdone = getUIElement("general.stats.jobsdone");
    jobsdone.setText("0");

    // Completed Jobs Update Hook
    ServiceEventsSupport.addServiceHook(new ServiceHookCallback() {
        public void onServiceEvent(ServiceMessage message) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    int count = ClusterManager.getInstance().getJobService().getFinishedJobCount();
                    jobsdone.setText(String.valueOf(count));
                }
            });
        }
    }, ServiceMessageType.JOB_END, ServiceMessageType.JOB_CANCEL);

    // Active Jobs
    final JLabel activejobs = getUIElement("general.stats.activejobs");
    activejobs.setText(String.valueOf(ClusterManager.getInstance().getJobService().getActiveJobCount()));

    // Active Jobs Update Hook
    ServiceEventsSupport.addServiceHook(new ServiceHookCallback() {
        public void onServiceEvent(ServiceMessage message) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    int count = ClusterManager.getInstance().getJobService().getActiveJobCount();
                    activejobs.setText(String.valueOf(count));
                }
            });
        }
    }, ServiceMessageType.JOB_START, ServiceMessageType.JOB_CANCEL, ServiceMessageType.JOB_END);

    // Start Up time Thread
    Thread t = new Thread(new Runnable() {
        public void run() {

            long start = System.currentTimeMillis();

            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    log.warn("Interrupted Exception in Up Time Thread", e);
                }

                final String uptime = TimeUtils.timeDifference(start);

                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        JLabel upTime = getUIElement("general.stats.uptime");
                        upTime.setText(uptime);
                    }

                });
            }

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