List of usage examples for java.util ArrayList subList
public List<E> subList(int fromIndex, int toIndex)
From source file:mp.teardrop.SongTimeline.java
/** * Run the given query and add the results to the song timeline. * * @param context A context to use./* w w w. j a va2s . c o m*/ * @param query The query to be run. The mode variable must be initialized * to one of SongTimeline.MODE_*. The type and data variables may also need * to be initialized depending on the given mode. * @return The number of songs that were added. */ public int addSongs(Context context, QueryTask query) { Cursor cursor = query.runQuery(context.getContentResolver()); if (cursor == null) { return 0; } int count = cursor.getCount(); if (count == 0) { return 0; } int mode = query.mode; int type = query.type; long data = query.data; ArrayList<Song> timeline = mSongs; synchronized (this) { saveActiveSongs(); switch (mode) { case MODE_ENQUEUE: case MODE_ENQUEUE_POS_FIRST: case MODE_ENQUEUE_ID_FIRST: break; case MODE_PLAY_NEXT: timeline.subList(mCurrentPos + 1, timeline.size()).clear(); break; case MODE_PLAY: case MODE_PLAY_POS_FIRST: case MODE_PLAY_ID_FIRST: timeline.clear(); mCurrentPos = 0; break; default: throw new IllegalArgumentException("Invalid mode: " + mode); } int start = timeline.size(); Song jumpSong = null; for (int j = 0; j != count; ++j) { cursor.moveToPosition(j); Song song = new Song(-1); song.populate(cursor); timeline.add(song); if (jumpSong == null) { if ((mode == MODE_PLAY_POS_FIRST || mode == MODE_ENQUEUE_POS_FIRST) && j == data) { jumpSong = song; } else if (mode == MODE_PLAY_ID_FIRST || mode == MODE_ENQUEUE_ID_FIRST) { long id; switch (type) { /* case MediaUtils.TYPE_ARTIST: id = song.artistId; break; case MediaUtils.TYPE_ALBUM: id = song.albumId; break; case MediaUtils.TYPE_SONG: id = song.id; break; */ default: throw new IllegalArgumentException("Unsupported id type: " + type); } /* if (id == data) jumpSong = song; */ } } } if (mShuffleMode != SHUFFLE_NONE) MediaUtils.shuffle(timeline.subList(start, timeline.size()), mShuffleMode == SHUFFLE_ALBUMS); if (jumpSong != null) { int jumpPos = timeline.indexOf(jumpSong); if (jumpPos != start) { // Get the sublist twice to avoid a ConcurrentModificationException. timeline.addAll(timeline.subList(start, jumpPos)); timeline.subList(start, jumpPos).clear(); } } broadcastChangedSongs(); } changed(); return count; }
From source file:com.soomla.store.billing.google.GoogleIabHelper.java
/** * Fetches items details for a given list of items. * * @throws RemoteException//from w ww . j a va 2 s . c o m * @throws JSONException */ private int querySkuDetails(String itemType, IabInventory inv, List<String> skus) throws RemoteException, JSONException { SoomlaUtils.LogDebug(TAG, "Querying SKU details."); // a list here is a bug no matter what, there is no point in // querying duplicates, and it can only create other bugs // on top of degrading performance // however, we need a subList later for chunks, so just // make the list through a Set 'filter' Set<String> skuSet = new HashSet<String>(skus); ArrayList<String> skuList = new ArrayList<String>(skuSet); if (skuList.size() == 0) { SoomlaUtils.LogDebug(TAG, "queryPrices: nothing to do because there are no SKUs."); return IabResult.BILLING_RESPONSE_RESULT_OK; } // see: http://stackoverflow.com/a/21080893/1469004 int chunkIndex = 1; while (skuList.size() > 0) { ArrayList<String> skuSubList = new ArrayList<String>( skuList.subList(0, Math.min(SKU_QUERY_MAX_CHUNK_SIZE, skuList.size()))); skuList.removeAll(skuSubList); final int chunkResponse = querySkuDetailsChunk(itemType, inv, skuSubList); if (chunkResponse != IabResult.BILLING_RESPONSE_RESULT_OK) { // todo: TBD skip chunk or abort? // for now aborting at that point SoomlaUtils.LogDebug(TAG, String.format("querySkuDetails[chunk=%d] failed: %s", chunkIndex, IabResult.getResponseDesc(chunkResponse))); return chunkResponse; // ABORT } chunkIndex++; } return IabResult.BILLING_RESPONSE_RESULT_OK; }
From source file:de.tap.easy_xkcd.Activities.SearchResultsActivity.java
private String getPreview(String query, String transcript) { String firstWord = query.split(" ")[0].toLowerCase(); transcript = transcript.replace(".", ". ").replace("?", "? ").replace("]]", " ").replace("[[", " ") .replace("{{", " ").replace("}}", " "); ArrayList<String> words = new ArrayList<>(Arrays.asList(transcript.toLowerCase().split(" "))); int i = 0;/*from w ww . ja va2 s .co m*/ boolean found = false; while (!found && i < words.size()) { if (query.length() < 5) { found = words.get(i).matches(".*\\b" + firstWord + "\\b.*"); } else { found = words.get(i).contains(firstWord); } if (!found) i++; } int start = i - 6; int end = i + 6; if (i < 6) start = 0; if (words.size() - i < 6) end = words.size(); StringBuilder sb = new StringBuilder(); for (String s : words.subList(start, end)) { sb.append(s); sb.append(" "); } String s = sb.toString(); return "..." + s.replace(query, "<b>" + query + "</b>") + "..."; }
From source file:com.bouncestorage.swiftproxy.v1.AccountResource.java
@GET public Response getAccount(@NotNull @PathParam("account") String account, @QueryParam("limit") Optional<Integer> limit, @QueryParam("marker") Optional<String> marker, @QueryParam("end_marker") Optional<String> endMarker, @QueryParam("format") Optional<String> format, @QueryParam("prefix") Optional<String> prefix, @QueryParam("delimiter") Optional<String> delimiter, @HeaderParam("X-Auth-Token") String authToken, @HeaderParam("X-Newest") @DefaultValue("false") boolean newest, @HeaderParam("Accept") Optional<String> accept) { delimiter.ifPresent(x -> logger.info("delimiter not supported yet")); BlobStore blobStore = getBlobStore(authToken).get(); ArrayList<ContainerEntry> entries = blobStore.list().stream().map(StorageMetadata::getName) .filter(name -> marker.map(m -> name.compareTo(m) > 0).orElse(true)) .filter(name -> endMarker.map(m -> name.compareTo(m) < 0).orElse(true)) .filter(name -> prefix.map(name::startsWith).orElse(true)).map(ContainerEntry::new) .collect(Collectors.toCollection(ArrayList::new)); MediaType formatType;//from w w w .ja va 2 s. c o m if (format.isPresent()) { formatType = BounceResourceConfig.getMediaType(format.get()); } else if (accept.isPresent()) { formatType = MediaType.valueOf(accept.get()); } else { formatType = MediaType.TEXT_PLAIN_TYPE; } if (blobStore.getContext().unwrap().getId().equals("transient")) { entries.sort((a, b) -> a.getName().compareTo(b.getName())); } long count = entries.size(); limit.ifPresent((max) -> { if (entries.size() > max) { entries.subList(max, entries.size()).clear(); } }); Account root = new Account(); root.name = account; root.container = entries; return output(root, entries, formatType).header("X-Account-Container-Count", count) .header("X-Account-Object-Count", -1).header("X-Account-Bytes-Used", -1).header("X-Timestamp", -1) .header("X-Trans-Id", -1).header("Accept-Ranges", "bytes").build(); }
From source file:org.eurekastreams.server.persistence.mappers.cache.MemcachedCache.java
/** * {@inheritDoc}/*from w w w . ja v a2s.c o m*/ */ public ArrayList<Long> getList(final String inKey, final int inMaximumEntries) { // This is how we modify a list when we find one in the cache. CASMutation<Object> mutation = new CASMutation<Object>() { // This is only invoked when a value actually exists. public Object getNewValue(final Object current) { // retrieve the list from the bytes stored in memcache ArrayList<Long> toReturn = new ArrayList<Long>(); try { toReturn = getListFromBytes(current); } catch (IOException e) { // problem getting the key .. return a null so the client goes // to the database log.error("Unable to retrieve LIST key " + inKey + " from memcached. Exception " + e.getMessage()); toReturn = null; } // check list size and trim if necessary if (toReturn != null && toReturn.size() > inMaximumEntries) { ArrayList<Long> trimmed = (ArrayList<Long>) toReturn.subList(0, inMaximumEntries - 1); // set the trimmed list back to memcached toReturn = trimmed; if (log.isInfoEnabled()) { log.info("Trimming list " + inKey + " to size of " + inMaximumEntries); } } try { return getBytesFromList(toReturn); } catch (IOException e) { // CAS timeout exceeded, return null because nothing was // stored in cache. log.error("Error in getList in getBytesFromList. Key " + inKey + " Exception " + e.toString()); return null; } } }; // The mutator who'll do all the low-level stuff. SerializingTranscoder transcoder = new SerializingTranscoder(); CASMutator<Object> mutator = new CASMutator<Object>(client, transcoder); // This returns whatever value was successfully stored within the // cache -- either the initial list as above, or a mutated existing // one try { // The initial value -- only used when there's no list stored under // the key. byte[] initialValue = null; return getListFromBytes(mutator.cas(inKey, initialValue, MAX_EXPIRATION_TIME, mutation)); } catch (Exception e) { // error, return null because nothing was stored in cache. log.error("Error in getList, general exception. Key " + inKey + " Exception " + e.toString()); return null; } }
From source file:com.hadoopvietnam.cache.memcached.MemcachedCache.java
/** * {@inheritDoc}//from w ww.jav a2 s .c o m */ public ArrayList<Long> getList(final String inKey, final int inMaximumEntries) { // This is how we modify a list when we find one in the cache. CASMutation<Object> mutation = new CASMutation<Object>() { // This is only invoked when a value actually exists. public Object getNewValue(final Object current) { // retrieve the list from the bytes stored in memcache ArrayList<Long> toReturn = new ArrayList<Long>(); try { toReturn = getListFromBytes(current); } catch (IOException e) { // problem getting the key .. return a null so the client goes // to the database log.error("Unable to retrieve LIST key " + inKey + " from memcached. Exception " + e.getMessage()); toReturn = null; } // check list size and trim if necessary if (toReturn != null && toReturn.size() > inMaximumEntries) { ArrayList<Long> trimmed = (ArrayList<Long>) toReturn.subList(0, inMaximumEntries - 1); // set the trimmed list back to memcached toReturn = trimmed; if (log.isInfoEnabled()) { log.info("Trimming list " + inKey + " to size of " + inMaximumEntries); } } try { return getBytesFromList(toReturn); } catch (IOException e) { // CAS timeout exceeded, return null because nothing was // stored in cache. log.error("Error in getList in getBytesFromList. Key " + inKey + " Exception " + e.toString()); return null; } } }; // The mutator who'll do all the low-level stuff. SerializingTranscoder transcoder = new SerializingTranscoder(); CASMutator<Object> mutator = new CASMutator<Object>(client, transcoder); // This returns whatever value was successfully stored within the // cache -- either the initial list as above, or a mutated existing // one try { // The initial value -- only used when there's no list stored under // the key. byte[] initialValue = null; return getListFromBytes(mutator.cas(inKey, initialValue, MAX_EXPIRATION_TIME, mutation)); } catch (Exception e) { // error, return null because nothing was stored in cache. log.error("Error in getList, general exception. Key " + inKey + " Exception " + e.toString()); return null; } }
From source file:org.eurekastreams.server.action.execution.stream.GetStreamsUserIsFollowingExecution.java
@Override public PagedSet<StreamDTO> execute(final PrincipalActionContext inActionContext) throws ExecutionException { GetStreamsUserIsFollowingRequest request = (GetStreamsUserIsFollowingRequest) inActionContext.getParams(); Long start = System.currentTimeMillis(); Long userId = getPersonIdByAccountIdMapper.execute(request.getAccountId()); log.debug("Lookup requested user id time: " + (System.currentTimeMillis() - start) + "(ms)."); Long currentUserId = inActionContext.getPrincipal().getId(); ArrayList<StreamDTO> results = new ArrayList<StreamDTO>(); PagedSet<StreamDTO> pagedResults = new PagedSet<StreamDTO>(); // get person/group ModelViews, which implement StreamDTO, and add to results; start = System.currentTimeMillis(); results.addAll(personModelViewsMapper.execute(personIdsUserIsFollowingMapper.execute(userId))); results.addAll(groupModelViewsMapper.execute(groupIdsUserIsFollowingMapper.execute(userId))); log.debug("Data retrieval time: " + (System.currentTimeMillis() - start) + "(ms)."); // if no results, short-circuit here. if (results.isEmpty()) { return pagedResults; }/* w ww.j a v a 2 s . co m*/ // sort results; start = System.currentTimeMillis(); Collections.sort(results, STREAMDTO_DISPLAYNAME_COMPARATOR); log.debug("Data sort time:" + (System.currentTimeMillis() - start) + "(ms)."); // set up PagedSet result and return. int total = results.size(); int startIndex = request.getStartIndex(); int endIndex = request.getEndIndex() > results.size() ? results.size() : request.getEndIndex() + 1; ArrayList<StreamDTO> trimmedResults = new ArrayList<StreamDTO>(results.subList(startIndex, endIndex)); start = System.currentTimeMillis(); followerStatusPopulator.execute(currentUserId, trimmedResults, FollowerStatus.NOTFOLLOWING); log.debug("Populate follower status time: " + (System.currentTimeMillis() - start) + "(ms)."); pagedResults.setFromIndex(startIndex); pagedResults.setToIndex(endIndex); pagedResults.setTotal(total); pagedResults.setPagedSet(trimmedResults); return pagedResults; }
From source file:org.sakaiproject.tool.assessment.ui.bean.evaluation.QuestionScoresBean.java
protected void init() { defaultSearchString = ContextUtil.getLocalizedString( "org.sakaiproject.tool.assessment.bundle.EvaluationMessages", "search_default_student_search_string"); if (searchString == null) { searchString = defaultSearchString; }/*ww w . j a va2 s . c o m*/ // Get allAgents only at the first time if (allAgents == null) { allAgents = getAllAgents(); } ArrayList matchingAgents; if (isFilteredSearch()) { matchingAgents = findMatchingAgents(searchString); } else { matchingAgents = allAgents; } scoreDataRows = matchingAgents.size(); ArrayList newAgents = null; if (maxDisplayedScoreRows == 0) { newAgents = matchingAgents; } else { int nextPageRow = Math.min(firstScoreRow + maxDisplayedScoreRows, scoreDataRows); newAgents = new ArrayList(matchingAgents.subList(firstScoreRow, nextPageRow)); log.debug("init(): subList " + firstScoreRow + ", " + nextPageRow); } agents = newAgents; }
From source file:org.jahia.services.usermanager.ldap.LDAPUserGroupProvider.java
@Override public List<String> searchUsers(final Properties searchCriteria, long offset, long limit) { if (searchCriteria.containsKey("username") && searchCriteria.size() == 1 && !searchCriteria.getProperty("username").contains("*")) { try {//from w w w .j a va2 s . co m JahiaUser user = getUser((String) searchCriteria.get("username")); return Arrays.asList(user.getUsername()); } catch (UserNotFoundException e) { return Collections.emptyList(); } } final ContainerCriteria query = buildUserQuery(searchCriteria); if (query == null) { return Collections.emptyList(); } final UsersNameClassPairCallbackHandler searchNameClassPairCallbackHandler = new UsersNameClassPairCallbackHandler(); long currentTimeMillis = System.currentTimeMillis(); ldapTemplateWrapper.execute(new BaseLdapActionCallback<Object>(externalUserGroupService, key) { @Override public Object doInLdap(LdapTemplate ldapTemplate) { ldapTemplate.search(query, searchNameClassPairCallbackHandler); return null; } }); logger.debug("Search users for {} in {} ms", searchCriteria, System.currentTimeMillis() - currentTimeMillis); ArrayList<String> l = new ArrayList<String>(searchNameClassPairCallbackHandler.getNames()); return l.subList(Math.min((int) offset, l.size()), limit < 0 ? l.size() : Math.min((int) (offset + limit), l.size())); }
From source file:jp.surbiton.billing_utilities.IabHelper.java
int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus) throws RemoteException, JSONException { logDebug("Querying SKU details."); ArrayList<String> skuList = new ArrayList<String>(); skuList.addAll(inv.getAllOwnedSkus(itemType)); if (moreSkus != null) { for (String sku : moreSkus) { if (!skuList.contains(sku)) { skuList.add(sku);// w w w . ja v a2 s . c o m } } } if (skuList.size() == 0) { logDebug("queryPrices: nothing to do because there are no SKUs."); return BILLING_RESPONSE_RESULT_OK; } while (skuList.size() > 0) { ArrayList<String> skuSubList = new ArrayList<String>(skuList.subList(0, Math.min(19, skuList.size()))); skuList.removeAll(skuSubList); Bundle querySkus = new Bundle(); querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuSubList); Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(), itemType, querySkus); if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) { int response = getResponseCodeFromBundle(skuDetails); if (response != BILLING_RESPONSE_RESULT_OK) { logDebug("getSkuDetails() failed: " + getResponseDesc(response)); return response; } else { logError("getSkuDetails() returned a bundle with neither an error nor a detail list."); return IABHELPER_BAD_RESPONSE; } } ArrayList<String> responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST); for (String thisResponse : responseList) { SkuDetails d = new SkuDetails(itemType, thisResponse); logDebug("Got sku details: " + d); inv.addSkuDetails(d); } } return BILLING_RESPONSE_RESULT_OK; }