Example usage for java.lang Thread setPriority

List of usage examples for java.lang Thread setPriority

Introduction

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

Prototype

public final void setPriority(int newPriority) 

Source Link

Document

Changes the priority of this thread.

Usage

From source file:edu.brown.hstore.HStoreSite.java

/**
 * Initializes all the pieces that we need to start this HStore site up
 * This should only be called by our run() method
 *///  ww  w. j ava2  s  .  c  om
protected HStoreSite init() {
    if (debug.val)
        LOG.debug("Initializing HStoreSite " + this.getSiteName());
    this.hstore_coordinator = this.initHStoreCoordinator();

    // First we need to tell the HStoreCoordinator to start-up and initialize its connections
    if (debug.val)
        LOG.debug("Starting HStoreCoordinator for " + this.getSiteName());
    this.hstore_coordinator.start();

    ThreadGroup auxGroup = this.threadManager.getThreadGroup(ThreadGroupType.AUXILIARY);

    // Start TransactionQueueManager
    Thread t = new Thread(auxGroup, this.txnQueueManager);
    t.setDaemon(true);
    t.setUncaughtExceptionHandler(this.exceptionHandler);
    t.start();

    // Start VoltNetwork
    t = new Thread(this.voltNetwork);
    t.setName(HStoreThreadManager.getThreadName(this, HStoreConstants.THREAD_NAME_VOLTNETWORK));
    t.setDaemon(true);
    t.setUncaughtExceptionHandler(this.exceptionHandler);
    t.start();

    // Start CommandLogWriter
    t = new Thread(auxGroup, this.commandLogger);
    t.setDaemon(true);
    t.setUncaughtExceptionHandler(this.exceptionHandler);
    t.start();

    // Start AntiCacheManager Queue Processor
    if (this.anticacheManager != null && this.anticacheManager.getEvictableTables().isEmpty() == false) {
        t = new Thread(auxGroup, this.anticacheManager);
        t.setDaemon(true);
        t.setUncaughtExceptionHandler(this.exceptionHandler);
        t.start();
    }

    // TransactionPreProcessors
    if (this.preProcessors != null) {
        for (TransactionPreProcessor tpp : this.preProcessors) {
            t = new Thread(this.threadManager.getThreadGroup(ThreadGroupType.PROCESSING), tpp);
            t.setDaemon(true);
            t.setUncaughtExceptionHandler(this.exceptionHandler);
            t.start();
        } // FOR
    }
    // TransactionPostProcessors
    if (this.postProcessors != null) {
        for (TransactionPostProcessor tpp : this.postProcessors) {
            t = new Thread(this.threadManager.getThreadGroup(ThreadGroupType.PROCESSING), tpp);
            t.setDaemon(true);
            t.setUncaughtExceptionHandler(this.exceptionHandler);
            t.start();
        } // FOR
    }

    // Then we need to start all of the PartitionExecutor in threads
    if (debug.val)
        LOG.debug(String.format("Starting PartitionExecutor threads for %s partitions on %s",
                this.local_partitions.size(), this.getSiteName()));
    for (int partition : this.local_partitions.values()) {
        PartitionExecutor executor = this.getPartitionExecutor(partition);
        // executor.initHStoreSite(this);

        t = new Thread(this.threadManager.getThreadGroup(ThreadGroupType.EXECUTION), executor);
        t.setDaemon(true);
        t.setPriority(Thread.MAX_PRIORITY); // Probably does nothing...
        t.setUncaughtExceptionHandler(this.exceptionHandler);
        this.executor_threads[partition] = t;
        t.start();
    } // FOR

    // Start Transaction Cleaners
    int i = 0;
    for (TransactionCleaner cleaner : this.txnCleaners) {
        String name = String.format("%s-%02d",
                HStoreThreadManager.getThreadName(this, HStoreConstants.THREAD_NAME_TXNCLEANER), i);
        t = new Thread(this.threadManager.getThreadGroup(ThreadGroupType.CLEANER), cleaner);
        t.setName(name);
        t.setDaemon(true);
        t.setUncaughtExceptionHandler(this.exceptionHandler);
        t.start();
        i += 1;
    } // FOR

    this.initPeriodicWorks();

    // Transaction Profile CSV Dumper
    if (hstore_conf.site.txn_profiling && hstore_conf.site.txn_profiling_dump) {
        File csvFile = new File(hstore_conf.global.log_dir + File.separator + this.getSiteName().toLowerCase()
                + "-profiler.csv");
        this.txn_profiler_dumper = new TransactionProfilerDumper(csvFile);
        LOG.info(String.format("Transaction profile data will be written to '%s'", csvFile));
    }

    // Add in our shutdown hook
    // Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook()));

    return (this);
}

From source file:com.klinker.android.twitter.services.TalonPullNotificationService.java

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

    if (TalonPullNotificationService.isRunning) {
        stopSelf();//from w  w w.  j a  v  a2s  . c  o  m
        return;
    }

    TalonPullNotificationService.isRunning = true;

    settings = AppSettings.getInstance(this);

    mCache = App.getInstance(this).getBitmapCache();

    sharedPreferences = getSharedPreferences("com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    pullUnread = sharedPreferences.getInt("pull_unread", 0);

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Intent stop = new Intent(this, StopPull.class);
    PendingIntent stopPending = PendingIntent.getService(this, 0, stop, 0);

    Intent popup = new Intent(this, RedirectToPopup.class);
    popup.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    popup.putExtra("from_notification", true);
    PendingIntent popupPending = PendingIntent.getActivity(this, 0, popup, 0);

    Intent compose = new Intent(this, WidgetCompose.class);
    popup.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent composePending = PendingIntent.getActivity(this, 0, compose, 0);

    String text;

    int count = 0;

    if (sharedPreferences.getBoolean("is_logged_in_1", false)) {
        count++;
    }
    if (sharedPreferences.getBoolean("is_logged_in_2", false)) {
        count++;
    }

    boolean multAcc = false;
    if (count == 2) {
        multAcc = true;
    }

    if (settings.liveStreaming && settings.timelineNot) {
        text = getResources().getString(R.string.new_tweets_upper) + ": " + pullUnread;
    } else {
        text = getResources().getString(R.string.listening_for_mentions) + "...";
    }

    mBuilder = new NotificationCompat.Builder(this).setSmallIcon(android.R.color.transparent)
            .setContentTitle(getResources().getString(R.string.talon_pull)
                    + (multAcc ? " - @" + settings.myScreenName : ""))
            .setContentText(text).setOngoing(true)
            .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_stat_icon));

    if (getApplicationContext().getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.addAction(R.drawable.ic_cancel_dark,
                getApplicationContext().getResources().getString(R.string.stop), stopPending);
        mBuilder.addAction(R.drawable.ic_popup, getResources().getString(R.string.popup), popupPending);
        mBuilder.addAction(R.drawable.ic_send_dark, getResources().getString(R.string.tweet), composePending);
    }

    try {
        mBuilder.setWhen(0);
    } catch (Exception e) {
    }

    mBuilder.setContentIntent(pendingIntent);

    // priority flag is only available on api level 16 and above
    if (getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.setPriority(Notification.PRIORITY_MIN);
    }

    mContext = getApplicationContext();

    IntentFilter filter = new IntentFilter();
    filter.addAction("com.klinker.android.twitter.STOP_PUSH");
    registerReceiver(stopPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.klinker.android.twitter.START_PUSH");
    registerReceiver(startPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.klinker.android.twitter.STOP_PUSH_SERVICE");
    registerReceiver(stopService, filter);

    if (settings.liveStreaming && settings.timelineNot) {
        filter = new IntentFilter();
        filter.addAction("com.klinker.android.twitter.UPDATE_NOTIF");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.klinker.android.twitter.NEW_TWEET");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.klinker.android.twitter.CLEAR_PULL_UNREAD");
        registerReceiver(clearPullUnread, filter);
    }

    Thread start = new Thread(new Runnable() {
        @Override
        public void run() {
            // get the ids of everyone you follow
            try {
                Log.v("getting_ids", "started getting ids, mine: " + settings.myId);
                Twitter twitter = Utils.getTwitter(mContext, settings);
                long currCursor = -1;
                IDs idObject;
                int rep = 0;

                do {
                    idObject = twitter.getFriendsIDs(settings.myId, currCursor);

                    long[] lIds = idObject.getIDs();
                    ids = new ArrayList<Long>();
                    for (int i = 0; i < lIds.length; i++) {
                        ids.add(lIds[i]);
                    }

                    rep++;
                } while ((currCursor = idObject.getNextCursor()) != 0 && rep < 3);

                ids.add(settings.myId);

                idsLoaded = true;

                startForeground(FOREGROUND_SERVICE_ID, mBuilder.build());

                mContext.sendBroadcast(new Intent("com.klinker.android.twitter.START_PUSH"));
            } catch (Exception e) {
                e.printStackTrace();
                TalonPullNotificationService.isRunning = false;

                pullUnread = 0;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TalonPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TalonPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                stopSelf();
            } catch (OutOfMemoryError e) {
                TalonPullNotificationService.isRunning = false;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TalonPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TalonPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                pullUnread = 0;

                stopSelf();
            }

        }
    });

    start.setPriority(Thread.MAX_PRIORITY - 1);
    start.start();

}

From source file:com.daiv.android.twitter.services.TestPullNotificationService.java

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

    if (TestPullNotificationService.isRunning) {
        stopSelf();//w w w  .j a va2 s .co m
        return;
    }

    TestPullNotificationService.isRunning = true;

    settings = AppSettings.getInstance(this);

    mCache = App.getInstance(this).getBitmapCache();

    sharedPreferences = getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    showNotification = sharedPreferences.getBoolean("show_pull_notification", true);
    pullUnread = sharedPreferences.getInt("pull_unread", 0);

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Intent stop = new Intent(this, StopPull.class);
    PendingIntent stopPending = PendingIntent.getService(this, 0, stop, 0);

    String text;

    int count = 0;

    if (sharedPreferences.getBoolean("is_logged_in_1", false)) {
        count++;
    }
    if (sharedPreferences.getBoolean("is_logged_in_2", false)) {
        count++;
    }

    boolean multAcc = false;
    if (count == 2) {
        multAcc = true;
    }

    if (settings.liveStreaming && settings.timelineNot) {
        text = getResources().getString(R.string.new_tweets_upper) + ": " + pullUnread;
    } else {
        text = getResources().getString(R.string.listening_for_mentions) + "...";
    }

    mBuilder = new NotificationCompat.Builder(this).setSmallIcon(android.R.color.transparent)
            .setContentTitle(getResources().getString(R.string.Test_pull)
                    + (multAcc ? " - @" + settings.myScreenName : ""))
            .setContentText(text).setOngoing(true)
            .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_stat_icon));

    if (getApplicationContext().getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.addAction(R.drawable.ic_cancel_dark,
                getApplicationContext().getResources().getString(R.string.stop), stopPending);
    }

    try {
        mBuilder.setWhen(0);
    } catch (Exception e) {
    }

    mBuilder.setContentIntent(pendingIntent);

    // priority flag is only available on api level 16 and above
    if (getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.setPriority(Notification.PRIORITY_MIN);
    }

    mContext = getApplicationContext();

    IntentFilter filter = new IntentFilter();
    filter.addAction("com.daiv.android.twitter.STOP_PUSH");
    registerReceiver(stopPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.daiv.android.twitter.START_PUSH");
    registerReceiver(startPush, filter);

    filter = new IntentFilter();
    filter.addAction("com.daiv.android.twitter.STOP_PUSH_SERVICE");
    registerReceiver(stopService, filter);

    if (settings.liveStreaming && settings.timelineNot) {
        filter = new IntentFilter();
        filter.addAction("com.daiv.android.twitter.UPDATE_NOTIF");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.daiv.android.twitter.NEW_TWEET");
        registerReceiver(updateNotification, filter);

        filter = new IntentFilter();
        filter.addAction("com.daiv.android.twitter.CLEAR_PULL_UNREAD");
        registerReceiver(clearPullUnread, filter);
    }

    Thread start = new Thread(new Runnable() {
        @Override
        public void run() {
            // get the ids of everyone you follow
            try {
                Log.v("getting_ids", "started getting ids, mine: " + settings.myId);
                Twitter twitter = Utils.getTwitter(mContext, settings);
                long currCursor = -1;
                IDs idObject;

                ids = new ArrayList<Long>();
                do {
                    idObject = twitter.getFriendsIDs(settings.myId, currCursor);

                    long[] lIds = idObject.getIDs();
                    for (int i = 0; i < lIds.length; i++) {
                        ids.add(lIds[i]);
                    }
                } while ((currCursor = idObject.getNextCursor()) != 0);
                ids.add(settings.myId);

                currCursor = -1;
                blockedIds = new ArrayList<Long>();
                do {
                    idObject = twitter.getBlocksIDs(currCursor);

                    long[] lIds = idObject.getIDs();
                    for (int i = 0; i < lIds.length; i++) {
                        blockedIds.add(lIds[i]);
                    }
                } while ((currCursor = idObject.getNextCursor()) != 0);

                idsLoaded = true;

                if (showNotification)
                    startForeground(FOREGROUND_SERVICE_ID, mBuilder.build());

                mContext.sendBroadcast(new Intent("com.daiv.android.twitter.START_PUSH"));
            } catch (Exception e) {
                e.printStackTrace();
                TestPullNotificationService.isRunning = false;

                pullUnread = 0;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TestPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TestPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                stopSelf();
            } catch (OutOfMemoryError e) {
                TestPullNotificationService.isRunning = false;

                Thread stop = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        TestPullNotificationService.shuttingDown = true;
                        try {
                            //pushStream.removeListener(userStream);
                        } catch (Exception x) {

                        }
                        try {
                            pushStream.cleanUp();
                            pushStream.shutdown();
                            Log.v("twitter_stream_push", "stopping push notifications");
                        } catch (Exception e) {
                            // it isn't running
                            e.printStackTrace();
                            // try twice to shut it down i guess
                            try {
                                Thread.sleep(2000);
                                pushStream.cleanUp();
                                pushStream.shutdown();
                                Log.v("twitter_stream_push", "stopping push notifications");
                            } catch (Exception x) {
                                // it isn't running
                                x.printStackTrace();
                            }
                        }

                        TestPullNotificationService.shuttingDown = false;
                    }
                });

                stop.setPriority(Thread.MAX_PRIORITY);
                stop.start();

                pullUnread = 0;

                stopSelf();
            }

        }
    });

    start.setPriority(Thread.MAX_PRIORITY - 1);
    start.start();

}

From source file:org.proteomecommons.tranche.modules.advancedsearch.AdvancedSearchPanel.java

/**
 * Performs the search, updates the GUI//from w  w  w  .j  av a  2s . c o  m
 */
public void search() {

    Thread t = new Thread() {

        public void run() {
            // For HTTP response
            BufferedReader reader = null;
            final IndeterminateProgressBar progress = new IndeterminateProgressBar("Connecting to database...");
            try {
                // Clear out all ephemeral components
                resetSearchView();

                progress.setDisposeAllowable(true);
                progress.setLocationRelativeTo(main);

                Thread pthread = new Thread() {

                    public void run() {
                        progress.start();
                    }
                };
                SwingUtilities.invokeLater(pthread);

                // Make the query string
                StringBuffer query = new StringBuffer();

                // "Any" refers to default query parameter
                String ionSelection = ionSourceDropDown.getSelectedItem().toString();
                if (ionSelection.equalsIgnoreCase("any")) {
                    ionSelection = "";
                }
                String journalSelection = journalDropDown.getSelectedItem().toString();
                if (journalSelection.equalsIgnoreCase("any")) {
                    journalSelection = "";
                }
                String instrumentSelection = instrumentDropDown.getSelectedItem().toString();
                if (instrumentSelection.equalsIgnoreCase("any")) {
                    instrumentSelection = "";
                }
                query.append("q=" + GUIUtil.createURLEncodedString(keywordText.getText()));
                query.append("&i=" + GUIUtil.createURLEncodedString(ionSelection));
                query.append("&j=" + GUIUtil.createURLEncodedString(journalSelection));
                query.append("&n=" + GUIUtil.createURLEncodedString(researcherText.getText()));
                query.append("&o=" + GUIUtil.createURLEncodedString(organismText.getText()));
                query.append("&m=" + GUIUtil.createURLEncodedString(instrumentSelection));
                if (onlineResultsOnlyBox.isSelected()) {
                    query.append("&t=on"); // HTTP request for results
                }
                HttpClient c = new HttpClient();
                GetMethod pm = new GetMethod(
                        "http://www.proteomecommons.org/data/tranche-advanced-search.jsp?" + query.toString());

                // execute the method
                if (c.executeMethod(pm) != 200) {
                    throw new Exception("Unsuccessfully registered hash.");
                }

                // Get response
                reader = new BufferedReader(new InputStreamReader(pm.getResponseBodyAsStream()));

                String line = null;
                // Buffer each entry separately
                StringBuffer buffer = new StringBuffer();

                while ((line = reader.readLine()) != null) {

                    printTracer("Reading next response line: " + line);

                    // Trim the line (to be safe)
                    line = line.trim() + " ";

                    // Skip blank lines
                    if (line.trim().equals("")) {
                        continue;
                    }
                    // If new entry
                    if (line.startsWith("TITLE")) {
                        // Add previous buffer to entry if not empty
                        if (!buffer.toString().trim().equals("")) {
                            // Add component
                            addEphemeralComponent(new SearchResult(buffer));
                            buffer = new StringBuffer();
                        }

                        buffer.append(line);
                    } else {
                        // Building up subsequent lines
                        buffer.append(line);
                    }
                }

                progress.stop();
                // If no results, notify user
                if (ephemeralComponents.size() == 0) {
                    JOptionPane.showMessageDialog(main, "You query didn't yield any matches.", "No results",
                            JOptionPane.INFORMATION_MESSAGE);
                } else {

                    String title = "Search results";
                    String message = "A total of ";

                    if (ephemeralComponents.size() == 1) {
                        message += "1 result was ";
                    } else {
                        message += (ephemeralComponents.size() + " results were ");
                    }
                    message += "found.";

                    JOptionPane.showMessageDialog(main, message, title, JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception ex) {
                progress.stop();
                ErrorFrame ef = new ErrorFrame();
                ef.show(ex, main);
            } finally {
                IOUtil.safeClose(reader);

                Thread updateThread = new Thread() {

                    public void run() {
                        updateUI();
                        // Request focus (scroll bar to top)
                        keywordText.select(0, 1);
                        keywordText.requestFocus();
                    }
                };
                SwingUtilities.invokeLater(updateThread);
            }

        } // run
    };
    t.setDaemon(true);
    t.setPriority(Thread.MIN_PRIORITY);
    t.start();
}

From source file:com.sentaroh.android.SMBSync2.ActivityMain.java

private void houseKeepLocalFileLastModList() {
    NotifyEvent ntfy = new NotifyEvent(mContext);
    ntfy.setListener(new NotifyEventListener() {
        @Override// w  w  w .j  a va  2s  .com
        public void positiveResponse(Context c, Object[] o) {
            mTcHousekeep = new ThreadCtrl();
            Thread th2 = new Thread() {
                @Override
                public void run() {
                    util.addLogMsg("I", mContext.getString(R.string.msgs_maintenance_last_mod_list_start_msg));
                    if (!mGp.syncThreadActive) {
                        mGp.syncThreadEnabled = false;
                        mUiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                housekeepThreadStarted();
                            }
                        });
                        ArrayList<FileLastModifiedEntryItem> mCurrLastModifiedList = new ArrayList<FileLastModifiedEntryItem>();
                        ArrayList<FileLastModifiedEntryItem> mNewLastModifiedList = new ArrayList<FileLastModifiedEntryItem>();
                        ArrayList<FileLastModifiedEntryItem> del_list = new ArrayList<FileLastModifiedEntryItem>();
                        LocalFileLastModified.loadLastModifiedList(mCurrLastModifiedList, mNewLastModifiedList);
                        if (mCurrLastModifiedList.size() > 0) {
                            for (FileLastModifiedEntryItem li : mCurrLastModifiedList) {
                                if (!mTcHousekeep.isEnabled())
                                    break;
                                if (li.getFullFilePath().startsWith(mGp.internalRootDirectory)) {
                                    File lf = new File(li.getFullFilePath());
                                    if (!lf.exists()) {
                                        del_list.add(li);
                                        util.addDebugMsg(1, "I",
                                                "Entery was deleted, fp=" + li.getFullFilePath());
                                    }
                                }
                            }
                            for (FileLastModifiedEntryItem li : del_list) {
                                if (!mTcHousekeep.isEnabled())
                                    break;
                                mCurrLastModifiedList.remove(li);
                            }
                        }
                        if (mTcHousekeep.isEnabled()) {
                            if (del_list.size() > 0)
                                LocalFileLastModified.saveLastModifiedList(mCurrLastModifiedList,
                                        mNewLastModifiedList);
                        }

                        String msg_txt = "";
                        if (mTcHousekeep.isEnabled())
                            msg_txt = mContext.getString(R.string.msgs_maintenance_last_mod_list_end_msg);
                        else
                            msg_txt = mContext.getString(R.string.msgs_maintenance_last_mod_list_cancel_msg);
                        util.addLogMsg("I", msg_txt);
                        commonDlg.showCommonDialog(false, "W", msg_txt, "", null);
                        mGp.uiHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                housekeepThreadEnded();
                                mGp.syncThreadEnabled = true;
                            }
                        });

                    } else {
                        util.addLogMsg("I",
                                mContext.getString(R.string.msgs_maintenance_last_mod_list_can_not_start_msg));
                        commonDlg.showCommonDialog(false, "W",
                                mContext.getString(R.string.msgs_maintenance_last_mod_list_can_not_start_msg),
                                "", null);
                    }
                }
            };
            th2.setPriority(Thread.MAX_PRIORITY);
            th2.start();
        }

        @Override
        public void negativeResponse(Context c, Object[] o) {
        }
    });
    if (!mGp.syncThreadActive) {
        commonDlg.showCommonDialog(true, "W",
                mContext.getString(R.string.msgs_maintenance_last_mod_list_confirm_start_msg), "", ntfy);
    } else {
        util.addLogMsg("I", mContext.getString(R.string.msgs_maintenance_last_mod_list_can_not_start_msg));
        commonDlg.showCommonDialog(false, "W",
                mContext.getString(R.string.msgs_maintenance_last_mod_list_can_not_start_msg), "", null);
    }
}

From source file:carnero.cgeo.original.libs.Base.java

public void storeCache(App app, Activity activity, Cache cache, String geocode, int listId, Handler handler) {
    try {//from www  . j  a  v  a  2 s  . c o  m
        // cache details
        if (cache != null) {
            final HashMap<String, String> params = new HashMap<String, String>();
            params.put("geocode", cache.geocode);
            final Long searchId = searchByGeocode(params, listId, false);
            cache = app.getCache(searchId);
        } else if (geocode != null) {
            final HashMap<String, String> params = new HashMap<String, String>();
            params.put("geocode", geocode);
            final Long searchId = searchByGeocode(params, listId, false);
            cache = app.getCache(searchId);
        }

        if (cache == null) {
            if (handler != null) {
                handler.sendMessage(new Message());
            }

            return;
        }

        final HtmlImg imgGetter = new HtmlImg(activity, settings, cache.geocode, false, listId, true);

        // store images from description
        if (cache.description != null) {
            Html.fromHtml(cache.description, imgGetter, null);
        }

        // store spoilers
        if (cache.spoilers != null && cache.spoilers.isEmpty() == false) {
            for (Spoiler oneSpoiler : cache.spoilers) {
                imgGetter.getDrawable(oneSpoiler.url);
            }
        }

        // store map previews
        if (settings.storeOfflineMaps == 1 && cache.latitude != null && cache.longitude != null) {
            final String latlonMap = String.format((Locale) null, "%.6f", cache.latitude) + ","
                    + String.format((Locale) null, "%.6f", cache.longitude);
            final Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay();
            final int maxWidth = display.getWidth() - 25;
            final int maxHeight = display.getHeight() - 25;
            int edge = 0;
            if (maxWidth > maxHeight) {
                edge = maxWidth;
            } else {
                edge = maxHeight;
            }

            String type = "mystery";
            if (cache.found == true) {
                type = cache.type + "_found";
            } else if (cache.disabled == true) {
                type = cache.type + "_disabled";
            } else {
                type = cache.type;
            }

            final String markerUrl = urlencode_rfc3986(
                    "http://cgeo.carnero.cc/_markers/marker_cache_" + type + ".png");
            final StringBuilder waypoints = new StringBuilder();
            if (cache.waypoints != null && cache.waypoints.size() > 0) {
                for (Waypoint waypoint : cache.waypoints) {
                    if (waypoint.latitude == null && waypoint.longitude == null) {
                        continue;
                    }

                    waypoints.append("&markers=icon%3Ahttp://cgeo.carnero.cc/_markers/marker_waypoint_");
                    waypoints.append(waypoint.type);
                    waypoints.append(".png%7C");
                    waypoints.append(String.format((Locale) null, "%.6f", waypoint.latitude));
                    waypoints.append(",");
                    waypoints.append(String.format((Locale) null, "%.6f", waypoint.longitude));
                }
            }

            // download map images in separate background thread for higher performance
            final String code = cache.geocode;
            final int finalEdge = edge;
            Thread staticMapsThread = new Thread("getting static map") {
                @Override
                public void run() {
                    MapImg mapGetter = new MapImg(settings, code);

                    mapGetter.getDrawable(
                            "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=20&size="
                                    + finalEdge + "x" + finalEdge + "&maptype=satellite&markers=icon%3A"
                                    + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false",
                            1);
                    mapGetter.getDrawable(
                            "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=18&size="
                                    + finalEdge + "x" + finalEdge + "&maptype=satellite&markers=icon%3A"
                                    + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false",
                            2);
                    mapGetter.getDrawable(
                            "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=16&size="
                                    + finalEdge + "x" + finalEdge + "&maptype=roadmap&markers=icon%3A"
                                    + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false",
                            3);
                    mapGetter.getDrawable(
                            "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=14&size="
                                    + finalEdge + "x" + finalEdge + "&maptype=roadmap&markers=icon%3A"
                                    + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false",
                            4);
                    mapGetter.getDrawable(
                            "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=11&size="
                                    + finalEdge + "x" + finalEdge + "&maptype=roadmap&markers=icon%3A"
                                    + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false",
                            5);
                }
            };
            staticMapsThread.setPriority(Thread.MIN_PRIORITY);
            staticMapsThread.start();
        }

        app.markStored(cache.geocode, listId);
        app.removeCacheFromCache(cache.geocode);

        if (handler != null) {
            handler.sendMessage(new Message());
        }
    } catch (Exception e) {
        Log.e(Settings.tag, "cgBase.storeCache: " + e.toString());
    }
}

From source file:carnero.cgeo.cgBase.java

public void storeCache(cgeoapplication app, Activity activity, cgCache cache, String geocode, int listId,
        Handler handler) {/*from  ww w.  ja v a 2  s  .c  o  m*/
    try {
        // cache details
        if (cache != null) {
            final HashMap<String, String> params = new HashMap<String, String>();
            params.put("geocode", cache.geocode);
            final Long searchId = searchByGeocode(params, listId, false);
            cache = app.getCache(searchId);
        } else if (geocode != null) {
            final HashMap<String, String> params = new HashMap<String, String>();
            params.put("geocode", geocode);
            final Long searchId = searchByGeocode(params, listId, false);
            cache = app.getCache(searchId);
        }

        if (cache == null) {
            if (handler != null) {
                handler.sendMessage(new Message());
            }

            return;
        }

        final cgHtmlImg imgGetter = new cgHtmlImg(activity, settings, cache.geocode, false, listId, true);

        // store images from description
        if (cache.description != null) {
            Html.fromHtml(cache.description, imgGetter, null);
        }

        // store spoilers
        if (cache.spoilers != null && cache.spoilers.isEmpty() == false) {
            for (cgSpoiler oneSpoiler : cache.spoilers) {
                imgGetter.getDrawable(oneSpoiler.url);
            }
        }

        // store map previews
        if (settings.storeOfflineMaps == 1 && cache.latitude != null && cache.longitude != null) {
            final String latlonMap = String.format((Locale) null, "%.6f", cache.latitude) + ","
                    + String.format((Locale) null, "%.6f", cache.longitude);
            final Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay();
            final int maxWidth = display.getWidth() - 25;
            final int maxHeight = display.getHeight() - 25;
            int edge = 0;
            if (maxWidth > maxHeight) {
                edge = maxWidth;
            } else {
                edge = maxHeight;
            }

            String type = "mystery";
            if (cache.found == true) {
                type = cache.type + "_found";
            } else if (cache.disabled == true) {
                type = cache.type + "_disabled";
            } else {
                type = cache.type;
            }

            final String markerUrl = urlencode_rfc3986(
                    "http://cgeo.carnero.cc/_markers/marker_cache_" + type + ".png");
            final StringBuilder waypoints = new StringBuilder();
            if (cache.waypoints != null && cache.waypoints.size() > 0) {
                for (cgWaypoint waypoint : cache.waypoints) {
                    if (waypoint.latitude == null && waypoint.longitude == null) {
                        continue;
                    }

                    waypoints.append("&markers=icon%3Ahttp://cgeo.carnero.cc/_markers/marker_waypoint_");
                    waypoints.append(waypoint.type);
                    waypoints.append(".png%7C");
                    waypoints.append(String.format((Locale) null, "%.6f", waypoint.latitude));
                    waypoints.append(",");
                    waypoints.append(String.format((Locale) null, "%.6f", waypoint.longitude));
                }
            }

            // download map images in separate background thread for higher performance
            final String code = cache.geocode;
            final int finalEdge = edge;
            Thread staticMapsThread = new Thread("getting static map") {
                @Override
                public void run() {
                    cgMapImg mapGetter = new cgMapImg(settings, code);

                    mapGetter.getDrawable(
                            "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=20&size="
                                    + finalEdge + "x" + finalEdge + "&maptype=satellite&markers=icon%3A"
                                    + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false",
                            1);
                    mapGetter.getDrawable(
                            "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=18&size="
                                    + finalEdge + "x" + finalEdge + "&maptype=satellite&markers=icon%3A"
                                    + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false",
                            2);
                    mapGetter.getDrawable(
                            "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=16&size="
                                    + finalEdge + "x" + finalEdge + "&maptype=roadmap&markers=icon%3A"
                                    + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false",
                            3);
                    mapGetter.getDrawable(
                            "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=14&size="
                                    + finalEdge + "x" + finalEdge + "&maptype=roadmap&markers=icon%3A"
                                    + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false",
                            4);
                    mapGetter.getDrawable(
                            "http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=11&size="
                                    + finalEdge + "x" + finalEdge + "&maptype=roadmap&markers=icon%3A"
                                    + markerUrl + "%7C" + latlonMap + waypoints.toString() + "&sensor=false",
                            5);
                }
            };
            staticMapsThread.setPriority(Thread.MIN_PRIORITY);
            staticMapsThread.start();
        }

        app.markStored(cache.geocode, listId);
        app.removeCacheFromCache(cache.geocode);

        if (handler != null) {
            handler.sendMessage(new Message());
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.storeCache: " + e.toString());
    }
}

From source file:com.juick.android.MessagesFragment.java

private void init(final boolean moveToTop) {
    if (implicitlyCreated)
        return;//from  w  ww .  j  a  v  a2  s.  c  o m

    parent.imagePreviewHelper = listAdapter.imagePreviewHelper = new ImagePreviewHelper(
            (ViewGroup) getView().findViewById(R.id.imagepreview_container), parent);

    final MessageListBackingData savedMainList = JuickAdvancedApplication.instance.getSavedList(getActivity());
    final ListView lv = getListView();
    boolean canUseMainList = getActivity() instanceof MainActivity; //
    if (savedMainList != null && canUseMainList) {
        messagesSource = savedMainList.messagesSource;
        initListWithMessages(savedMainList.messages);
        int selectItem = 0;
        ListAdapter wrappedAdapter = lv.getAdapter();
        for (int i = 0; i < wrappedAdapter.getCount(); i++) {
            Object ai = wrappedAdapter.getItem(i);
            if (ai != null && ai instanceof JuickMessage) {
                if (((JuickMessage) ai).getMID().equals(savedMainList.topMessageId)) {
                    selectItem = i;
                }
            }
        }
        lv.setSelectionFromTop(selectItem, savedMainList.topMessageScrollPos);
        JuickAdvancedApplication.instance.setSavedList(null, false);
    } else {
        final MessagesLoadNotification messagesLoadNotification = new MessagesLoadNotification(getActivity(),
                handler);
        Thread thr = new Thread("Download messages (init)") {

            public void run() {
                final MessagesLoadNotification notification = messagesLoadNotification;
                final Utils.Function<Void, RetainedData> then = new Utils.Function<Void, RetainedData>() {
                    @Override
                    public Void apply(final RetainedData mespos) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                notification.statusText.setText("Filter and format..");
                            }
                        });
                        Log.w("com.juick.advanced", "getFirst: before filter");
                        final ArrayList<JuickMessage> messages = filterMessages(mespos.messages);
                        Log.w("com.juick.advanced", "getFirst: after filter");
                        Boolean ownView = null;
                        if (!JuickMessagesAdapter.dontKeepParsed(parent)) {
                            for (JuickMessage juickMessage : messages) {
                                if (ownView == null) {
                                    MicroBlog blog = MainActivity.microBlogs
                                            .get(juickMessage.getMID().getMicroBlogCode());
                                    ownView = blog instanceof OwnRenderItems;
                                }
                                if (!ownView) {
                                    juickMessage.parsedText = JuickMessagesAdapter.formatMessageText(parent,
                                            juickMessage, false);
                                }
                            }
                        }
                        final Parcelable listPosition = mespos.viewState;
                        if (isAdded()) {
                            if (messages.size() == 0) {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (notification.lastError == null) {
                                            notification.statusText
                                                    .setText(parent.getString(R.string.EmptyList));
                                        } else {
                                            notification.statusText.setText(
                                                    "Error obtaining messages: " + notification.lastError);

                                        }
                                        notification.progressBar.setVisibility(View.GONE);
                                    }
                                });
                            }
                            final Activity activity = getActivity();
                            if (activity != null) {
                                final Parcelable finalListPosition = listPosition;
                                activity.runOnUiThread(new Runnable() {

                                    public void run() {
                                        try {
                                            if (isAdded()) {
                                                lastPrepareMessages(messages, new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        if (!hasListView()) {
                                                            handler.postDelayed(this, 300);
                                                            return;
                                                        }
                                                        initListWithMessages(messages);
                                                        if (moveToTop) {
                                                            lv.setSelection(0);
                                                        } else {
                                                            if (finalListPosition != null) {
                                                                lv.onRestoreInstanceState(finalListPosition);
                                                            } else {
                                                                //setSelection(messagesSource.supportsBackwardRefresh() ? 1 : 0);
                                                                setSelection(0);
                                                            }
                                                        }
                                                        Log.w("com.juick.advanced", "getFirst: end.");
                                                        handler.postDelayed(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                onListLoaded();
                                                            }
                                                        }, 10);
                                                    }
                                                });
                                            }
                                        } catch (IllegalStateException e) {
                                            Toast.makeText(activity, e.toString(), Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                            }
                        } else {
                            Log.w("com.juick.advanced", "getFirst: not added!");
                        }
                        return null;
                    }
                };
                if (getActivity() != null)
                    messagesSource.setContext(getActivity());
                if (restoreData == null) {
                    messagesSource.getFirst(notification, new Utils.Function<Void, ArrayList<JuickMessage>>() {
                        @Override
                        public Void apply(ArrayList<JuickMessage> juickMessages) {
                            return then.apply(new RetainedData(juickMessages, null));
                        }
                    });
                } else {
                    then.apply((RetainedData) restoreData);
                    restoreData = null;
                }
            }
        };
        thr.setPriority(Thread.MIN_PRIORITY);
        thr.start();
    }
}

From source file:ECallCenter21.java

private void phonesPoolTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_phonesPoolTableMouseClicked
    if (evt.getClickCount() == 2) {
        myCoordinate = new Coordinate(phonesPoolTable.getSelectedRow(), phonesPoolTable.getSelectedColumn());
        final int selectedSoftPhoneInstance = getSoftPhoneInstance(myCoordinate); // Calculate the SoftPhone instance according the selected coordinate
        final SoftPhone softPhoneInstance = (SoftPhone) threadArray[selectedSoftPhoneInstance]; // Get the related SoftPhone instance reference
        softPhoneInstance.setEPhoneGUIActive(true);

        Thread selectPhoneThread = new Thread(allThreadsGroup, new Runnable() {
            @Override// ww  w . j a  va2 s .  co m
            public void run() {
                java.awt.EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        EPhone mySoftPhoneGUI = new EPhone(softPhoneInstance); // SoftPhoneGUI usually tied up with new SoftPhone instance, but in this case it's not a new instance it's an existing instance
                        mySoftPhoneGUI.setVisible(true);
                        softPhoneInstance.setUserInterface2(mySoftPhoneGUI);
                        softPhoneInstance.updateDisplay();
                    }
                });
            }
        });
        selectPhoneThread.setName("selectPhoneThread");
        selectPhoneThread.setDaemon(runThreadsAsDaemons);
        selectPhoneThread.setPriority(4);
        selectPhoneThread.start();
    }
}