Java 类org.apache.commons.collections4.ListUtils 实例源码

项目:scheduling    文件:TaskResultCreator.java   
private Map<String, byte[]> extractTaskResultsAndMergeIntoMap(SchedulerDBManager dbManager,
        EligibleTaskDescriptor eligibleTaskDescriptor, InternalJob job) {
    Map<String, byte[]> mergedVariables = new HashMap<>();

    int numberOfParentTasks = eligibleTaskDescriptor.getParents().size();
    List<TaskId> parentIds = new ArrayList<>(numberOfParentTasks);
    for (int i = 0; i < numberOfParentTasks; i++) {
        parentIds.add(eligibleTaskDescriptor.getParents().get(i).getTaskId());
    }

    // Batch fetching of parent tasks results
    Map<TaskId, TaskResult> taskResults = new HashMap<>();
    for (List<TaskId> parentsSubList : ListUtils.partition(new ArrayList<>(parentIds),
                                                           PASchedulerProperties.SCHEDULER_DB_FETCH_TASK_RESULTS_BATCH_SIZE.getValueAsInt())) {
        taskResults.putAll(dbManager.loadTasksResults(job.getId(), parentsSubList));
    }

    for (TaskResult taskResult : taskResults.values()) {
        if (taskResult.getPropagatedVariables() != null) {
            mergedVariables.putAll(taskResult.getPropagatedVariables());
        }
    }
    return mergedVariables;
}
项目:scheduling    文件:TestListenJobLogs.java   
public synchronized void waitForLoggingEvent(long timeout, String... expectedMessages)
        throws InterruptedException {
    List<String> expectedMessagesList = new ArrayList<>(expectedMessages.length);

    Collections.addAll(expectedMessagesList, expectedMessages);

    System.out.println("Waiting for logging events with messages: " + expectedMessagesList + " (" + name + ")");

    long endTime = System.currentTimeMillis() + timeout;
    while (!ListUtils.removeAll(expectedMessagesList, actualMessages).isEmpty()) {
        long waitTime = endTime - System.currentTimeMillis();
        if (waitTime > 0) {
            wait(100);
        } else {
            break;
        }
    }

    Assert.assertTrue("Didn't receive expected events, expected: " + expectedMessagesList + ", actual: " +
                      actualMessages, ListUtils.removeAll(expectedMessagesList, actualMessages).isEmpty());
    actualMessages.clear();
}
项目:metron    文件:DefaultProfileBuilder.java   
/**
 * Executes the expressions contained within the profile definition.
 * @param expressions A list of expressions to execute.
 * @param transientState Additional transient state provided to the expressions.
 * @param expressionType The type of expression; init, update, result.  Provides additional context if expression execution fails.
 * @return The result of executing each expression.
 */
private List<Object> execute(List<String> expressions, Map<String, Object> transientState, String expressionType) {
  List<Object> results = new ArrayList<>();

  for(String expr: ListUtils.emptyIfNull(expressions)) {
    try {
      // execute an expression
      Object result = executor.execute(expr, transientState, Object.class);
      results.add(result);

    } catch (Throwable e) {

      // in-scope variables = persistent state maintained by the profiler + the transient state
      Set<String> variablesInScope = new HashSet<>();
      variablesInScope.addAll(transientState.keySet());
      variablesInScope.addAll(executor.getState().keySet());

      String msg = format("Bad '%s' expression: error='%s', expr='%s', profile='%s', entity='%s', variables-available='%s'",
              expressionType, e.getMessage(), expr, profileName, entity, variablesInScope);
      LOG.error(msg, e);
      throw new ParseException(msg, e);
    }
  }

  return results;
}
项目:find    文件:ComparisonController.java   
@SuppressWarnings("MethodWithTooManyParameters")
@RequestMapping(value = RESULTS_PATH, method = RequestMethod.GET)
public Documents<R> getResults(
        @RequestParam(STATE_MATCH_PARAM) final List<String> stateMatchIds,
        @RequestParam(value = STATE_DONT_MATCH_PARAM, required = false) final List<String> stateDontMatchIds,
        @RequestParam(value = TEXT_PARAM, required = false, defaultValue = "*") final String text,
        @RequestParam(value = FIELD_TEXT_PARAM, defaultValue = "") final String fieldText,
        @RequestParam(value = RESULTS_START_PARAM, required = false, defaultValue = "1") final int resultsStart,
        @RequestParam(MAX_RESULTS_PARAM) final int maxResults,
        @RequestParam(SUMMARY_PARAM) final String summary,
        @RequestParam(value = SORT_PARAM, required = false) final String sort,
        @RequestParam(value = HIGHLIGHT_PARAM, required = false, defaultValue = "true") final boolean highlight,
        @RequestParam(value = PROMOTIONS, defaultValue = "false") final boolean promotions
) throws E {
    return comparisonService.getResults(
            stateMatchIds,
            ListUtils.emptyIfNull(stateDontMatchIds),
            text,
            fieldText,
            resultsStart,
            maxResults,
            summary,
            sort,
            highlight
    );
}
项目:syncope    文件:Relationships.java   
public Relationships(final AnyWrapper<?> modelObject, final PageReference pageRef) {
    super();
    add(new Label("title", new ResourceModel("any.relationships")));

    if (modelObject instanceof UserWrapper
            && UserWrapper.class.cast(modelObject).getPreviousUserTO() != null
            && !ListUtils.isEqualList(
                    UserWrapper.class.cast(modelObject).getInnerObject().getRelationships(),
                    UserWrapper.class.cast(modelObject).getPreviousUserTO().getRelationships())) {
        add(new LabelInfo("changed", StringUtils.EMPTY));
    } else {
        add(new Label("changed", StringUtils.EMPTY));
    }

    this.anyTO = modelObject.getInnerObject();
    this.pageRef = pageRef;

    // ------------------------
    // Existing relationships
    // ------------------------
    add(getViewFragment().setRenderBodyOnly(true));
    // ------------------------ 
}
项目:gatk    文件:CoveragePerContigCollection.java   
public CoveragePerContigCollection(final LocatableMetadata metadata,
                                   final List<CoveragePerContig> coveragePerContigs,
                                   final List<String> contigs) {
    super(
            metadata,
            coveragePerContigs,
            new TableColumnCollection(ListUtils.union(Collections.singletonList(SAMPLE_NAME_TABLE_COLUMN), contigs)),
            dataLine -> new CoveragePerContig(
                    dataLine.get(SAMPLE_NAME_TABLE_COLUMN),
                    contigs.stream().collect(Collectors.toMap(
                            Function.identity(),
                            dataLine::getInt,
                            (u, v) -> {
                                throw new GATKException.ShouldNeverReachHereException("Cannot have duplicate contigs.");
                            },   //contigs should already be distinct
                            LinkedHashMap::new))),
            (coveragePerContig, dataLine) -> {
                dataLine.append(coveragePerContig.getSampleName());
                contigs.stream().map(coveragePerContig::getCoverage).forEach(dataLine::append);
            });
}
项目:ameba    文件:DataViewMessageBodyWriter.java   
/**
 * {@inheritDoc}
 */
@Override
public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
                           final MediaType mediaType) {
    String[] p;
    return !dataViewDisabled
            && -1 != ListUtils.indexOf(requestProvider.get().getAcceptableMediaTypes(),
            this::isSupportMediaType)
            && ((p = TemplateHelper.getProduces(annotations)) == null
            || -1 != ArrayUtils.indexOf(p,
            (Predicate<String>) stringType -> {
                if (stringType.equals(MediaType.WILDCARD)) return true;

                MediaType mediaType1 = MediaType.valueOf(stringType);
                return isSupportMediaType(mediaType1);
            }));
}
项目:Amphitheatre    文件:GetFilesTask.java   
@Override
protected void onPostExecute(List<SmbFile> files) {
    try {
        final int cpuCount = Runtime.getRuntime().availableProcessors();
        final int maxPoolSize = cpuCount * 2 + 1;
        final int partitionSize = files.size() < maxPoolSize ? files.size() : (files.size() / maxPoolSize);

        List<List<SmbFile>> subSets = ListUtils.partition(files, partitionSize);

        mNumOfSets = subSets.size();

        for (List<SmbFile> subSet : subSets) {
            if (mIsMovie) {
                new DownloadMovieTask(mContext, mConfig, subSet, this)
                        .executeOnExecutor(THREAD_POOL_EXECUTOR);
            } else {
                new DownloadTvShowTask(mContext, mConfig, subSet, this)
                        .executeOnExecutor(THREAD_POOL_EXECUTOR);
            }
        }
    } catch (Exception e) {
        if (mCallback != null) {
            mCallback.failure();
        }
    }
}
项目:sample-acmegifts    文件:Occasion.java   
public static JsonArray listToJsonArray(List<Contribution> contributions) {
  String method = "listToJsonArray";
  logger.entering(clazz, method);

  JsonArrayBuilder contributionsBuilder = Json.createArrayBuilder();
  for (Contribution contribution : ListUtils.emptyIfNull(contributions)) {
    contributionsBuilder.add(contribution.toJson());
  }
  JsonArray contributionsOut = contributionsBuilder.build();

  logger.exiting(clazz, method, contributionsOut);
  return contributionsOut;
}
项目:sample-acmegifts    文件:Occasion.java   
public static BasicDBList listToDBList(List<Contribution> contributions) {
  String method = "listToString";
  logger.entering(clazz, method);
  BasicDBList dbl = new BasicDBList();
  for (Contribution contribution : ListUtils.emptyIfNull(contributions)) {
    dbl.add(contribution.toDbo());
  }
  logger.exiting(clazz, method);
  return dbl;
}
项目:sample-acmegifts    文件:Occasion.java   
public static String listToString(List<Contribution> contributions) {
  String method = "listToString";
  logger.entering(clazz, method);
  StringBuilder sb = new StringBuilder();
  for (Contribution contribution : ListUtils.emptyIfNull(contributions)) {
    sb.append(contribution.toString());
  }
  String str = sb.toString();
  logger.exiting(clazz, method, str);
  return str;
}
项目:sample-acmegifts    文件:Occasion.java   
public static List<Contribution> dbListToList(BasicDBList dbl) {
  String method = "dbListToList";
  logger.entering(clazz, method, dbl);

  List<Contribution> contributions = new ArrayList<>();
  for (Object dbo : ListUtils.emptyIfNull(dbl)) {
    contributions.add(new Contribution((BasicDBObject) dbo));
  }

  logger.exiting(clazz, method, listToString(contributions));
  return contributions;
}
项目:sample-acmegifts    文件:Occasion.java   
public static boolean listsEqual(List<Contribution> list1, List<Contribution> list2) {
  for (Contribution p1 : ListUtils.emptyIfNull(list1)) {
    if (!list2.contains(p1)) return false;
  }
  for (Contribution p2 : ListUtils.emptyIfNull(list2)) {
    if (!list1.contains(p2)) return false;
  }
  return true;
}
项目:sample-acmegifts    文件:Occasion.java   
public static BasicDBList jsonArrayToDbList(JsonArray jsonArray) {
  String method = "jsonArrayToDbList";
  logger.entering(clazz, method, jsonArray);

  BasicDBList dbl = new BasicDBList();
  for (JsonValue json : ListUtils.emptyIfNull(jsonArray)) {
    BasicDBObject dbo = new Occasion((JsonObject) json).toDbo();
    dbl.add(dbo);
  }

  logger.exiting(clazz, method, dbl);
  return dbl;
}
项目:sample-acmegifts    文件:Occasion.java   
public static JsonArray dboListToJsonArray(List<DBObject> dboList) {
  String method = "dboListToJsonArray";
  logger.entering(clazz, method, dboList);

  JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
  for (Object dbo : ListUtils.emptyIfNull(dboList)) {
    JsonObject json = new Occasion((DBObject) dbo).toJson();
    arrayBuilder.add(json);
  }
  JsonArray returnArray = arrayBuilder.build();

  logger.exiting(clazz, method, returnArray);
  return returnArray;
}
项目:HCFCore    文件:SetUniqueList.java   
/**
 * {@inheritDoc}
 * <p>
 * NOTE: from 4.0, an unmodifiable list will be returned, as changes to the
 * subList can invalidate the parent list.
 */
@Override
public List<E> subList(final int fromIndex, final int toIndex) {
    final List<E> superSubList = super.subList(fromIndex, toIndex);
    final Set<E> subSet = createSetBasedOnList(set, superSubList);
    return ListUtils.unmodifiableList(new SetUniqueList<E>(superSubList, subSet));
}
项目:HCFCore    文件:AbstractListValuedMap.java   
@Override
public V remove(int index) {
    final List<V> list = ListUtils.emptyIfNull(getMapping());
    V value = list.remove(index);
    if (list.isEmpty()) {
        AbstractListValuedMap.this.remove(key);
    }
    return value;
}
项目:HCFCore    文件:AbstractListValuedMap.java   
@Override
public boolean equals(Object other) {
    final List<V> list = getMapping();
    if (list == null) {
        return Collections.emptyList().equals(other);
    }
    if (!(other instanceof List)) {
        return false;
    }
    List<?> otherList = (List<?>) other;
    return ListUtils.isEqualList(list, otherList);
}
项目:HCFCore    文件:SetUniqueList.java   
/**
 * {@inheritDoc}
 * <p>
 * NOTE: from 4.0, an unmodifiable list will be returned, as changes to the
 * subList can invalidate the parent list.
 */
@Override
public List<E> subList(final int fromIndex, final int toIndex) {
    final List<E> superSubList = super.subList(fromIndex, toIndex);
    final Set<E> subSet = createSetBasedOnList(set, superSubList);
    return ListUtils.unmodifiableList(new SetUniqueList<E>(superSubList, subSet));
}
项目:HCFCore    文件:AbstractListValuedMap.java   
@Override
public V remove(int index) {
    final List<V> list = ListUtils.emptyIfNull(getMapping());
    V value = list.remove(index);
    if (list.isEmpty()) {
        AbstractListValuedMap.this.remove(key);
    }
    return value;
}
项目:HCFCore    文件:AbstractListValuedMap.java   
@Override
public boolean equals(Object other) {
    final List<V> list = getMapping();
    if (list == null) {
        return Collections.emptyList().equals(other);
    }
    if (!(other instanceof List)) {
        return false;
    }
    List<?> otherList = (List<?>) other;
    return ListUtils.isEqualList(list, otherList);
}
项目:smarti    文件:ConversationCloudSync.java   
public SyncData sync(ConversytionSyncCallback callback, Date since) {
    long start = System.currentTimeMillis();
    UpdatedConversationIds updated = conversationRepository.updatedSince(since);
    Date lastUpdate = updated.getLastModified();
    AtomicInteger count = new AtomicInteger();
    //load in batches of 10 from the MongoDB
    ListUtils.partition(updated.ids(), 10).forEach(batch -> {
        conversationRepository.findAll(batch).forEach(c -> {
                callback.updateConversation(c, lastUpdate);
                count.incrementAndGet();
            });
    });
    return new SyncData(lastUpdate, count.get(), (int)(System.currentTimeMillis()-start));

}
项目:JumperSumo    文件:Finder.java   
/**
 * This method joins commands list in one List.
 *
 * @param params List to join.
 * @return List of all commands.
 */
public List<String> joinListCommands(List<String>... params) {

    List<String> result = new ArrayList<String>();
    if (params.length != 0) {
        for (int i = 0; i < params.length; i++)
            result = ListUtils.union(result, params[i]);
    }

    return result;
}
项目:TomboloDigitalConnector    文件:FractionOfTotalField.java   
private ValueWithTimestamp getValue(Subject subject) throws IncomputableFieldException {
    List<TimedValue> dividendValues = getLatestTimedValuesForSubjectAndAttributes(subject, dividendAttributes);
    List<TimedValue> divisorValues = getLatestTimedValuesForSubjectAndAttributes(subject, Collections.singletonList(divisorAttribute));

    Double dividend = sumTimedValues(dividendValues);
    Double divisor = sumTimedValues(divisorValues);
    LocalDateTime latestTimeStamp = getMostRecentTimestampForTimedValues(ListUtils.union(dividendValues, divisorValues));

    if (0 == divisor) {
        throw new IncomputableFieldException("Cannot divide by zero");
    }

    return new ValueWithTimestamp(dividend/divisor, latestTimeStamp);
}
项目:TomboloDigitalConnector    文件:FractionOfTotalField.java   
private List<TimedValue> getLatestTimedValuesForSubjectAndAttributes(Subject subject, List<AttributeMatcher> attributeMatchers) throws IncomputableFieldException {
    List<Attribute> attributes = getAttributes(attributeMatchers);
    List<TimedValue> timedValues = TimedValueUtils.getLatestBySubjectAndAttributes(subject, attributes);

    // We check for and throw on missing timedValues with some info on what they are
    if (timedValues.size() != attributeMatchers.size()) {
        List<Attribute> presentAttributes = timedValues.stream().map(timedValue -> timedValue.getId().getAttribute()).collect(Collectors.toList());
        List<Attribute> missingAttributes = ListUtils.subtract(attributes, presentAttributes);
        String missingAttributesString = missingAttributes.stream().map(Attribute::getLabel).collect(Collectors.joining(", "));
        throw new IncomputableFieldException(String.format("No TimedValue found for attributes %s", missingAttributesString));
    }

    return timedValues;
}
项目:spring-boot    文件:Test3.java   
private void subList() {
    System.out.println(StringUtils.center("apache commons", 80, "="));
    List<Integer> largeList = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
    MyFastJsonUtils.prettyPrint(ListUtils.partition(largeList, 3));
    System.out.println(StringUtils.center("Guava", 80, "="));
    MyFastJsonUtils.prettyPrint(Lists.partition(largeList, 3));
    System.out.println(StringUtils.center("my customize", 80, "="));
    MyFastJsonUtils.prettyPrint(MyCollectionUtils.partition(largeList, 3));

}
项目:java-hod-client    文件:RetrieveIndexFieldsResponse.java   
private RetrieveIndexFieldsResponse(final Builder builder) {
    fieldTypeCounts = builder.fieldTypeCounts;
    totalFields = builder.totalFields;

    fields.put(FieldTypeParam.AutnRank, ListUtils.emptyIfNull(builder.autnRankTypeFields));
    fields.put(FieldTypeParam.NumericDate, ListUtils.emptyIfNull(builder.dateTypeFields));
    fields.put(FieldTypeParam.Index, ListUtils.emptyIfNull(builder.indexTypeFields));
    fields.put(FieldTypeParam.Numeric, ListUtils.emptyIfNull(builder.numericTypeFields));
    fields.put(FieldTypeParam.Parametric, ListUtils.emptyIfNull(builder.parametricTypeFields));
    fields.put(FieldTypeParam.Reference, ListUtils.emptyIfNull(builder.referenceTypeFields));
    fields.put(FieldTypeParam.All, ListUtils.emptyIfNull(builder.storedTypeFields));
}
项目:gatk-protected    文件:CopyRatioSegmenter.java   
/**
 * evenly-spaced log-2 copy ratios
 * @param K the initial number of hidden states
 */
private static List<Double> initialNonConstantLog2CopyRatios(final int K) {
    ParamUtils.isPositive(K, "must have at least one non-constant state");
    final double spacing = (MAX_INITIAL_LOG_2_COPY_RATIO  - MIN_INITIAL_LOG_2_COPY_RATIO) / (K + 1);
    final int numNegativeStates = K / 2;
    final int numPositiveStates = K - numNegativeStates;
    final List<Double> negativeStates = Doubles.asList(GATKProtectedMathUtils.createEvenlySpacedPoints(MIN_INITIAL_LOG_2_COPY_RATIO, spacing, numNegativeStates));
    final List<Double> positiveStates = Doubles.asList(GATKProtectedMathUtils.createEvenlySpacedPoints(spacing, MAX_INITIAL_LOG_2_COPY_RATIO, numPositiveStates));
    return ListUtils.union(negativeStates, positiveStates);
}
项目:gatk-protected    文件:ScalarHMMSegmenter.java   
public ScalarHMMSegmenter(final List<SimpleInterval> positions, final List<DATA> data,
                          final List<Double> constantHiddenStates, final List<Double> initialNonConstantHiddenStates) {
    super(positions, data, ListUtils.union(constantHiddenStates, initialNonConstantHiddenStates),
            uniformWeights(constantHiddenStates.size() + initialNonConstantHiddenStates.size()),
            DEFAULT_INITIAL_CONCENTRATION, DEFAULT_MEMORY_LENGTH);
    numConstantStates = constantHiddenStates.size();
}
项目:gatk-protected    文件:SegmentUtils.java   
private static SortedMap<String, List<Breakpoint>> collectBreakpointsByContig(final List<SimpleInterval> targetSegments,
                                                                              final List<SimpleInterval> snpSegments) {
    return ListUtils.union(targetSegments, snpSegments).stream()
            .map(s -> Arrays.asList(
                    new Breakpoint(BreakpointType.START, s.getContig(), s.getStart()),
                    new Breakpoint(BreakpointType.END, s.getContig(), s.getEnd())))
            .flatMap(Collection::stream)
            .sorted()
            .collect(Collectors.groupingBy(Interval::getContig, TreeMap::new, Collectors.toList()));
}
项目:APIServer    文件:Task.java   
/**
 * Retrieves the associated infrastructure Id.
 * This is the Id of the infrastructure selected to execute the task among
 * the many the application can run on.
 *
 * @return The infrastructure Id
 */
public String getAssociatedInfrastructureId() {
    if ((associatedInfrastructureId == null
            || associatedInfrastructureId.isEmpty())
            && applicationDetail != null) {
        List<Infrastructure> infras =
                ListUtils.select(applicationDetail.getInfrastructures(),
                        new Predicate<Infrastructure>() {
                            @Override
                            public boolean evaluate(
                                    final Infrastructure t) {
                                return t.isEnabled();
                            }
                        }
                );
        Random rand = new Random((new Date()).getTime());

        while (!infras.isEmpty()) {
            Infrastructure i = infras.remove(rand.nextInt(infras.size()));
            if (i.isEnabled()) {
                setAssociatedInfrastructureId(i.getId());
                return associatedInfrastructureId;
            }
        }
    }
    return associatedInfrastructureId;
}
项目:scheduling    文件:InternalTask.java   
/**
 * Updates the runtime variables for this task. Variables are updated using the following order:
 * 1) job variables
 * 2) task variables
 * 3) propagated variables
 * 4) system variables
 *
 * @param schedulingService
 */
public synchronized void updateVariables(SchedulingService schedulingService) {
    if (updatedVariables == null) {
        updatedVariables = new LinkedHashMap<>();
        updatedVariables.putAll(internalJob.getVariablesAsReplacementMap());
        updatedVariables.putAll(getScopeVariables());

        if (internalTasksDependencies != null) {
            Set<TaskId> parentIds = new HashSet<>(internalTasksDependencies.size());
            for (InternalTask parentTask : internalTasksDependencies) {
                parentIds.addAll(InternalTaskParentFinder.getInstance()
                                                         .getFirstNotSkippedParentTaskIds(parentTask));
            }

            // Batch fetching of parent tasks results
            Map<TaskId, TaskResult> taskResults = new HashMap<>();
            for (List<TaskId> parentsSubList : ListUtils.partition(new ArrayList<>(parentIds),
                                                                   PASchedulerProperties.SCHEDULER_DB_FETCH_TASK_RESULTS_BATCH_SIZE.getValueAsInt())) {

                taskResults.putAll(schedulingService.getInfrastructure()
                                                    .getDBManager()
                                                    .loadTasksResults(internalJob.getId(), parentsSubList));

            }
            if (!parentIds.isEmpty()) {
                updateVariablesWithTaskResults(taskResults);
            }
        }

        updatedVariables.putAll(getSystemVariables());
    }
}
项目:feilong-core    文件:ThreadUtil.java   
/**
 * Builds the thread array.
 * 
 * <p>
 * 调用 {@link ListUtils#partition(List, int)} 对list 分成N份,对应的创建N份线程,每个线程的 名字 参见 {@link #buildThreadName(int, PartitionRunnableBuilder)}
 * </p>
 * 
 * <p>
 * 会自动创建 ThreadGroup,线程组名字参见 {@link #buildThreadGroupName(List, PartitionRunnableBuilder)}, <br>
 * 所有新建的线程将归属到该 线程组,你可以在自定义的partitionRunnableBuilder中监控或者管理 该ThreadGroup
 * </p>
 *
 * @param <T>
 *            the generic type
 * @param list
 *            the list
 * @param eachSize
 *            the per size
 * @param paramsMap
 *            the params map
 * @param partitionRunnableBuilder
 *            the group runnable builder
 * @return the thread[]
 */
private static <T> Thread[] buildThreadArray(
                List<T> list,
                int eachSize,
                Map<String, ?> paramsMap,
                PartitionRunnableBuilder<T> partitionRunnableBuilder){

    //使用group进行管理  
    ThreadGroup threadGroup = new ThreadGroup(buildThreadGroupName(list, partitionRunnableBuilder));

    //将 list 分成 N 份
    List<List<T>> groupList = ListUtils.partition(list, eachSize);

    //-------------------------------------------------------------------
    int i = 0;
    Thread[] threads = new Thread[groupList.size()];
    for (List<T> perBatchList : groupList){
        String threadName = buildThreadName(i, partitionRunnableBuilder);

        PartitionThreadEntity partitionThreadEntity = new PartitionThreadEntity(
                        threadName,
                        list.size(),
                        eachSize,
                        i,
                        perBatchList.size());

        Runnable runnable = partitionRunnableBuilder.build(perBatchList, partitionThreadEntity, paramsMap);
        threads[i] = new Thread(threadGroup, runnable, threadName);
        i++;
    }

    //---------------------------------------------------------------

    LOGGER.info("total list size:[{}],build [{}] threads,perSize:[{}]", list.size(), threads.length, eachSize);
    return threads;
}
项目:metron    文件:ThreatTriageFunctions.java   
@Override
public Object apply(List<Object> args, Context context) throws ParseException {
  SensorEnrichmentConfig config = getSensorEnrichmentConfig(args, 0);

  ThreatIntelConfig tiConfig = (ThreatIntelConfig) getConfig(config, EnrichmentConfigFunctions.Type.THREAT_INTEL);
  if(tiConfig == null) {
    return "";
  }
  org.apache.metron.common.configuration.enrichment.threatintel.ThreatTriageConfig triageConfig = tiConfig.getTriageConfig();
  if(triageConfig == null) {
    return "";
  }

  // print each rule
  List<RiskLevelRule> triageRules = ListUtils.emptyIfNull(triageConfig.getRiskLevelRules());
  String[] headers = new String[] {"Name", "Comment", "Triage Rule", "Score", "Reason"};
  String[][] data = new String[triageRules.size()][5];
  int i = 0;
  for(RiskLevelRule rule : triageRules) {
    double d = rule.getScore().doubleValue();
    String score = d == (long)d ? String.format("%d", (long)d) : String.format("%s", d);
    String name = Optional.ofNullable(rule.getName()).orElse("");
    String comment = Optional.ofNullable(rule.getComment()).orElse("");
    String reason = Optional.ofNullable(rule.getReason()).orElse("");
    data[i++]  = new String[] {name, comment, rule.getRule(), score, reason};
  }
  String ret = FlipTable.of(headers, data);

  // print the aggregation
  if(!triageRules.isEmpty()) {
    ret += "Aggregation: " + triageConfig.getAggregator().name();
  }
  return ret;
}
项目:metron    文件:EncodingFunctionsTest.java   
@Test
public void testSupportedEncodingsList() throws Exception{
  Object ret = run("GET_SUPPORTED_ENCODINGS()", new HashMap());
  Assert.assertTrue(ret instanceof List );
  List<String> list = (List<String>)ret;
  List<String> expected = new ArrayList<>(Arrays.asList("BASE32","BASE32HEX","BASE64","BINARY","HEX"));
  Assert.assertTrue(ListUtils.isEqualList(expected,list));
}
项目:karaf-commands    文件:EnsembleHealthyAction.java   
protected Boolean waitForEnsembleHealthy() throws InterruptedException {
    Boolean hasTimedOut = false;

    Long currentTime = System.nanoTime();
    Long waitTimeout = currentTime + TimeUnit.MILLISECONDS.toNanos(wait);

    while (!hasTimedOut) {
        List<String> containersInEnsemble = clusterService.getEnsembleContainers();

        //Sort them to be alphabetical
        Collections.sort(containersInEnsemble);

        Boolean isEqualList = ListUtils.isEqualList(containers, containersInEnsemble);
        if (isEqualList) {
            log.trace("MATCH: Expected: {}, Result: {}", StringUtils.join(containers, ','), StringUtils.join(containersInEnsemble, ','));

            System.out.println(String.format(FORMAT, "Ensemble List: ", StringUtils.join(containersInEnsemble, ',')));
            System.out.println("Ensemble Healthy: success");
            break;

        } else {
            log.trace("NON-MATCH: Expected: {}, Result: {}. Waiting...", StringUtils.join(containers, ','), StringUtils.join(containersInEnsemble, ','));
        }

        currentTime = System.nanoTime();
        if (currentTime > waitTimeout) {
            log.trace("Ensemble of {} took too long. Current time {}ns is greater than wait {}ns", StringUtils.join(containers, ','), currentTime, waitTimeout);

            hasTimedOut = true;
            break;
        }

        //Probably not the best way, but does its job
        TimeUnit.MILLISECONDS.sleep(tick);
    }

    return hasTimedOut;
}
项目:find    文件:ParametricValuesController.java   
@RequestMapping(method = RequestMethod.GET, value = NUMERIC_PATH + VALUE_DETAILS_PATH)
@ResponseBody
public NumericValueDetails getNumericValueDetails(
    @RequestParam(FIELD_NAME_PARAM) final FieldPath fieldName,
    @RequestParam(QUERY_TEXT_PARAM) final String queryText,
    @RequestParam(value = FIELD_TEXT_PARAM, defaultValue = "") final String fieldText,
    @RequestParam(DATABASES_PARAM) final Collection<S> databases,
    @RequestParam(value = MIN_DATE_PARAM, required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) final ZonedDateTime minDate,
    @RequestParam(value = MAX_DATE_PARAM, required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) final ZonedDateTime maxDate,
    @RequestParam(value = MIN_SCORE, defaultValue = "0") final Integer minScore,
    @RequestParam(value = STATE_TOKEN_PARAM, required = false) final List<String> stateTokens
) throws E {
    final Q queryRestrictions = queryRestrictionsBuilderFactory.getObject()
        .queryText(queryText)
        .fieldText(fieldText)
        .databases(databases)
        .minDate(minDate)
        .maxDate(maxDate)
        .minScore(minScore)
        .stateMatchIds(ListUtils.emptyIfNull(stateTokens))
        .build();

    final R parametricRequest = parametricRequestBuilderFactory.getObject()
        .fieldName(fieldName)
        .maxValues(null)
        .queryRestrictions(queryRestrictions)
        .build();

    return parametricValuesService.getNumericValueDetails(parametricRequest).get(fieldName);
}
项目:find    文件:ParametricValuesController.java   
@RequestMapping(method = RequestMethod.GET, value = DATE_PATH + VALUE_DETAILS_PATH)
@ResponseBody
public DateValueDetails getDateValueDetails(
    @RequestParam(FIELD_NAME_PARAM) final FieldPath fieldName,
    @RequestParam(QUERY_TEXT_PARAM) final String queryText,
    @RequestParam(value = FIELD_TEXT_PARAM, defaultValue = "") final String fieldText,
    @RequestParam(DATABASES_PARAM) final Collection<S> databases,
    @RequestParam(value = MIN_DATE_PARAM, required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) final ZonedDateTime minDate,
    @RequestParam(value = MAX_DATE_PARAM, required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) final ZonedDateTime maxDate,
    @RequestParam(value = MIN_SCORE, defaultValue = "0") final Integer minScore,
    @RequestParam(value = STATE_TOKEN_PARAM, required = false) final List<String> stateTokens
) throws E {
    final Q queryRestrictions = queryRestrictionsBuilderFactory.getObject()
        .queryText(queryText)
        .fieldText(fieldText)
        .databases(databases)
        .minDate(minDate)
        .maxDate(maxDate)
        .minScore(minScore)
        .stateMatchIds(ListUtils.emptyIfNull(stateTokens))
        .build();

    final R parametricRequest = parametricRequestBuilderFactory.getObject()
        .fieldName(fieldName)
        .maxValues(null)
        .queryRestrictions(queryRestrictions)
        .build();

    return parametricValuesService.getDateValueDetails(parametricRequest).get(fieldName);
}
项目:find    文件:ParametricValuesController.java   
@RequestMapping(method = RequestMethod.GET, value = DEPENDENT_VALUES_PATH)
@ResponseBody
public List<DependentParametricField> getDependentParametricValues(
    @RequestParam(FIELD_NAMES_PARAM) final List<FieldPath> fieldNames,
    @RequestParam(QUERY_TEXT_PARAM) final String queryText,
    @RequestParam(value = FIELD_TEXT_PARAM, defaultValue = "") final String fieldText,
    @RequestParam(DATABASES_PARAM) final Collection<S> databases,
    @RequestParam(value = MIN_DATE_PARAM, required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) final ZonedDateTime minDate,
    @RequestParam(value = MAX_DATE_PARAM, required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) final ZonedDateTime maxDate,
    @RequestParam(value = MIN_SCORE, defaultValue = "0") final Integer minScore,
    @RequestParam(value = STATE_TOKEN_PARAM, required = false) final List<String> stateTokens
) throws E {
    final Q queryRestrictions = queryRestrictionsBuilderFactory.getObject()
        .queryText(queryText)
        .fieldText(fieldText)
        .databases(databases)
        .minDate(minDate)
        .maxDate(maxDate)
        .minScore(minScore)
        .stateMatchIds(ListUtils.emptyIfNull(stateTokens))
        .build();

    final R parametricRequest = parametricRequestBuilderFactory.getObject()
        .fieldNames(ListUtils.emptyIfNull(fieldNames))
        .queryRestrictions(queryRestrictions)
        .maxValues(null)
        .build();

    return parametricValuesService.getDependentParametricValues(parametricRequest);
}
项目:find    文件:RelatedConceptsController.java   
@SuppressWarnings("MethodWithTooManyParameters")
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public List<T> findRelatedConcepts(
    @RequestParam(QUERY_TEXT_PARAM) final String queryText,
    @RequestParam(value = FIELD_TEXT_PARAM, defaultValue = "") final String fieldText,
    @RequestParam(DATABASES_PARAM) final Collection<S> databases,
    @RequestParam(value = MIN_DATE_PARAM, required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) final ZonedDateTime minDate,
    @RequestParam(value = MAX_DATE_PARAM, required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) final ZonedDateTime maxDate,
    @RequestParam(value = MIN_SCORE_PARAM, defaultValue = "0") final Integer minScore,
    @RequestParam(value = STATE_MATCH_TOKEN_PARAM, required = false) final List<String> stateMatchTokens,
    @RequestParam(value = STATE_DONT_MATCH_TOKEN_PARAM, required = false) final List<String> stateDontMatchTokens,
    @RequestParam(value = MAX_RESULTS, required = false) final Integer maxResults
) throws E {
    final Q queryRestrictions = queryRestrictionsBuilderFactory.getObject()
            .queryText(queryText)
            .fieldText(fieldText)
            .databases(databases)
            .minDate(minDate)
            .maxDate(maxDate)
            .minScore(minScore)
            .stateMatchIds(ListUtils.emptyIfNull(stateMatchTokens))
            .stateDontMatchIds(ListUtils.emptyIfNull(stateDontMatchTokens))
            .build();

    final R relatedConceptsRequest = relatedConceptsRequestBuilderFactory.getObject()
        .maxResults(maxResults)
        .querySummaryLength(QUERY_SUMMARY_LENGTH)
        .queryRestrictions(queryRestrictions)
        .build();

    return relatedConceptsService.findRelatedConcepts(relatedConceptsRequest);
}