Java Code Examples for java.util.List#subList()

The following examples show how to use java.util.List#subList() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CronParser.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Build possible cron expressions from definitions. One is built for sure. A second one may be build if last field is optional.
 *
 * @param cronDefinition - cron definition instance
 */
private void buildPossibleExpressions(final CronDefinition cronDefinition) {
    final List<CronParserField> sortedExpression = cronDefinition.getFieldDefinitions().stream()
            .map(this::toCronParserField)
            .sorted(CronParserField.createFieldTypeComparator())
            .collect(Collectors.toList());

    List<CronParserField> tempExpression = sortedExpression;

    while(lastFieldIsOptional(tempExpression)) {
        int expressionLength = tempExpression.size() - 1;
        ArrayList<CronParserField> possibleExpression = new ArrayList<>(tempExpression.subList(0, expressionLength));

        expressions.put(expressionLength, possibleExpression);
        tempExpression = possibleExpression;
    }

    expressions.put(sortedExpression.size(), sortedExpression);
}
 
Example 2
Source File: IReductionOpportunityFinder.java    From graphicsfuzz with Apache License 2.0 6 votes vote down vote up
static IReductionOpportunityFinder<SimplifyExprReductionOpportunity>
    largestExprToConstantFinder(int maxOpportunities) {
  return new IReductionOpportunityFinder<SimplifyExprReductionOpportunity>() {
    @Override
    public List<SimplifyExprReductionOpportunity> findOpportunities(
        ShaderJob shaderJob,
        ReducerContext context) {
      List<SimplifyExprReductionOpportunity> ops =
          exprToConstantFinder().findOpportunities(shaderJob,
          context);
      ops.sort(Comparator.comparingInt(
          SimplifyExprReductionOpportunity::getNumRemovableNodes).reversed());
      return ops.subList(0, Math.min(ops.size(), maxOpportunities));
    }

    @Override
    public String getName() {
      return "largestExprToConstant";
    }
  };
}
 
Example 3
Source File: FunctionCallExpression.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Override
public GroovyExpression copy(List<GroovyExpression> newChildren) {

    if (getCaller() == null) {
        return new FunctionCallExpression(getType(), functionName, newChildren);
    }

    GroovyExpression newTarget = newChildren.get(0);
    List<GroovyExpression> args = null;
    if (newChildren.size() > 1) {
        args = newChildren.subList(1, newChildren.size());
    } else {
        args = Collections.emptyList();
    }
    return new FunctionCallExpression(getType(), newTarget, functionName, args);

}
 
Example 4
Source File: Solution.java    From LeetCode-Java with Apache License 2.0 6 votes vote down vote up
/**
 * bfs
 * @param root
 * @return
 */
public List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> ret = new ArrayList<>();
    if(root==null)
        return ret;

    TreeNode cur = root;
    List<TreeNode> q = new ArrayList<>();
    q.add(cur);
    while(!q.isEmpty()) {
        int l = q.size();
        List<Integer> currentLevel = new ArrayList<>();
        for(int i=0; i<l; i++) {
            cur = q.get(i);
            currentLevel.add(cur.val);
            if(cur.left!=null) q.add(cur.left);
            if(cur.right!=null) q.add(cur.right);
        }
        ret.add(currentLevel);
        q = q.subList(l, q.size());  // similar API as python
    }
    return ret;
}
 
Example 5
Source File: GeneticOptimizerApp.java    From rheem with Apache License 2.0 6 votes vote down vote up
private Tuple<Integer, List<Individual>> superOptimize(
        int numTribes,
        List<Individual> individuals,
        Collection<PartialExecution> partialExecutions,
        int currentGeneration,
        int maxGenerations,
        int maxStableGenerations,
        double minFitness,
        long stopMillis) {

    int individualsPerTribe = (individuals.size() + numTribes - 1) / numTribes;
    List<Individual> superpopulation = new ArrayList<>(individuals.size() * numTribes);
    int maxGeneration = 0;
    for (int i = 0; i < numTribes; i++) {
        final Tuple<Integer, List<Individual>> population = this.optimize(
                individuals, partialExecutions, currentGeneration, maxGenerations, maxStableGenerations, minFitness, stopMillis
        );
        maxGeneration = Math.max(maxGeneration, population.getField0());
        superpopulation.addAll(population.getField1().subList(0, individualsPerTribe));
    }
    superpopulation.sort(Individual.fitnessComparator);
    return new Tuple<>(maxGeneration, superpopulation.subList(0, individuals.size()));
}
 
Example 6
Source File: TestStopFilter.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Check that the positions of the terms in a document keep into account the fact
 * that some of the words were filtered by two StopwordFilters concatenated together.
 */
public void testTokenPositionsWithConcatenatedStopwordFilters() throws IOException {
  // at least 1 token
  final int numberOfTokens = random().nextInt(MAX_NUMBER_OF_TOKENS-1)+1;
  StringBuilder sb = new StringBuilder();
  List<String> stopwords = new ArrayList<>(numberOfTokens);
  List<Integer> stopwordPositions = new ArrayList<>();
  generateTestSetWithStopwordsAndStopwordPositions(numberOfTokens, sb, stopwords, stopwordPositions);

  // we want to make sure that concatenating two list of stopwords
  // produce the same results of using one unique list of stopwords.
  // So we first generate a list of stopwords:
  // e.g.: [a, b, c, d, e]
  // and then we split the list in two disjoint partitions
  // e.g. [a, c, e] [b, d]
  int partition = random().nextInt(stopwords.size());
  Collections.shuffle(stopwords, random());
  final List<String> stopwordsRandomPartition = stopwords.subList(0, partition);
  final Set<String> stopwordsRemaining = new HashSet<>(stopwords);
  stopwordsRemaining.removeAll(stopwordsRandomPartition); // remove the first partition from all the stopwords

  CharArraySet firstStopSet = StopFilter.makeStopSet(stopwordsRandomPartition);
  logStopwords("Stopwords-first", stopwordsRandomPartition);
  CharArraySet secondStopSet = StopFilter.makeStopSet(new ArrayList<>(stopwordsRemaining), false);
  logStopwords("Stopwords-second", stopwordsRemaining);

  Reader reader = new StringReader(sb.toString());
  final MockTokenizer in1 = new MockTokenizer(MockTokenizer.WHITESPACE, false);
  in1.setReader(reader);

  // Here we create a stopFilter with the stopwords in the first partition and then we
  // concatenate it with the stopFilter created with the stopwords in the second partition
  StopFilter stopFilter = new StopFilter(in1, firstStopSet); // first part of the set
  StopFilter concatenatedStopFilter = new StopFilter(stopFilter, secondStopSet); // two stop filters concatenated!

  // ... and finally we check that the positions of the filtered tokens matched using the concatenated
  // stopFilters match the positions of the filtered tokens using the unique original list of stopwords
  doTestStopwordsPositions(concatenatedStopFilter, stopwordPositions, numberOfTokens);
}
 
Example 7
Source File: ListDefaults.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testForEach() {
    @SuppressWarnings("unchecked")
    final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_SUPPLIERS, SIZE);
    for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
        final List<Integer> original = test.expected;
        final List<Integer> list = test.collection;

        try {
            list.forEach(null);
            fail("expected NPE not thrown");
        } catch (NullPointerException npe) {}
        CollectionAsserts.assertContents(list, original);

        final List<Integer> actual = new LinkedList<>();
        list.forEach(actual::add);
        CollectionAsserts.assertContents(actual, list);
        CollectionAsserts.assertContents(actual, original);

        if (original.size() > SUBLIST_SIZE) {
            final List<Integer> subList = original.subList(SUBLIST_FROM, SUBLIST_TO);
            final List<Integer> actualSubList = new LinkedList<>();
            subList.forEach(actualSubList::add);
            assertEquals(actualSubList.size(), SUBLIST_SIZE);
            for (int i = 0; i < SUBLIST_SIZE; i++) {
                assertEquals(actualSubList.get(i), original.get(i + SUBLIST_FROM));
            }
        }

        trimmedSubList(list, l -> {
                final List<Integer> a = new LinkedList<>();
                l.forEach(a::add);
                CollectionAsserts.assertContents(a, l);
            });
    }
}
 
Example 8
Source File: ListUtil.java    From domino-jna with Apache License 2.0 5 votes vote down vote up
/**
 * Method to return a sublist from a list based on the start index <code>start</code> and
 * the number of entries to return <code>count</code>. In constrast to {@link List#subList(int, int)},
 * this implementation is forgiving in case <code>start</code> or <code>start+count</code> is higher than
 * the actual number of list entries.
 * 
 * @param <T> list type
 * @param list list
 * @param start start index
 * @param count number of entries to return
 * @return sublist, backed by the original list; see {@link List#subList(int, int)} for details
 */
public static <T> List<T> subListChecked(List<T> list, int start, int count) {
	if (start > list.size())
		return Collections.emptyList();
	else {
		long startLong = start;
		long countLong = count;
		//make sure we do not exceed Integer.MAX_VALUE
		long sum = Math.min(Integer.MAX_VALUE, startLong+countLong);
		
		return list.subList(start, Math.min(list.size(), (int) sum));
	}
}
 
Example 9
Source File: FabricSDKWrapper.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
private static void generateTbTransHashListPage(Integer pageIndex,
                                                Integer pageSize,
                                                ListPage<TbTransHash> tbTransHashListPage,
                                                List<TbTransHash> tbTransHashes,
                                                BlockInfo blockInfo) throws BrokerException {
    Integer transCount = blockInfo.getTransactionCount();

    if (pageIndex < 1 || (pageIndex - 1) * pageSize > transCount) {
        log.error("pageIndex error.");
        throw new BrokerException("pageIndex error.");
    }
    Integer transSize = (transCount <= pageIndex * pageSize) ? (transCount - ((pageIndex - 1) * pageSize)) : pageSize;
    Integer transIndexStart = (pageIndex - 1) * pageSize;


    Iterable<BlockInfo.EnvelopeInfo> envelopeInfos = blockInfo.getEnvelopeInfos();
    envelopeInfos.forEach(envelopeInfo -> {
        TbTransHash tbTransHash = new TbTransHash();
        tbTransHash.setCreateTime(DataTypeUtils.getTimestamp(envelopeInfo.getTimestamp()));
        tbTransHash.setBlockTimestamp(DataTypeUtils.getTimestamp(envelopeInfo.getTimestamp()));
        tbTransHash.setTransHash(envelopeInfo.getTransactionID());
        tbTransHash.setBlockNumber(BigInteger.valueOf(blockInfo.getBlockNumber()));
        tbTransHashes.add(tbTransHash);
    });

    if (tbTransHashes != null && !tbTransHashes.isEmpty()) {
        tbTransHashes.subList(transIndexStart, transSize + transIndexStart);
    }

    tbTransHashListPage.setPageSize(transSize);
    tbTransHashListPage.setTotal(transCount);
    tbTransHashListPage.setPageData(tbTransHashes);
}
 
Example 10
Source File: SubList.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "modifiable",
      expectedExceptions = ConcurrentModificationException.class)
public void testModClear(List<Integer> list, int from, int to) {
    List<Integer> subList = list.subList(from, to);
    list.add(42);
    subList.clear();
}
 
Example 11
Source File: ListDefaults.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testForEach() {
    @SuppressWarnings("unchecked")
    final CollectionSupplier<List<Integer>> supplier = new CollectionSupplier(LIST_SUPPLIERS, SIZE);
    for (final CollectionSupplier.TestCase<List<Integer>> test : supplier.get()) {
        final List<Integer> original = test.expected;
        final List<Integer> list = test.collection;

        try {
            list.forEach(null);
            fail("expected NPE not thrown");
        } catch (NullPointerException npe) {}
        CollectionAsserts.assertContents(list, original);

        final List<Integer> actual = new LinkedList<>();
        list.forEach(actual::add);
        CollectionAsserts.assertContents(actual, list);
        CollectionAsserts.assertContents(actual, original);

        if (original.size() > SUBLIST_SIZE) {
            final List<Integer> subList = original.subList(SUBLIST_FROM, SUBLIST_TO);
            final List<Integer> actualSubList = new LinkedList<>();
            subList.forEach(actualSubList::add);
            assertEquals(actualSubList.size(), SUBLIST_SIZE);
            for (int i = 0; i < SUBLIST_SIZE; i++) {
                assertEquals(actualSubList.get(i), original.get(i + SUBLIST_FROM));
            }
        }

        trimmedSubList(list, l -> {
                final List<Integer> a = new LinkedList<>();
                l.forEach(a::add);
                CollectionAsserts.assertContents(a, l);
            });
    }
}
 
Example 12
Source File: TSDataFileChain.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Optional<TSDataFileChain> openDirExisting(@NonNull TSDataScanDir scandir, long max_filesize) throws IOException {
    List<MetaData> files = scandir.getFiles();
    if (files.isEmpty())
        return Optional.empty();

    /* If the most recent file is upgradable, use that to append new records to. */
    Optional<MetaData> last = Optional.of(files.get(files.size() - 1))
            .filter((md) -> md.isUpgradable());
    if (last.isPresent())
        files = files.subList(0, files.size() - 1);
    return Optional.of(new TSDataFileChain(scandir.getDir(), last.map(MetaData::getFileName), files, max_filesize));
}
 
Example 13
Source File: CalendarPortletRunController.java    From olat with Apache License 2.0 5 votes vote down vote up
private List getMatchingEvents(final UserRequest ureq, final WindowControl wControl) {
    final Date startDate = new Date();
    final Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 7);
    final Date endDate = cal.getTime();
    List events = new ArrayList();
    CalendarWrapperCreator calendarWrapperCreator = CoreSpringFactory.getBean(CalendarWrapperCreator.class);
    final List calendars = calendarWrapperCreator.getListOfCalendarWrappers(ureq, wControl);
    calendars.addAll(calendarWrapperCreator.getListOfImportedCalendarWrappers(ureq));
    for (final Iterator iter = calendars.iterator(); iter.hasNext();) {
        final CalendarRenderWrapper calendarWrapper = (CalendarRenderWrapper) iter.next();
        final boolean readOnly = (calendarWrapper.getAccess() == CalendarRenderWrapper.ACCESS_READ_ONLY) && !calendarWrapper.isImported();
        final List eventsWithinPeriod = CalendarUtils.listEventsForPeriod(calendarWrapper.getCalendar(), startDate, endDate);
        for (final Iterator iterator = eventsWithinPeriod.iterator(); iterator.hasNext();) {
            final CalendarEntry event = (CalendarEntry) iterator.next();
            // skip non-public events
            if (readOnly && event.getClassification() != CalendarEntry.CLASS_PUBLIC) {
                continue;
            }
            events.add(event);
        }
    }
    // sort events
    Collections.sort(events, new Comparator() {
        @Override
        public int compare(final Object arg0, final Object arg1) {
            final Date begin0 = ((CalendarEntry) arg0).getBegin();
            final Date begin1 = ((CalendarEntry) arg1).getBegin();
            return begin0.compareTo(begin1);
        }
    });
    if (events.size() > MAX_EVENTS) {
        events = events.subList(0, MAX_EVENTS);
    }
    return events;
}
 
Example 14
Source File: SyntacticSequencerPDAProvider.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
protected List<ISynState> shortestPathTo(Iterator<RuleCall> stack, Predicate<ISynState> matches, boolean includeMatch) {
	List<ISynState> pathTo = new PdaUtil().shortestPathTo(getPathToTarget(), stack, matches);
	if (pathTo != null)
		return pathTo.subList(1, pathTo.size() - (includeMatch ? 0 : 1));
	return null;
}
 
Example 15
Source File: ASCIIGridDataInfo.java    From MeteoInfo with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public GridData getGridData_LonLat(int timeIdx, String varName, int levelIdx) {
    try {
        int xNum = this.getXDimension().getLength();
        int yNum = this.getYDimension().getLength();
        double[][] theData = new double[yNum][xNum];
        BufferedReader sr = new BufferedReader(new FileReader(new File(this.getFileName())));
        String[] dataArray;
        int i, j;
        String aLine;

        for (i = 0; i < 6; i++) {
            sr.readLine();
        }

        List<String> dataList = new ArrayList<>();
        int col = 0;
        do {
            aLine = sr.readLine();
            if (aLine == null) {
                break;
            }
            dataArray = aLine.trim().split("\\s+");
            dataList.addAll(Arrays.asList(dataArray));
            if (col == 0) {
                if (!MIMath.isNumeric(dataList.get(0))) {
                    aLine = sr.readLine();
                    dataArray = aLine.trim().split("\\s+");
                    dataList = Arrays.asList(dataArray);
                }
            }
            for (i = 0; i < 100; i++) {
                if (dataList.size() < xNum) {
                    aLine = sr.readLine();
                    if (aLine == null) {
                        break;
                    }
                    dataArray = aLine.trim().split("\\s+");
                    dataList.addAll(Arrays.asList(dataArray));
                } else {
                    break;
                }
            }
            for (i = 0; i < xNum; i++) {
                theData[col][i] = Double.parseDouble(dataList.get(i));
            }
            if (dataList.size() > xNum) {
                dataList = dataList.subList(xNum, dataList.size() - 1);
            } else {
                dataList = new ArrayList<>();
            }
            col += 1;
        } while (aLine != null);

        sr.close();

        double[][] newGridData = new double[yNum][xNum];
        for (i = 0; i < yNum; i++) {
            for (j = 0; j < xNum; j++) {
                newGridData[i][j] = theData[yNum - 1 - i][j];
            }
        }

        GridData aGridData = new GridData();
        aGridData.data = newGridData;
        aGridData.xArray = this.getXDimension().getValues();
        aGridData.yArray = this.getYDimension().getValues();
        aGridData.missingValue = this.getMissingValue();

        return aGridData;
    } catch (IOException ex) {
        Logger.getLogger(ASCIIGridDataInfo.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}
 
Example 16
Source File: KeycloakUserService.java    From camunda-bpm-identity-keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Requests users.
 * @param query the user query - not including a groupId criteria
 * @return list of matching users
 */
public List<User> requestUsersWithoutGroupId(KeycloakUserQuery query) {
	List<User> userList = new ArrayList<>();

	StringBuilder resultLogger = new StringBuilder();
	if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
		resultLogger.append("Keycloak user query results: [");
	}

	try {
		// get members of this group
		ResponseEntity<String> response = null;

		if (!StringUtils.isEmpty(query.getId())) {
			response = requestUserById(query.getId());
		} else {
			// Create user search filter
			String userFilter = createUserSearchFilter(query);
			response = restTemplate.exchange(keycloakConfiguration.getKeycloakAdminUrl() + "/users" + userFilter, HttpMethod.GET,
					keycloakContextProvider.createApiRequestEntity(), String.class);
		}
		if (!response.getStatusCode().equals(HttpStatus.OK)) {
			throw new IdentityProviderException(
					"Unable to read users from " + keycloakConfiguration.getKeycloakAdminUrl()
							+ ": HTTP status code " + response.getStatusCodeValue());
		}

		JsonArray searchResult = parseAsJsonArray(response.getBody());
		for (int i = 0; i < searchResult.size(); i++) {
			JsonObject keycloakUser = getJsonObjectAtIndex(searchResult, i);
			if (keycloakConfiguration.isUseEmailAsCamundaUserId() && 
					StringUtils.isEmpty(getJsonString(keycloakUser, "email"))) {
				continue;
			}
			if (keycloakConfiguration.isUseUsernameAsCamundaUserId() &&
					StringUtils.isEmpty(getJsonString(keycloakUser, "username"))) {
				continue;
			}

			UserEntity user = transformUser(keycloakUser);

			// client side check of further query filters
			// beware: looks like most attributes are treated as 'like' queries on Keycloak
			//         and must therefore be seen as a sort of pre-filter only
			if (!matches(query.getId(), user.getId())) continue;
			if (!matches(query.getEmail(), user.getEmail())) continue;
			if (!matches(query.getFirstName(), user.getFirstName())) continue;
			if (!matches(query.getLastName(), user.getLastName())) continue;
			if (!matches(query.getIds(), user.getId())) continue;
			if (!matchesLike(query.getEmailLike(), user.getEmail())) continue;
			if (!matchesLike(query.getFirstNameLike(), user.getFirstName())) continue;
			if (!matchesLike(query.getLastNameLike(), user.getLastName())) continue;
			
			if(isAuthenticatedUser(user) || isAuthorized(READ, USER, user.getId())) {
				userList.add(user);

				if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
					resultLogger.append(user);
					resultLogger.append(" based on ");
					resultLogger.append(keycloakUser.toString());
					resultLogger.append(", ");
				}
			}
		}

	} catch (RestClientException rce) {
		throw new IdentityProviderException("Unable to query users", rce);
	} catch (JsonException je) {
		throw new IdentityProviderException("Unable to query users", je);
	}

	if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
		resultLogger.append("]");
		KeycloakPluginLogger.INSTANCE.userQueryResult(resultLogger.toString());
	}

	// sort users according to query criteria
	if (query.getOrderingProperties().size() > 0) {
		userList.sort(new UserComparator(query.getOrderingProperties()));
	}
	
	// paging
	if ((query.getFirstResult() > 0) || (query.getMaxResults() < Integer.MAX_VALUE)) {
		userList = userList.subList(query.getFirstResult(), 
				Math.min(userList.size(), query.getFirstResult() + query.getMaxResults()));
	}
	
	return userList;
}
 
Example 17
Source File: BM25NBClassifier.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public List<ClassificationResult<BytesRef>> getClasses(String text, int max) throws IOException {
  List<ClassificationResult<BytesRef>> assignedClasses = assignClassNormalizedList(text);
  Collections.sort(assignedClasses);
  return assignedClasses.subList(0, max);
}
 
Example 18
Source File: NodeMaintenanceTask.java    From nuls-v2 with MIT License 4 votes vote down vote up
private List<Node> getNeedConnectNodes(NodeGroup nodeGroup, boolean isCross) {
    Collection<Node> connectedNodes = nodeGroup.getConnectedNodes(isCross);
    int maxOutCount = isCross ? nodeGroup.getMaxCrossOut() : nodeGroup.getMaxOut();
    if (connectedNodes.size() >= maxOutCount) {
        //进行种子节点的断链
        nodeGroup.stopConnectedSeeds(isCross);
        return null;
    }
    Collection<Node> canConnectNodes = nodeGroup.getCanConnectNodes(isCross);
    if (canConnectNodes.size() == 0) {
        return null;
    }
    List<Node> nodeList = new ArrayList<>(canConnectNodes);
    //   nodeList.removeAll(connectedNodes);
    for (int i = nodeList.size() - 1; i >= 0; i--) {
        Node node = nodeList.get(i);
        if (IpUtil.isSelf(node.getIp())) {
            nodeList.remove(node);
            LoggerUtil.logger(nodeGroup.getChainId()).info("move self Address={}", node.getId());
            if (isCross) {
                nodeGroup.getCrossNodeContainer().getCanConnectNodes().remove(node.getId());
                continue;
            } else {
                nodeGroup.getLocalNetNodeContainer().getCanConnectNodes().remove(node.getId());
                continue;
            }
        }
        if (node.getConnectStatus() == NodeConnectStatusEnum.CONNECTING) {
            LoggerUtil.COMMON_LOG.info("{} is in connecting", node.getId());
            nodeList.remove(node);
        }
    }

    //最大需要连接的数量 大于 可用连接数的时候,直接返回可用连接数,否则进行选择性返回
    int maxCount = maxOutCount - connectedNodes.size();
    if (nodeList.size() < maxCount) {
        return nodeList;
    }
    Collections.shuffle(nodeList);
    return nodeList.subList(0, maxCount);
}
 
Example 19
Source File: InAppBillingV3Vendor.java    From Cashier with Apache License 2.0 4 votes vote down vote up
private List<Product> getProductsWithType(List<String> skus, String type)
    throws RemoteException, ApiException {
  if (skus == null || TextUtils.isEmpty(type)) {
    throw new IllegalArgumentException("Given skus are null or type is empty/null");
  }

  throwIfUninitialized();
  log("Retrieving sku details for " + skus.size() + " " + type + " skus");
  if (!type.equals(PRODUCT_TYPE_ITEM) && !type.equals(PRODUCT_TYPE_SUBSCRIPTION)) {
    throw new IllegalArgumentException("Invalid product type " + type);
  }

  final List<Product> products = new ArrayList<>();
  for (int i = 0; i < skus.size(); i += 20) {
    final ArrayList<String> page = new ArrayList<>(skus.subList(i, Math.min(skus.size(), i + 20)));
    final Bundle skuQuery = new Bundle();
    skuQuery.putStringArrayList(REQUEST_SKU_DETAILS_ITEM_LIST, page);

    final Bundle skuDetails = api.getSkuDetails(type, skuQuery);
    final int response = getResponseCode(skuDetails);
    log("Got response: " + response);
    if (skuDetails == null) {
      continue;
    }

    if (response != BILLING_RESPONSE_RESULT_OK || !skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) {
      throw new ApiException(response);
    }

    final ArrayList<String> detailsList
        = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST);
    if (detailsList == null) continue;

    for (final String detail : detailsList) {
      log("Parsing sku details: " + detail);
      try {
        products.add(InAppBillingProduct.create(detail, type.equals(PRODUCT_TYPE_SUBSCRIPTION)));
      } catch (JSONException e) {
        log("Couldn't parse sku: " + detail);
      }
    }
  }

  return Collections.unmodifiableList(products);
}
 
Example 20
Source File: ThingUID.java    From smarthome with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Returns the bridge ids.
 *
 * @return list of bridge ids
 */
public List<String> getBridgeIds() {
    List<String> allSegments = getAllSegments();
    return allSegments.subList(2, allSegments.size() - 1);
}