Search in sources :

Example 81 with Comparator

use of java.util.Comparator in project gradle by gradle.

the class DefaultGroupTaskReportModel method build.

public void build(TaskReportModel model) {
    Comparator<String> keyComparator = GUtil.last(GUtil.last(STRING_COMPARATOR, OTHER_GROUP), DEFAULT_GROUP);
    Comparator<TaskDetails> taskComparator = new Comparator<TaskDetails>() {

        public int compare(TaskDetails task1, TaskDetails task2) {
            int diff = STRING_COMPARATOR.compare(task1.getPath().getName(), task2.getPath().getName());
            if (diff != 0) {
                return diff;
            }
            Path parent1 = task1.getPath().getParent();
            Path parent2 = task2.getPath().getParent();
            if (parent1 == null && parent2 != null) {
                return -1;
            }
            if (parent1 != null && parent2 == null) {
                return 1;
            }
            if (parent1 == null) {
                return 0;
            }
            return parent1.compareTo(parent2);
        }
    };
    groups = TreeMultimap.create(keyComparator, taskComparator);
    for (String group : model.getGroups()) {
        groups.putAll(group, model.getTasksForGroup(group));
    }
    String otherGroupName = findOtherGroup(groups.keySet());
    if (otherGroupName != null && groups.keySet().contains(DEFAULT_GROUP)) {
        groups.putAll(otherGroupName, groups.removeAll(DEFAULT_GROUP));
    }
    if (groups.keySet().contains(DEFAULT_GROUP) && groups.keySet().size() > 1) {
        groups.putAll(OTHER_GROUP, groups.removeAll(DEFAULT_GROUP));
    }
}
Also used : Path(org.gradle.util.Path) Comparator(java.util.Comparator)

Example 82 with Comparator

use of java.util.Comparator in project translationstudio8 by heartsome.

the class GridTableViewer method createCellSelection.

private CellSelection createCellSelection() {
    Point[] ps = grid.getCellSelection();
    Arrays.sort(ps, new Comparator() {

        public int compare(Object arg0, Object arg1) {
            Point a = (Point) arg0;
            Point b = (Point) arg1;
            int rv = a.y - b.y;
            if (rv == 0) {
                rv = a.x - b.x;
            }
            return rv;
        }
    });
    ArrayList objectList = new ArrayList();
    ArrayList indiceLists = new ArrayList();
    ArrayList indiceList = new ArrayList();
    int curLine = -1;
    for (int i = 0; i < ps.length; i++) {
        if (curLine != ps[i].y) {
            curLine = ps[i].y;
            indiceList = new ArrayList();
            indiceLists.add(indiceList);
            objectList.add(grid.getItem(curLine).getData());
        }
        indiceList.add(new Integer(ps[i].x));
    }
    Object focusElement = null;
    if (grid.getFocusItem() != null) {
        focusElement = grid.getFocusItem().getData();
    }
    return new CellSelection(objectList, indiceLists, focusElement, getComparer());
}
Also used : ArrayList(java.util.ArrayList) CellSelection(org.eclipse.nebula.jface.gridviewer.internal.CellSelection) Point(org.eclipse.swt.graphics.Point) Point(org.eclipse.swt.graphics.Point) Comparator(java.util.Comparator)

Example 83 with Comparator

use of java.util.Comparator in project hazelcast by hazelcast.

the class TopicTest method testTopicLocalOrder.

@Test
@SuppressWarnings("unchecked")
public void testTopicLocalOrder() throws Exception {
    final int nodeCount = 5;
    final int count = 1000;
    final String randomTopicName = randomString();
    Config config = new Config();
    config.getTopicConfig(randomTopicName).setGlobalOrderingEnabled(false);
    TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(nodeCount);
    final HazelcastInstance[] instances = factory.newInstances(config);
    final List<TestMessage>[] messageLists = new List[nodeCount];
    for (int i = 0; i < nodeCount; i++) {
        messageLists[i] = new CopyOnWriteArrayList<TestMessage>();
    }
    final CountDownLatch startLatch = new CountDownLatch(nodeCount);
    final CountDownLatch messageLatch = new CountDownLatch(nodeCount * nodeCount * count);
    final CountDownLatch publishLatch = new CountDownLatch(nodeCount * count);
    ExecutorService ex = Executors.newFixedThreadPool(nodeCount);
    for (int i = 0; i < nodeCount; i++) {
        final int finalI = i;
        ex.execute(new Runnable() {

            public void run() {
                final List<TestMessage> messages = messageLists[finalI];
                HazelcastInstance hz = instances[finalI];
                ITopic<TestMessage> topic = hz.getTopic(randomTopicName);
                topic.addMessageListener(new MessageListener<TestMessage>() {

                    public void onMessage(Message<TestMessage> message) {
                        messages.add(message.getMessageObject());
                        messageLatch.countDown();
                    }
                });
                startLatch.countDown();
                try {
                    startLatch.await(1, TimeUnit.MINUTES);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return;
                }
                Member localMember = hz.getCluster().getLocalMember();
                for (int j = 0; j < count; j++) {
                    topic.publish(new TestMessage(localMember, UuidUtil.newUnsecureUuidString()));
                    publishLatch.countDown();
                }
            }
        });
    }
    try {
        assertTrue(publishLatch.await(2, TimeUnit.MINUTES));
        assertTrue(messageLatch.await(5, TimeUnit.MINUTES));
        TestMessage[] ref = new TestMessage[messageLists[0].size()];
        messageLists[0].toArray(ref);
        Comparator<TestMessage> comparator = new Comparator<TestMessage>() {

            public int compare(TestMessage m1, TestMessage m2) {
                // sort only publisher blocks. if publishers are the same, leave them as they are
                return m1.publisher.getUuid().compareTo(m2.publisher.getUuid());
            }
        };
        Arrays.sort(ref, comparator);
        for (int i = 1; i < nodeCount; i++) {
            TestMessage[] messages = new TestMessage[messageLists[i].size()];
            messageLists[i].toArray(messages);
            Arrays.sort(messages, comparator);
            assertArrayEquals(ref, messages);
        }
    } finally {
        ex.shutdownNow();
    }
}
Also used : ITopic(com.hazelcast.core.ITopic) Message(com.hazelcast.core.Message) ListenerConfig(com.hazelcast.config.ListenerConfig) Config(com.hazelcast.config.Config) MessageListener(com.hazelcast.core.MessageListener) CountDownLatch(java.util.concurrent.CountDownLatch) Comparator(java.util.Comparator) HazelcastInstance(com.hazelcast.core.HazelcastInstance) ExecutorService(java.util.concurrent.ExecutorService) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) TestHazelcastInstanceFactory(com.hazelcast.test.TestHazelcastInstanceFactory) Member(com.hazelcast.core.Member) QuickTest(com.hazelcast.test.annotation.QuickTest) NightlyTest(com.hazelcast.test.annotation.NightlyTest) Test(org.junit.Test) ParallelTest(com.hazelcast.test.annotation.ParallelTest)

Example 84 with Comparator

use of java.util.Comparator in project smooth-app-bar-layout by henrytao-me.

the class BaseActivity method requestItemsForPurchase.

private void requestItemsForPurchase(final AsyncCallback<List<PurchaseItem>> callback) {
    if (mPurchaseItems != null && mPurchaseItems.size() > 0) {
        if (callback != null) {
            callback.onSuccess(mPurchaseItems);
        }
        return;
    }
    new AsyncTask<IInAppBillingService, Void, AsyncResult<List<PurchaseItem>>>() {

        @Override
        protected AsyncResult<List<PurchaseItem>> doInBackground(IInAppBillingService... params) {
            List<PurchaseItem> result = new ArrayList<>();
            Throwable exception = null;
            IInAppBillingService billingService = params[0];
            if (billingService == null) {
                exception = new Exception("Unknow");
            } else {
                ArrayList<String> skuList = new ArrayList<>(Arrays.asList(DONATE_ITEMS));
                Bundle querySkus = new Bundle();
                querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
                try {
                    Bundle skuDetails = billingService.getSkuDetails(3, getPackageName(), "inapp", querySkus);
                    int response = skuDetails.getInt("RESPONSE_CODE");
                    if (response == 0) {
                        ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
                        PurchaseItem purchaseItem;
                        for (String item : responseList) {
                            purchaseItem = new PurchaseItem(new JSONObject(item));
                            if (purchaseItem.isValid()) {
                                result.add(purchaseItem);
                            }
                        }
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                    exception = e;
                } catch (JSONException e) {
                    e.printStackTrace();
                    exception = e;
                }
            }
            return new AsyncResult<>(result, exception);
        }

        @Override
        protected void onPostExecute(AsyncResult<List<PurchaseItem>> result) {
            if (!isFinishing() && callback != null) {
                Throwable error = result.getError();
                if (error == null && (result.getResult() == null || result.getResult().size() == 0)) {
                    error = new Exception("Unknow");
                }
                if (error != null) {
                    callback.onError(error);
                } else {
                    mPurchaseItems = result.getResult();
                    Collections.sort(mPurchaseItems, new Comparator<PurchaseItem>() {

                        @Override
                        public int compare(PurchaseItem lhs, PurchaseItem rhs) {
                            return (int) ((lhs.getPriceAmountMicros() - rhs.getPriceAmountMicros()) / 1000);
                        }
                    });
                    callback.onSuccess(mPurchaseItems);
                }
            }
        }
    }.execute(mBillingService);
}
Also used : Bundle(android.os.Bundle) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) RemoteException(android.os.RemoteException) JSONException(org.json.JSONException) Comparator(java.util.Comparator) JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List) IInAppBillingService(com.android.vending.billing.IInAppBillingService) RemoteException(android.os.RemoteException)

Example 85 with Comparator

use of java.util.Comparator in project android_frameworks_base by DirtyUnicorns.

the class AlarmManagerService method dumpImpl.

void dumpImpl(PrintWriter pw) {
    synchronized (mLock) {
        pw.println("Current Alarm Manager state:");
        mConstants.dump(pw);
        pw.println();
        final long nowRTC = System.currentTimeMillis();
        final long nowELAPSED = SystemClock.elapsedRealtime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        pw.print("  nowRTC=");
        pw.print(nowRTC);
        pw.print("=");
        pw.print(sdf.format(new Date(nowRTC)));
        pw.print(" nowELAPSED=");
        pw.print(nowELAPSED);
        pw.println();
        pw.print("  mLastTimeChangeClockTime=");
        pw.print(mLastTimeChangeClockTime);
        pw.print("=");
        pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
        pw.print("  mLastTimeChangeRealtime=");
        TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
        pw.println();
        if (!mInteractive) {
            pw.print("  Time since non-interactive: ");
            TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
            pw.println();
            pw.print("  Max wakeup delay: ");
            TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
            pw.println();
            pw.print("  Time since last dispatch: ");
            TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
            pw.println();
            pw.print("  Next non-wakeup delivery time: ");
            TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
            pw.println();
        }
        long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
        long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
        pw.print("  Next non-wakeup alarm: ");
        TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
        pw.print(" = ");
        pw.println(sdf.format(new Date(nextNonWakeupRTC)));
        pw.print("  Next wakeup: ");
        TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
        pw.print(" = ");
        pw.println(sdf.format(new Date(nextWakeupRTC)));
        pw.print("  Last wakeup: ");
        TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
        pw.print(" set at ");
        TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
        pw.println();
        pw.print("  Num time change events: ");
        pw.println(mNumTimeChanged);
        pw.println("  mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
        pw.println();
        pw.println("  Next alarm clock information: ");
        final TreeSet<Integer> users = new TreeSet<>();
        for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
            users.add(mNextAlarmClockForUser.keyAt(i));
        }
        for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
            users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
        }
        for (int user : users) {
            final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
            final long time = next != null ? next.getTriggerTime() : 0;
            final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
            pw.print("    user:");
            pw.print(user);
            pw.print(" pendingSend:");
            pw.print(pendingSend);
            pw.print(" time:");
            pw.print(time);
            if (time > 0) {
                pw.print(" = ");
                pw.print(sdf.format(new Date(time)));
                pw.print(" = ");
                TimeUtils.formatDuration(time, nowRTC, pw);
            }
            pw.println();
        }
        if (mAlarmBatches.size() > 0) {
            pw.println();
            pw.print("  Pending alarm batches: ");
            pw.println(mAlarmBatches.size());
            for (Batch b : mAlarmBatches) {
                pw.print(b);
                pw.println(':');
                dumpAlarmList(pw, b.alarms, "    ", nowELAPSED, nowRTC, sdf);
            }
        }
        if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
            pw.println();
            pw.println("    Idle mode state:");
            pw.print("      Idling until: ");
            if (mPendingIdleUntil != null) {
                pw.println(mPendingIdleUntil);
                mPendingIdleUntil.dump(pw, "        ", nowRTC, nowELAPSED, sdf);
            } else {
                pw.println("null");
            }
            pw.println("      Pending alarms:");
            dumpAlarmList(pw, mPendingWhileIdleAlarms, "      ", nowELAPSED, nowRTC, sdf);
        }
        if (mNextWakeFromIdle != null) {
            pw.println();
            pw.print("  Next wake from idle: ");
            pw.println(mNextWakeFromIdle);
            mNextWakeFromIdle.dump(pw, "    ", nowRTC, nowELAPSED, sdf);
        }
        pw.println();
        pw.print("  Past-due non-wakeup alarms: ");
        if (mPendingNonWakeupAlarms.size() > 0) {
            pw.println(mPendingNonWakeupAlarms.size());
            dumpAlarmList(pw, mPendingNonWakeupAlarms, "    ", nowELAPSED, nowRTC, sdf);
        } else {
            pw.println("(none)");
        }
        pw.print("    Number of delayed alarms: ");
        pw.print(mNumDelayedAlarms);
        pw.print(", total delay time: ");
        TimeUtils.formatDuration(mTotalDelayTime, pw);
        pw.println();
        pw.print("    Max delay time: ");
        TimeUtils.formatDuration(mMaxDelayTime, pw);
        pw.print(", max non-interactive time: ");
        TimeUtils.formatDuration(mNonInteractiveTime, pw);
        pw.println();
        pw.println();
        pw.print("  Broadcast ref count: ");
        pw.println(mBroadcastRefCount);
        pw.println();
        if (mInFlight.size() > 0) {
            pw.println("Outstanding deliveries:");
            for (int i = 0; i < mInFlight.size(); i++) {
                pw.print("   #");
                pw.print(i);
                pw.print(": ");
                pw.println(mInFlight.get(i));
            }
            pw.println();
        }
        pw.print("  mAllowWhileIdleMinTime=");
        TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
        pw.println();
        if (mLastAllowWhileIdleDispatch.size() > 0) {
            pw.println("  Last allow while idle dispatch times:");
            for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); i++) {
                pw.print("  UID ");
                UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
                pw.print(": ");
                TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i), nowELAPSED, pw);
                pw.println();
            }
        }
        pw.println();
        if (mLog.dump(pw, "  Recent problems", "    ")) {
            pw.println();
        }
        final FilterStats[] topFilters = new FilterStats[10];
        final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {

            @Override
            public int compare(FilterStats lhs, FilterStats rhs) {
                if (lhs.aggregateTime < rhs.aggregateTime) {
                    return 1;
                } else if (lhs.aggregateTime > rhs.aggregateTime) {
                    return -1;
                }
                return 0;
            }
        };
        int len = 0;
        for (int iu = 0; iu < mBroadcastStats.size(); iu++) {
            ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
            for (int ip = 0; ip < uidStats.size(); ip++) {
                BroadcastStats bs = uidStats.valueAt(ip);
                for (int is = 0; is < bs.filterStats.size(); is++) {
                    FilterStats fs = bs.filterStats.valueAt(is);
                    int pos = len > 0 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
                    if (pos < 0) {
                        pos = -pos - 1;
                    }
                    if (pos < topFilters.length) {
                        int copylen = topFilters.length - pos - 1;
                        if (copylen > 0) {
                            System.arraycopy(topFilters, pos, topFilters, pos + 1, copylen);
                        }
                        topFilters[pos] = fs;
                        if (len < topFilters.length) {
                            len++;
                        }
                    }
                }
            }
        }
        if (len > 0) {
            pw.println("  Top Alarms:");
            for (int i = 0; i < len; i++) {
                FilterStats fs = topFilters[i];
                pw.print("    ");
                if (fs.nesting > 0)
                    pw.print("*ACTIVE* ");
                TimeUtils.formatDuration(fs.aggregateTime, pw);
                pw.print(" running, ");
                pw.print(fs.numWakeup);
                pw.print(" wakeups, ");
                pw.print(fs.count);
                pw.print(" alarms: ");
                UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
                pw.print(":");
                pw.print(fs.mBroadcastStats.mPackageName);
                pw.println();
                pw.print("      ");
                pw.print(fs.mTag);
                pw.println();
            }
        }
        pw.println(" ");
        pw.println("  Alarm Stats:");
        final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
        for (int iu = 0; iu < mBroadcastStats.size(); iu++) {
            ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
            for (int ip = 0; ip < uidStats.size(); ip++) {
                BroadcastStats bs = uidStats.valueAt(ip);
                pw.print("  ");
                if (bs.nesting > 0)
                    pw.print("*ACTIVE* ");
                UserHandle.formatUid(pw, bs.mUid);
                pw.print(":");
                pw.print(bs.mPackageName);
                pw.print(" ");
                TimeUtils.formatDuration(bs.aggregateTime, pw);
                pw.print(" running, ");
                pw.print(bs.numWakeup);
                pw.println(" wakeups:");
                tmpFilters.clear();
                for (int is = 0; is < bs.filterStats.size(); is++) {
                    tmpFilters.add(bs.filterStats.valueAt(is));
                }
                Collections.sort(tmpFilters, comparator);
                for (int i = 0; i < tmpFilters.size(); i++) {
                    FilterStats fs = tmpFilters.get(i);
                    pw.print("    ");
                    if (fs.nesting > 0)
                        pw.print("*ACTIVE* ");
                    TimeUtils.formatDuration(fs.aggregateTime, pw);
                    pw.print(" ");
                    pw.print(fs.numWakeup);
                    pw.print(" wakes ");
                    pw.print(fs.count);
                    pw.print(" alarms, last ");
                    TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
                    pw.println(":");
                    pw.print("      ");
                    pw.print(fs.mTag);
                    pw.println();
                }
            }
        }
        if (RECORD_DEVICE_IDLE_ALARMS) {
            pw.println();
            pw.println("  Allow while idle dispatches:");
            for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
                IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
                pw.print("    ");
                TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
                pw.print(": ");
                UserHandle.formatUid(pw, ent.uid);
                pw.print(":");
                pw.println(ent.pkg);
                if (ent.op != null) {
                    pw.print("      ");
                    pw.print(ent.op);
                    pw.print(" / ");
                    pw.print(ent.tag);
                    if (ent.argRealtime != 0) {
                        pw.print(" (");
                        TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
                        pw.print(")");
                    }
                    pw.println();
                }
            }
        }
        if (WAKEUP_STATS) {
            pw.println();
            pw.println("  Recent Wakeup History:");
            long last = -1;
            for (WakeupEvent event : mRecentWakeups) {
                pw.print("    ");
                pw.print(sdf.format(new Date(event.when)));
                pw.print('|');
                if (last < 0) {
                    pw.print('0');
                } else {
                    pw.print(event.when - last);
                }
                last = event.when;
                pw.print('|');
                pw.print(event.uid);
                pw.print('|');
                pw.print(event.action);
                pw.println();
            }
            pw.println();
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Date(java.util.Date) Comparator(java.util.Comparator) TreeSet(java.util.TreeSet) IAlarmManager(android.app.IAlarmManager) AlarmManager(android.app.AlarmManager) SimpleDateFormat(java.text.SimpleDateFormat)

Aggregations

Comparator (java.util.Comparator)322 ArrayList (java.util.ArrayList)123 List (java.util.List)58 Test (org.junit.Test)58 HashMap (java.util.HashMap)50 IOException (java.io.IOException)36 Map (java.util.Map)35 File (java.io.File)24 HashSet (java.util.HashSet)23 TreeSet (java.util.TreeSet)20 Set (java.util.Set)18 Iterator (java.util.Iterator)15 Method (java.lang.reflect.Method)14 Collections (java.util.Collections)14 Date (java.util.Date)14 TreeMap (java.util.TreeMap)14 ArrayMap (android.util.ArrayMap)12 Collection (java.util.Collection)11 LinkedList (java.util.LinkedList)11 SimpleDateFormat (java.text.SimpleDateFormat)10