Example usage for java.util Collections reverse

List of usage examples for java.util Collections reverse

Introduction

In this page you can find the example usage for java.util Collections reverse.

Prototype

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void reverse(List<?> list) 

Source Link

Document

Reverses the order of the elements in the specified list.

This method runs in linear time.

Usage

From source file:com.netflix.curator.x.discovery.TestServiceDiscovery.java

@Test
public void testBasic() throws Exception {
    List<Closeable> closeables = Lists.newArrayList();
    TestingServer server = new TestingServer();
    closeables.add(server);//w ww  .ja va  2  s  . c om
    try {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test")
                .port(10064).build();
        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test")
                .client(client).thisInstance(instance).build();
        closeables.add(discovery);
        discovery.start();

        Assert.assertEquals(discovery.queryForNames(), Arrays.asList("test"));

        List<ServiceInstance<String>> list = Lists.newArrayList();
        list.add(instance);
        Assert.assertEquals(discovery.queryForInstances("test"), list);
    } finally {
        Collections.reverse(closeables);
        for (Closeable c : closeables) {
            IOUtils.closeQuietly(c);
        }
    }
}

From source file:com.moviejukebox.plugin.ImdbPlugin.java

protected String getPreferredValue(List<String> values, boolean useLast) {
    String value = UNKNOWN;

    if (useLast) {
        Collections.reverse(values);
    }//from w w  w . j a va  2 s.co m

    for (String text : values) {
        String country = null;

        int pos = text.indexOf(':');
        if (pos != -1) {
            country = text.substring(0, pos);
            text = text.substring(pos + 1);
        }
        pos = text.indexOf('(');
        if (pos != -1) {
            text = text.substring(0, pos).trim();
        }

        if (country == null) {
            if (value.equals(UNKNOWN)) {
                value = text;
            }
        } else if (country.equals(preferredCountry)) {
            value = text;
            // No need to continue scanning
            break;
        }
    }
    return HTMLTools.stripTags(value);
}

From source file:com.arctech.stikyhive.ChattingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    recipientStkid = getIntent().getExtras().getString("recipientStkid");
    chatRecipient = getIntent().getExtras().getString("chatRecipient");
    chatRecipientUrl = getIntent().getExtras().getString("chatRecipientUrl");
    senderToken = getIntent().getExtras().getString("senderToken");
    recipientToken = getIntent().getExtras().getString("recipientToken");
    noti = getIntent().getExtras().getBoolean("noti");
    message = getIntent().getExtras().getString("message");
    rows = getIntent().getExtras().getInt("rows");

    pref = PreferenceManager.getDefaultSharedPreferences(this);
    ws = new JsonWebService();
    dbHelper = new DBHelper(this);
    dialog = new ProgressDialog(this);
    listChatContact = new ArrayList<>();
    listChatContact = dbHelper.getChatContact();
    Log.i(" Chat Contact ", " " + listChatContact.size());
    //to change font
    faceSemi_bold = Typeface.createFromAsset(getAssets(), fontOSSemi_bold);
    Typeface faceLight = Typeface.createFromAsset(getAssets(), fontOSLight);
    faceRegular = Typeface.createFromAsset(getAssets(), fontOSRegular);

    imageLoader = ImageLoader.getInstance();
    if (!imageLoader.isInited()) {
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
    }//from www .  j  a v a2 s  .c o m

    start = new Date();
    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
    timeSend = oFormat.format(start);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat);

    txtUserName = (TextView) findViewById(R.id.txtChatName);
    edTxtMsg = (EditText) findViewById(R.id.edTxtMsg);
    imgViewProfile = (ImageView) findViewById(R.id.imgViewChat);
    imgViewAddCon = (ImageView) findViewById(R.id.imgAddContact);
    lv = (ListView) findViewById(R.id.listView1);
    layoutLabel = (LinearLayout) findViewById(R.id.layoutLabel);
    txtLabel1 = (TextView) findViewById(R.id.txtLabel1);
    txtLabel2 = (TextView) findViewById(R.id.txtLabel2);
    txtLabel3 = (TextView) findViewById(R.id.txtLabel3);
    txtLabel2.setText(" " + chatRecipient + " ");
    txtLabel1.setTypeface(faceLight);
    txtLabel2.setTypeface(faceRegular);
    txtLabel3.setTypeface(faceLight);
    // lv.smoothScrollToPosition(adapter.getCount() - 1);

    for (ChatContact contact : listChatContact) {
        if (contact.getContactId().equals(recipientStkid)) {
            imgViewAddCon.setVisibility(View.INVISIBLE);
            layoutLabel.setVisibility(View.GONE);
            break;
        }
    }
    Log.i(TAG, " come back again");
    adapter = new ChatArrayAdapter(getApplicationContext(), R.layout.messaging_listview, faceSemi_bold,
            faceRegular);
    lv.setAdapter(adapter);
    // adapter.add(new StikyChat(chatRecipientUrl, "Hello", false, "12.10.2015", "12.1.2014"));

    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    // BEGIN_INCLUDE (change_colors)
    // Set the color scheme of the SwipeRefreshLayout by providing 4 color resource ids
    swipeRefreshLayout.setColorScheme(R.color.swipe_color_1, R.color.swipe_color_2, R.color.swipe_color_3,
            R.color.swipe_color_4);
    limitMsg = 7;
    // END_INCLUDE (change_colors)
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.i(" Refresh Layout ", "onRefresh called from SwipeRefreshLayout");
            if (limitMsg < rows) {
                Log.i("Limit Message ", " " + limitMsg);
                limitMsg *= 2;
                fetchRecords();
            } else if (limitMsg > rows && (limitMsg - rows < 7)) {
                fetchRecords();
            } else {
                Log.i("No data ", "to refresh");
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getApplicationContext(), "No data to refresh!", Toast.LENGTH_SHORT).show();
            }

            // initiateRefresh();
        }
    });

    LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout headerLayout = (LinearLayout) findViewById(R.id.header);
    View header = inflator.inflate(R.layout.header, null);

    TextView textView = (TextView) header.findViewById(R.id.textView1);
    textView.setText("StikyChat");
    textView.setTypeface(faceSemi_bold);
    textView.setVisibility(View.VISIBLE);
    headerLayout.addView(header);
    LinearLayout layoutRight = (LinearLayout) header.findViewById(R.id.layoutRight);
    layoutRight.setVisibility(View.GONE);

    txtUserName.setText(chatRecipient);
    Log.i(TAG, "Activity Name " + txtUserName.getText().toString());
    txtUserName.setTypeface(faceSemi_bold);

    String url = "";
    if (chatRecipientUrl.contains("http")) {
        url = chatRecipientUrl;
    } else {
        url = this.getResources().getString(R.string.url) + "/" + chatRecipientUrl;
    }
    addAndroidUniversalImageLoader(imgViewProfile, url);
    //        if (noti && (!message.equals(""))) {
    //            adapter.add(new StikyChat(chatRecipientUrl, message, true, timeSend, ""));
    //            lv.smoothScrollToPosition(adapter.getCount() - 1);
    //        }

    //to show history chats between two users(sender & recipient)
    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat2 = new SimpleDateFormat("dd MMM HH:mm");
    listHistory = dbHelper.getStikyChat();
    if (listHistory.size() > 0) {
        Collections.reverse(listHistory);
        for (StikyChatTb chatTb : listHistory) {
            String getDate = chatTb.getSendDate();
            String fromStikyBee = chatTb.getSender();
            try {
                String createDate = dateFormat2.format(dateFormat.parse(getDate));
                if (fromStikyBee.equals(pref.getString("stkid", ""))) {
                    adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate, ""));
                } else {
                    adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate, ""));
                }
                lv.smoothScrollToPosition(adapter.getCount() - 1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            messageGCM = sharedPreferences.getString("message", "");
            recipientProfileGCM = sharedPreferences.getString("chatRecipientUrl", "");
            recipientNameGCM = sharedPreferences.getString("chatRecipientName", "");
            recipientStkidGCM = sharedPreferences.getString("recipientStkid", "");
            recipientTokenGCM = sharedPreferences.getString("recipientToken", "");
            senderTokenGCM = sharedPreferences.getString("senderToken", "");

            Log.i(TAG, "..." + recipientStkidGCM.trim() + " STKID " + recipientStkid.trim() + ":");
            if (firstConnect) {
                if (recipientStkidGCM.trim() == recipientStkid.trim()
                        || recipientStkidGCM.equals(recipientStkid)) {
                    MyGcmListenerService.flagSendNoti = false;
                    Log.i(TAG, " " + message);
                    // (1) get today's date
                    start = new Date();
                    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
                    timeSend = oFormat.format(start);

                    Log.i(TAG, "First connect " + firstConnect);
                    StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend, "");
                    Log.i(TAG, " First " + message + " " + recipientProfileGCM + " " + timeSend);
                    Log.i(TAG, "User " + txtUserName.getText().toString());
                    //txtUserName.setText(message);
                    Log.i(TAG, "User 2 " + txtUserName.getText().toString());
                    adapter.add(stikyChat);
                    adapter.notifyDataSetChanged();
                    //new regTask2().execute("Obj ");
                    lv.smoothScrollToPosition(adapter.getCount() - 1);
                } else {
                    Log.i(TAG, "..." + recipientStkidGCM.trim());
                    Log.i(TAG, "&&&" + recipientStkid.trim());
                    Log.i(TAG, "else casee");
                    //notificaton send
                    flagNotifi = true;
                    new regTask2().execute("Notification");
                }
                firstConnect = false;
            }
        }
    };
}

From source file:immf.ImodeNetClient.java

/**
 *
 * @param folderId ??ID?????ID?(0:?)/*from   ww w  .jav a2  s.  c o m*/
 * @return ID????????ID???Map
 * @throws IOException
 * @throws LoginException
 */
public synchronized Map<Integer, List<String>> getMailIdList() throws IOException, LoginException {
    log.info("# ID?");
    HttpPost post = null;

    try {
        // null????cookie?????????
        if (this.logined != null && this.logined == Boolean.FALSE) {
            this.login();
        }

        post = new HttpPost(JsonUrl + "mailidlist");
        HttpResponse res = this.requestPost(post, null);
        if (!isJson(res)) {
            if (res != null)
                toStringBody(res);
            post.abort();
            this.clearCookie();
            this.logined = Boolean.FALSE;
            throw new LoginException("Response is not Json");
        }
        JSONObject json = JSONObject.fromObject(toStringBody(res));

        String result = json.getJSONObject("common").getString("result");
        if (!result.equals("PW1000")) {
            log.debug(json.toString(2));
            this.clearCookie();
            this.logined = Boolean.FALSE;
            throw new LoginException("Bad response " + result);
        }
        this.logined = Boolean.TRUE;
        //log.debug(json.toString(2));
        JSONArray array = json.getJSONObject("data").getJSONArray("folderList");

        Map<Integer, List<String>> r = new TreeMap<Integer, List<String>>();
        for (int i = 0; i < array.size(); i++) {
            json = array.getJSONObject(i);
            int folderId = json.getInt("folderId");
            if (folderId == FolderIdDrafts) {
                // ???
                // ?????
                continue;
            }
            log.debug("FolderId " + folderId);
            @SuppressWarnings("unchecked")
            Collection<String> mailIdlist = (Collection<String>) JSONArray
                    .toCollection(json.getJSONArray("mailIdList"), String.class);
            if (mailIdlist.isEmpty()) {
                // ??(folderId=0?mailId?)
                continue;
            }
            List<String> list = new ArrayList<String>(mailIdlist);
            Collections.sort(list);
            Collections.reverse(list);
            r.put(folderId, list);
        }

        return r;
    } finally {
        if (post != null)
            post.abort();
    }
}

From source file:com.expressui.core.util.BeanPropertyType.java

/**
 * Gets the list of ancestors of this property type, starting with the root and ending with this property type.
 *
 * @return list of property type ancestors
 *//* w  w  w  .j a  v a  2s  .  c o  m*/
public List<BeanPropertyType> getAncestors() {
    List<BeanPropertyType> ancestors = new ArrayList<BeanPropertyType>();
    BeanPropertyType currentBeanPropertyType = this;
    while (currentBeanPropertyType != null) {
        ancestors.add(currentBeanPropertyType);
        currentBeanPropertyType = currentBeanPropertyType.getParent();
    }

    Collections.reverse(ancestors);

    return ancestors;
}

From source file:com.rapleaf.hank.storage.incremental.IncrementalPartitionUpdater.java

/**
 * Return the list of versions needed to update to the specific version given that
 * the specified current version and cached bases are available.
 *
 * @param currentVersion//from w  w  w. j  a  va2  s  .co  m
 * @param cachedBases
 * @param updatingToVersion
 * @return
 * @throws java.io.IOException
 */
protected IncrementalUpdatePlan computeUpdatePlan(DomainVersion currentVersion, Set<DomainVersion> cachedBases,
        DomainVersion updatingToVersion) throws IOException {
    LinkedList<DomainVersion> updatePlanVersions = new LinkedList<DomainVersion>();
    // Backtrack versions (ignoring defunct versions) until we find:
    // - a base (no parent)
    // - or the current version (which is by definition a base or a rebased delta)
    // - or a version that is a base and that is cached
    DomainVersion parentVersion = updatingToVersion;
    while (parentVersion != null) {
        // Ignore completely defunct versions
        if (!parentVersion.isDefunct()) {
            // If a version along the path is still open, abort
            if (!DomainVersions.isClosed(parentVersion)) {
                throw new IOException("Detected a domain version that is still open"
                        + " along the path from current version to version to update to: " + " domain: "
                        + domain + " open version: " + parentVersion + " current version: " + currentVersion
                        + " updating to version: " + updatingToVersion);
            }
            // If backtrack to current version, use it and stop backtracking
            if (currentVersion != null && parentVersion.equals(currentVersion)) {
                // If we only need the current version, we don't need any plan
                if (updatePlanVersions.isEmpty()) {
                    return null;
                } else {
                    updatePlanVersions.add(parentVersion);
                    break;
                }
            }
            // If backtrack to cached base version, use it and stop backtracking
            if (cachedBases.contains(parentVersion)) {
                updatePlanVersions.add(parentVersion);
                break;
            }
            // Add backtracked version to versions needed
            updatePlanVersions.add(parentVersion);
        }
        // Move to parent version
        parentVersion = getParentDomainVersion(parentVersion);
    }
    if (updatePlanVersions.isEmpty()) {
        return null;
    }
    // The base is the last version that was added (a base, the current version or a cached base)
    DomainVersion base = updatePlanVersions.removeLast();
    // Reverse list of deltas as we have added versions going backwards
    Collections.reverse(updatePlanVersions);
    return new IncrementalUpdatePlan(base, updatePlanVersions);
}

From source file:com.liusoft.dlog4j.velocity.DLOG_Photo_VelocityTool.java

/**
 * //from w w w .j a  v  a  2s. c  o  m
 * @param site
 * @return
 */
public List list_photo_months(SiteBean site) {
    if (site == null)
        return null;
    List months = PhotoDAO.listMonths(site.getId());
    Collections.reverse(months);
    return months;
}

From source file:com.haulmont.cuba.core.sys.AbstractMessages.java

@Nullable
protected String searchMessage(String packs, String key, Locale locale, Locale truncatedLocale,
        Set<String> passedPacks) {
    StrTokenizer tokenizer = new StrTokenizer(packs);
    //noinspection unchecked
    List<String> list = tokenizer.getTokenList();
    Collections.reverse(list);
    for (String pack : list) {
        if (!enterPack(pack, locale, truncatedLocale, passedPacks))
            continue;

        String msg = searchOnePack(pack, key, locale, truncatedLocale, passedPacks);
        if (msg != null)
            return msg;

        Locale tmpLocale = truncatedLocale;
        while (tmpLocale != null) {
            tmpLocale = truncateLocale(tmpLocale);
            msg = searchOnePack(pack, key, locale, tmpLocale, passedPacks);
            if (msg != null)
                return msg;
        }//from  ww  w .  java 2s.  c o  m
    }
    if (log.isTraceEnabled()) {
        String packName = new StrBuilder().appendWithSeparators(list, ",").toString();
        log.trace("Resource '" + makeCacheKey(packName, key, locale, locale) + "' not found");
    }
    return null;
}

From source file:com.xpn.xwiki.stats.impl.xwiki.XWikiStatsReader.java

/**
 * Retrieves back-link statistics./*from  ww  w .  jav  a2s  .  co  m*/
 * 
 * @param domain the domain used for filtering the results.
 * @param scope the scope of referred documents for which to retrieve statistics.
 * @param period the period of time, including its start date but excluding its end date.
 * @param range the sub-range to return from the entire result set. Use this parameter for pagination.
 * @param context the XWiki context.
 * @return a list of DocumentStats objects.
 */
public List<DocumentStats> getBackLinkStatistics(String domain, Scope scope, Period period, Range range,
        XWikiContext context) {
    List<DocumentStats> documentStatsList;

    List<Object> paramList = new ArrayList<Object>(4);

    String nameFilter = getHqlNameFilterFromScope(scope, paramList);

    String sortOrder = getHqlSortOrderFromRange(range);

    XWikiHibernateStore store = context.getWiki().getHibernateStore();
    try {
        String query = MessageFormat.format("select name, sum(pageViews) from RefererStats"
                + " where {0} and referer like ? and ? <= period and period < ? group by name"
                + " order by sum(pageViews) {1}", nameFilter, sortOrder);

        paramList.add(getHqlValidDomain(domain));
        paramList.add(period.getStartCode());
        paramList.add(period.getEndCode());

        List<?> solist = store.search(query, range.getAbsoluteSize(), range.getAbsoluteStart(), paramList,
                context);

        documentStatsList = getDocumentStatistics(solist, "refer");
        if (range.getSize() < 0) {
            Collections.reverse(documentStatsList);
        }
    } catch (XWikiException e) {
        documentStatsList = Collections.emptyList();
    }

    return documentStatsList;
}

From source file:org.modeshape.web.jcr.rest.handler.RestItemHandlerImpl.java

/**
 * Performs a bulk deletion of items, using a single {@link javax.jcr.Session}. If any of the items cannot be deleted for whatever
 * reason, the entire operation fails.//from  w w w. j a  va 2s.co m
 *
 * @param request        the servlet request; may not be null or unauthenticated
 * @param repositoryName the URL-encoded repository name
 * @param workspaceName  the URL-encoded workspace name
 * @param requestContent the JSON-encoded array of the nodes to remove
 * @return a {@code non-null} {@link Result}
 * @throws javax.jcr.RepositoryException if any of the JCR operations fail
 * @see RestItemHandlerImpl#deleteItem(Request, String, String, String)
 */
@Override
public void deleteItems(Request request, String repositoryName, String workspaceName, String requestContent)
        throws RepositoryException {
    ArrayNode requestArray = stringToJSONArray(requestContent);
    if (requestArray.size() == 0) {
        return;
    }

    Session session = getSession(request, repositoryName, workspaceName);
    TreeSet<String> pathsInOrder = new TreeSet<>();
    for (int i = 0; i < requestArray.size(); i++) {
        pathsInOrder.add(absPath(requestArray.get(i).toString()));
    }
    List<String> pathsInOrderList = new ArrayList<>(pathsInOrder);
    Collections.reverse(pathsInOrderList);
    for (String path : pathsInOrderList) {
        doDelete(path, session);
    }
    session.save();
}