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

项目:bluegreen-manager    文件:TwoEnvLoader.java   
/**
 * Gets the applicationVm's persisted application record.  (Currently require exactly 1.)
 */
private Application findApplicationFromVm(ApplicationVm applicationVm)
{
  List<Application> applications = applicationVm.getApplications();
  if (CollectionUtils.isEmpty(applications))
  {
    throw new IllegalStateException(context(applicationVm.getEnvironment()) + "No application");
  }
  else
  {
    if (applications.size() > 1)
    {
      throw new UnsupportedOperationException(context(applicationVm.getEnvironment())
          + "Currently only support case of 1 application, but applicationVm '"
          + applicationVm.getHostname() + "' has " + applications.size());
    }
    return applications.get(0);
  }
}
项目:spring-grow    文件:AdministrationUserController.java   
@RequestMapping(value = "/update", method = { RequestMethod.POST })
public String update(@ModelAttribute User user) {
   User persistentUser = userService.findByPK(user.getId());
   boolean expireUserSession = !user.isActive() || !CollectionUtils.isEqualCollection(user.getRoles(), persistentUser.getRoles());
   persistentUser.setFirstname(user.getFirstname());
   persistentUser.setLastname(user.getLastname());
   persistentUser.setEmail(user.getEmail());
   persistentUser.setRoles(user.getRoles());
   persistentUser.setActive(user.isActive());
   persistentUser.setPasswordExpired(user.isPasswordExpired());
   userService.update(persistentUser);

   if (expireUserSession){
      // expire user session
      sessionService.expireUserSession(persistentUser);
   }else{
      // update user information without expiring her session
      sessionService.updateUserSession(persistentUser);
   }

   return "redirect:/administration/user/list?success=true";
}
项目:bluegreen-manager    文件:ElbInstanceGoneProgressChecker.java   
/**
 * Sanity checks the LB description, and checks for done-ness.
 */
private void checkInstanceRemoval(LoadBalancerDescription loadBalancerDescription)
{
  if (!StringUtils.equals(elbName, loadBalancerDescription.getLoadBalancerName()))
  {
    throw new IllegalStateException(logContext + "We requested description of ELB '" + elbName
        + "' but response is for '" + loadBalancerDescription.getLoadBalancerName() + "'");
  }
  if (CollectionUtils.isEmpty(loadBalancerDescription.getInstances()))
  {
    throw new IllegalStateException("ELB '" + elbName + "' has zero instances");
  }
  if (instanceIsGoneFromList(loadBalancerDescription.getInstances()))
  {
    LOGGER.info("ELB '" + elbName + "' list of instances shows '" + ec2InstanceId + "' is gone");
    done = true;
    result = true;
  }
}
项目:hybris-integration-intellij-idea-plugin    文件:AbstractHybrisModuleDescriptor.java   
@NotNull
protected Set<HybrisModuleDescriptor> recursivelyCollectDependenciesPlainSet(
    @NotNull final HybrisModuleDescriptor descriptor,
    @NotNull final Set<HybrisModuleDescriptor> dependenciesSet
) {
    Validate.notNull(descriptor);
    Validate.notNull(dependenciesSet);

    if (CollectionUtils.isEmpty(descriptor.getDependenciesTree())) {
        return dependenciesSet;
    }

    for (HybrisModuleDescriptor moduleDescriptor : descriptor.getDependenciesTree()) {
        if (dependenciesSet.contains(moduleDescriptor)) {
            continue;
        }

        dependenciesSet.add(moduleDescriptor);
        dependenciesSet.addAll(recursivelyCollectDependenciesPlainSet(moduleDescriptor, dependenciesSet));
    }

    return dependenciesSet;
}
项目:smarti    文件:MltConfig.java   
public MltConfig setSimilarityFields(String lang, Collection<String> similarityFields) {
    lang = StringUtils.lowerCase(lang, Locale.ROOT);
    if(CollectionUtils.isEmpty(similarityFields)){
        langSimilarityFields.remove(lang);
    } else {
        Collection<String> langFields = similarityFields.stream()
                .filter(StringUtils::isNoneBlank)
                .collect(Collectors.toCollection(() -> new LinkedHashSet<>()));
        if(CollectionUtils.isNotEmpty(langFields)){
            langSimilarityFields.put(lang, langFields);
        } else {
            langSimilarityFields.remove(lang);
        }
    }
    return this;
}
项目:simm-lib    文件:VegaMarginAcrossBucketUtils.java   
static BigDecimal sumCorrelationsAcrossBuckets(RiskClass riskClass, List<BucketWeightedAggregation> aggregateByBucket) {
  BigDecimal sum = BigDecimal.ZERO;

  if (CollectionUtils.isNotEmpty(aggregateByBucket)) {
    for (BucketWeightedAggregation bucketAggregateB : aggregateByBucket) {
      for (BucketWeightedAggregation bucketAggregateC : aggregateByBucket) {
        if (!StringUtils.equals(bucketAggregateB.getBucket(), bucketAggregateC.getBucket())) {
          BigDecimal concentrationRiskFactor = RiskConcentration.getVegaCrossBucketConcentration(riskClass, bucketAggregateB, bucketAggregateC);
          BigDecimal correlation = RiskCorrelation.getBucketCorrelation(riskClass, bucketAggregateB.getBucket(), bucketAggregateC.getBucket());

          BigDecimal bucketBSum = WeightedSensitivityUtils.sumWeightSensitivities(bucketAggregateB.getWeightedSensitivities());
          BigDecimal bucketCSum = WeightedSensitivityUtils.sumWeightSensitivities(bucketAggregateC.getWeightedSensitivities());

          BigDecimal bucketBAggregate = bucketAggregateB.getAggregate();
          BigDecimal bucketCAggregate = bucketAggregateC.getAggregate();
          BigDecimal sb = bucketBSum.min(bucketBAggregate).max(bucketBAggregate.negate());
          BigDecimal sc = bucketCSum.min(bucketCAggregate).max(bucketCAggregate.negate());
          BigDecimal product = correlation.multiply(concentrationRiskFactor).multiply(sb).multiply(sc);
          sum = sum.add(product);
        }
      }
    }
  }
  return sum;
}
项目:simm-lib    文件:SensitivityUtils.java   
/**
 * As defined in Appendix 1 section B.8.a, B.9.a of doc/ISDA_SIMM_vR1.0_(PUBLIC).pdf
 */
public static List<Sensitivity> netSensitivitiesByRiskFactor(RiskClass riskClass, List<Sensitivity> sensitivities) {
  List<Sensitivity> riskFactorList = new ArrayList<>();
  Map<String, BigDecimal> valuesMap = new LinkedHashMap<>();

  if (CollectionUtils.isNotEmpty(sensitivities)) {
    for (Sensitivity sensitivity : sensitivities) {
      String key = sensitivity.getProductClass() + "/" + sensitivity.getRiskType() + "/" + sensitivity.getQualifier() + "/" + sensitivity.getBucket()
        + "/" + sensitivity.getLabel1() + "/" + sensitivity.getLabel2();

      if (valuesMap.containsKey(key)) {
        BigDecimal value = valuesMap.get(key);
        valuesMap.put(key, value.add(sensitivity.getAmountUsd()));
      } else {
        valuesMap.put(key, sensitivity.getAmountUsd());
      }
    }
  }

  for (Entry<String, BigDecimal> valueEntry : valuesMap.entrySet()) {
    riskFactorList.add(new Sensitivity(valueEntry.getKey(), valueEntry.getValue()));
  }

  return riskFactorList;
}
项目:talchain    文件:BlockMiner.java   
private void onPendingStateChanged() {
    if (!isLocalMining && externalMiner == null) return;

    logger.debug("onPendingStateChanged()");
    if (miningBlock == null) {
        restartMining();
    } else if (miningBlock.getNumber() <= ((PendingStateImpl) pendingState).getBestBlock().getNumber()) {
        logger.debug("Restart mining: new best block: " + blockchain.getBestBlock().getShortDescr());
        restartMining();
    } else if (!CollectionUtils.isEqualCollection(miningBlock.getTransactionsList(), getAllPendingTransactions())) {
        logger.debug("Restart mining: pending transactions changed");
        restartMining();
    } else {
        if (logger.isDebugEnabled()) {
            String s = "onPendingStateChanged() event, but pending Txs the same as in currently mining block: ";
            for (Transaction tx : getAllPendingTransactions()) {
                s += "\n    " + tx;
            }
            logger.debug(s);
        }
    }
}
项目:AppCoins-ethereumj    文件:BlockMiner.java   
private void onPendingStateChanged() {
    if (!isLocalMining && externalMiner == null) return;

    logger.debug("onPendingStateChanged()");
    if (miningBlock == null) {
        restartMining();
    } else if (miningBlock.getNumber() <= ((PendingStateImpl) pendingState).getBestBlock().getNumber()) {
        logger.debug("Restart mining: new best block: " + blockchain.getBestBlock().getShortDescr());
        restartMining();
    } else if (!CollectionUtils.isEqualCollection(miningBlock.getTransactionsList(), getAllPendingTransactions())) {
        logger.debug("Restart mining: pending transactions changed");
        restartMining();
    } else {
        if (logger.isDebugEnabled()) {
            String s = "onPendingStateChanged() event, but pending Txs the same as in currently mining block: ";
            for (Transaction tx : getAllPendingTransactions()) {
                s += "\n    " + tx;
            }
            logger.debug(s);
        }
    }
}
项目:bluegreen-manager    文件:OneEnvLoader.java   
/**
 * Gets the env's persisted logicaldb record.  Requires exactly 1.
 */
private LogicalDatabase findLogicalDatabaseFromEnvironment()
{
  List<LogicalDatabase> logicalDatabases = environment.getLogicalDatabases();
  if (CollectionUtils.isEmpty(logicalDatabases))
  {
    throw new IllegalStateException(context() + "No logical databases");
  }
  else if (logicalDatabases.size() > 1)
  {
    throw new UnsupportedOperationException(context() + "Currently only support case of 1 logicalDatabase, but env has "
        + logicalDatabases.size() + ": " + environmentHelper.listOfNames(logicalDatabases));
  }
  else if (StringUtils.isBlank(logicalDatabases.get(0).getLogicalName()))
  {
    throw new IllegalStateException(context() + "Live logical database has blank name");
  }
  return logicalDatabases.get(0);
}
项目:rskj    文件:PeerExplorerTest.java   
@Test
public void sendInitialMessageToNodes() {
    List<String> nodes = new ArrayList<>();
    nodes.add("localhost:3306");
    nodes.add("localhost:3307");
    nodes.add("localhost:3306:abd");
    nodes.add("");
    nodes.add(null);

    Node node = new Node(new ECKey().getNodeId(), HOST_1, PORT_1);
    NodeDistanceTable distanceTable = new NodeDistanceTable(KademliaOptions.BINS, KademliaOptions.BUCKET_SIZE, node);
    PeerExplorer peerExplorer = new PeerExplorer(nodes, node, distanceTable, new ECKey(), TIMEOUT, REFRESH);

    UDPChannel channel = new UDPChannel(Mockito.mock(Channel.class), peerExplorer);
    peerExplorer.setUDPChannel(channel);

    Set<String> nodesWithMessage = peerExplorer.startConversationWithNewNodes();

    Assert.assertTrue(CollectionUtils.size(nodesWithMessage) == 2);
    Assert.assertTrue(nodesWithMessage.contains("localhost/127.0.0.1:3307"));
    Assert.assertTrue(nodesWithMessage.contains("localhost/127.0.0.1:3306"));
}
项目:HCFCore    文件:CompositeMap.java   
/**
 * Add an additional Map to the composite.
 *
 * @param map  the Map to be added to the composite
 * @throws IllegalArgumentException if there is a key collision and there is no
 *         MapMutator set to handle it.
 */
@SuppressWarnings("unchecked")
public synchronized void addComposited(final Map<K, V> map) throws IllegalArgumentException {
    for (int i = composite.length - 1; i >= 0; --i) {
        final Collection<K> intersect = CollectionUtils.intersection(this.composite[i].keySet(), map.keySet());
        if (intersect.size() != 0) {
            if (this.mutator == null) {
                throw new IllegalArgumentException("Key collision adding Map to CompositeMap");
            }
            this.mutator.resolveCollision(this, this.composite[i], map, intersect);
        }
    }
    final Map<K, V>[] temp = new Map[this.composite.length + 1];
    System.arraycopy(this.composite, 0, temp, 0, this.composite.length);
    temp[temp.length - 1] = map;
    this.composite = temp;
}
项目:IPPR2016    文件:ExecuteRefinementTask.java   
private BusinessObjectInstanceDTO getBusinessObjectInstanceDTO(
    final BusinessObject businessObject) {
  final Long bomId = businessObject.getBomId();

  final List<BusinessObjectFieldInstanceDTO> fields = businessObject.getFields().values().stream()
      .map(field -> new BusinessObjectFieldInstanceDTO(field.getBofmId(), field.getValue()))
      .collect(Collectors.toList());

  final List<BusinessObjectInstanceDTO> children = Lists.newArrayList();
  if (CollectionUtils.isEmpty(businessObject.getChildren().values())) {
    for (final BusinessObject child : businessObject.getChildren().values()) {
      children.add(getBusinessObjectInstanceDTO(child));
    }
  }
  return new BusinessObjectInstanceDTO(bomId, fields, children);
}
项目:NGB-master    文件:DaoHelper.java   
@Transactional(propagation = Propagation.MANDATORY)
public Long createTempStringList(final Long listId, final Collection<String> list) {
    Assert.notNull(listId);
    Assert.isTrue(CollectionUtils.isNotEmpty(list));
    // creates a new local temporary table if it doesn't exists to handle temporary lists
    getJdbcTemplate().update(createTemporaryStringListQuery);
    // fills in a temporary list by given values
    int i = 0;
    final Iterator<String> iterator = list.iterator();
    final MapSqlParameterSource[] batchArgs = new MapSqlParameterSource[list.size()];
    while (iterator.hasNext()) {
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue(HelperParameters.LIST_ID.name(), listId);
        params.addValue(HelperParameters.LIST_VALUE.name(), iterator.next());
        batchArgs[i] = params;
        i++;
    }
    getNamedParameterJdbcTemplate().batchUpdate(insertTemporaryStringListItemQuery, batchArgs);
    return listId;
}
项目:bluegreen-manager    文件:OneEnvLoader.java   
/**
 * Gets the env's persisted application vm record.  (Currently support only 1.)
 */
private void findApplicationVmFromEnvironment(boolean createVm)
{
  List<ApplicationVm> applicationVms = environment.getApplicationVms();
  if (CollectionUtils.isEmpty(applicationVms))
  {
    if (!createVm)
    {
      throw new IllegalStateException(context() + "No application vms");
    }
  }
  else if (createVm)
  {
    throw new IllegalStateException("Cannot create applicationVm, since " + applicationVms.size() + " already exist");
  }
  else
  {
    if (applicationVms.size() > 1)
    {
      throw new UnsupportedOperationException(context() + "Currently only support case of 1 applicationVm, but found "
          + applicationVms.size());
    }
    this.applicationVm = applicationVms.get(0);
  }
}
项目:dshell    文件:DefaultInternalCompilerTest.java   
@Test
public void reports_errors_when_provided_file_contains_syntax_problems() {
    final String javaFile = ResourceUtils.getFileFromClassPath("java/InvalidClassUnderCompilationTest.java");

    final DefaultJavaFileCompiler compiler = new DefaultJavaFileCompiler();
    compiler.init(
            folder.getRoot().getAbsolutePath(),
            new DefaultDependencyResolver(),
            new DefaultInternalCompiler()
    );

    final CompilationResult compilationResult = compiler.compile(javaFile, null);
    Assert.assertFalse(compilationResult.isSuccess());
    final List<String> compilerBarks = compilationResult.getCompilerBarks();
    assertTrue("expect compiler errors", CollectionUtils.isNotEmpty(compilerBarks));
}
项目:osc-core    文件:ServiceFunctionChainRequestValidator.java   
public void validateVirtualSystems(List<Long> vsIds, VirtualizationConnector vc) throws Exception {
    // make sure all the virtual system in the sfc dto list exist otherwise
    // throw
       for (Long vsId : CollectionUtils.emptyIfNull(vsIds)) {
           VirtualSystem virtualSystem = VirtualSystemEntityMgr.findById(this.em, vsId);
           if (virtualSystem == null) {
               throw new VmidcBrokerValidationException("VirtualSytem with id " + vsId + " is not found.");
           } else if (!vc.getVirtualSystems().contains(virtualSystem)) {
               throw new VmidcBrokerValidationException(String.format(
                       "Virtual system with id %s and with Virtualization Connector id %s does not match the virtualization connector"
                               + " under which this Service function chain is being created/updated",
                       vsId, virtualSystem.getVirtualizationConnector().getId()));
           }
       }

}
项目:HCFCore    文件:CompositeMap.java   
/**
 * Add an additional Map to the composite.
 *
 * @param map  the Map to be added to the composite
 * @throws IllegalArgumentException if there is a key collision and there is no
 *         MapMutator set to handle it.
 */
@SuppressWarnings("unchecked")
public synchronized void addComposited(final Map<K, V> map) throws IllegalArgumentException {
    for (int i = composite.length - 1; i >= 0; --i) {
        final Collection<K> intersect = CollectionUtils.intersection(this.composite[i].keySet(), map.keySet());
        if (intersect.size() != 0) {
            if (this.mutator == null) {
                throw new IllegalArgumentException("Key collision adding Map to CompositeMap");
            }
            this.mutator.resolveCollision(this, this.composite[i], map, intersect);
        }
    }
    final Map<K, V>[] temp = new Map[this.composite.length + 1];
    System.arraycopy(this.composite, 0, temp, 0, this.composite.length);
    temp[temp.length - 1] = map;
    this.composite = temp;
}
项目:spring-boot-start-current    文件:RecursionUtils.java   
public static < T extends ParentChildrenRecursion > T innerFindOneself ( List< ? extends ParentChildrenRecursion > list ,
                                                                         Serializable oneselfId ) {
    if ( CollectionUtils.isEmpty( list ) ) {
        return null;
    }
    if ( Objects.equals( list.get( 0 ).rootId() , oneselfId ) ) {
        return null;
    }
    for ( ParentChildrenRecursion element : list ) {
        if ( Objects.equals( element.getId() , oneselfId ) ) {
            return ( T ) element;
        }
        final List< ? extends ParentChildrenRecursion > children = element.getChildren();
        if ( CollectionUtils.isNotEmpty( children ) ) {
            return innerFindOneself( children , oneselfId );
        }
    }
    return null;
}
项目:spring-boot-start-current    文件:RecursionUtils.java   
/**
 * 层级关系的list转换为平行的list
 * <p>
 * 现在是一个层级关系的 树形 结构
 * <pre>
 *                          root
 *   children | children children | children children children
 *   ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
 *   转换为平行的,也就是普通的链表
 *   element | element | element | element | element | element
 * </pre>
 *
 * @param trees     implements {@link ParentChildrenRecursion}
 * @param container 存储
 * @return
 */
public static List elementTreeToList ( List< ? extends ParentChildrenRecursion > trees ,
                                       List< ParentChildrenRecursion > container ) {
    if ( CollectionUtils.isEmpty( trees ) ) {
        return container;
    }
    for ( ParentChildrenRecursion tree : trees ) {
        container.add( tree );
        if ( CollectionUtils.isNotEmpty( tree.getChildren() ) ) {
            elementTreeToList( tree.getChildren() , container );
        }
    }
    // 清空 children 内容
    return container.parallelStream()
                    .map( element -> element.setChildren( null ) )
                    .collect( Collectors.toList() );
}
项目:NGB-master    文件:ProteinSequenceManager.java   
private HashMap<Gene, List<Gene>> makeMrnaToVarCdsMap(Map<Gene, List<Gene>> mrnaToCdsMap, Set<Gene> allCds,
                                                      Map<Gene, List<List<Sequence>>> cdsToNucleotidesMap) {
    HashMap<Gene, List<Gene>> mrnaToVarCdsMap = new HashMap<>();
    List<Gene> cdsListNoDuplicates = removeCdsDuplicates(allCds, cdsToNucleotidesMap);

    for (Map.Entry<Gene, List<Gene>> mrnaCdsEntry : mrnaToCdsMap.entrySet()) {
        List<Gene> variationCdsList = new ArrayList<>();
        for (Gene cds : cdsListNoDuplicates) {
            List<Gene> cdsList = mrnaCdsEntry.getValue();
            List<Gene> collect = cdsList.stream().filter(c -> c.getStartIndex().equals(cds.getStartIndex()) &&
                                                              c.getEndIndex().equals(cds.getEndIndex()))
                .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                variationCdsList.add(cds);
            }
        }
        mrnaToVarCdsMap.put(mrnaCdsEntry.getKey(), variationCdsList);
    }

    return mrnaToVarCdsMap;
}
项目:DDComponentForAndroid    文件:RouterProcessor.java   
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    if (CollectionUtils.isNotEmpty(set)) {
        Set<? extends Element> routeNodes = roundEnvironment.getElementsAnnotatedWith(RouteNode.class);
        try {
            logger.info(">>> Found routes, start... <<<");
            parseRouteNodes(routeNodes);
        } catch (Exception e) {
            logger.error(e);
        }
        generateRouterImpl();
        generateRouterTable();
        return true;
    }
    return false;
}
项目:wulkanowy    文件:EntitiesCompare.java   
public static List<Grade> compareGradeList(List<Grade> newList, List<Grade> oldList) {

        List<Grade> addedOrUpdatedGradeList = new ArrayList<>(CollectionUtils
                .removeAll(newList, oldList));
        List<Grade> updatedList = new ArrayList<>(CollectionUtils
                .removeAll(newList, addedOrUpdatedGradeList));
        List<Grade> lastList = new ArrayList<>();

        for (Grade grade : addedOrUpdatedGradeList) {
            if (!oldList.isEmpty()) {
                grade.setRead(false);
                grade.setIsNew(true);
            }
            updatedList.add(grade);
        }

        for (Grade updateGrade : updatedList) {
            for (Grade oldGrade : oldList) {
                if (updateGrade.equals(oldGrade)) {
                    updateGrade.setRead(oldGrade.getRead());
                }
            }
            lastList.add(updateGrade);
        }
        return lastList;
    }
项目:spring-boot-start-current    文件:RolePermissionResourceServiceImpl.java   
@Override
public List< RolePermissionResource > listByUserId ( Long userId ) {
    // 1. 得到用户
    final User user = userService.selectById( userId );

    if ( Objects.isNull( user ) ) {
        return Collections.emptyList();
    }

    // 2. 得到角色
    final List< Role > roles = roleService.listByUserId( user.getId() );

    if ( CollectionUtils.isEmpty( roles ) ) {
        return Collections.emptyList();
    }
    // 3. 得到角色资源中间表信息
    final List< RolePermissionResource > rolePermissionResources = super.selectList(
            new Condition().in(
                    "role_id",
                    roles.parallelStream().map( Role::getId ).collect( Collectors.toList() )
            )
    );
    return rolePermissionResources;
}
项目:bluegreen-manager    文件:TwoEnvLoader.java   
/**
 * Gets the env's persisted application vm record.  (Currently support only 1.)
 */
private ApplicationVm findApplicationVmFromEnvironment(Environment environment)
{
  List<ApplicationVm> applicationVms = environment.getApplicationVms();
  if (CollectionUtils.isEmpty(applicationVms))
  {
    throw new IllegalStateException(context(environment) + "No application vms");
  }
  else
  {
    if (applicationVms.size() > 1)
    {
      throw new UnsupportedOperationException(context(environment) + "Currently only support case of 1 applicationVm, but environment '"
          + environment.getEnvName() + "' has " + applicationVms.size());
    }
    return applicationVms.get(0);
  }
}
项目:plugin-id-ldap    文件:UserLdapRepository.java   
@Override
public void updateMembership(final Collection<String> groups, final UserOrg user) {
    // Add new groups
    addUserToGroups(user, CollectionUtils.subtract(groups, user.getGroups()));

    // Remove old groups
    removeUserFromGroups(user, CollectionUtils.subtract(user.getGroups(), groups));
}
项目:plugin-id-ldap    文件:LdapCacheDao.java   
/**
 * Transform user to JPA.
 */
private CacheUser toCacheUserInternal(final UserOrg user) {
    final CacheUser entity = new CacheUser();
    entity.setId(user.getId());
    entity.setFirstName(user.getFirstName());
    entity.setLastName(user.getLastName());
    if (CollectionUtils.isNotEmpty(user.getMails())) {
        entity.setMails(user.getMails().get(0));
    }
    return entity;
}
项目:bluegreen-manager    文件:OneEnvLoader.java   
/**
 * Gets the env's persisted application record.  (Currently support only 1.)
 */
private void findApplicationFromVm()
{
  List<Application> applications = applicationVm.getApplications();
  if (CollectionUtils.isEmpty(applications))
  {
    throw new IllegalStateException(context() + "No applications");
  }
  else if (applications.size() > 1)
  {
    throw new UnsupportedOperationException(context() + "Currently only support case of 1 application, but found "
        + applications.size());
  }
  this.application = applications.get(0);
}
项目:NGB-master    文件:FeatureIndexDao.java   
/**
 * Groups variations from specified {@link List} of {@link VcfFile}s by specified field
 * @param files a {@link List} of {@link FeatureFile}, which indexes to search
 * @param query a query to search in index
 * @param groupBy a field to perform grouping
 * @return a {@link List} of {@link Group}s, mapping field value to number of variations, having this value
 * @throws IOException if something goes wrong with the file system
 */
public List<Group> groupVariations(List<VcfFile> files, Query query, String groupBy) throws IOException {
    List<Group> res = new ArrayList<>();

    if (CollectionUtils.isEmpty(files)) {
        return Collections.emptyList();
    }

    SimpleFSDirectory[] indexes = fileManager.getIndexesForFiles(files);

    try (MultiReader reader = openMultiReader(indexes)) {
        if (reader.numDocs() == 0) {
            return Collections.emptyList();
        }

        IndexSearcher searcher = new IndexSearcher(reader);
        AbstractGroupFacetCollector groupedFacetCollector =
            TermGroupFacetCollector.createTermGroupFacetCollector(FeatureIndexFields.UID.fieldName,
                                                  getGroupByField(files, groupBy), false, null, GROUP_INITIAL_SIZE);
        searcher.search(query, groupedFacetCollector); // Computing the grouped facet counts
        TermGroupFacetCollector.GroupedFacetResult groupedResult = groupedFacetCollector.mergeSegmentResults(
            reader.numDocs(), 1, false);
        List<AbstractGroupFacetCollector.FacetEntry> facetEntries = groupedResult.getFacetEntries(0,
                                                                                                  reader.numDocs());
        for (AbstractGroupFacetCollector.FacetEntry facetEntry : facetEntries) {
            res.add(new Group(facetEntry.getValue().utf8ToString(), facetEntry.getCount()));
        }
    } finally {
        for (SimpleFSDirectory index : indexes) {
            IOUtils.closeQuietly(index);
        }
    }

    return res;
}
项目:HCFCore    文件:AbstractMultiValuedMap.java   
@Override
public String toString() {
    final Collection<V> coll = getMapping();
    if (coll == null) {
        return CollectionUtils.EMPTY_COLLECTION.toString();
    }
    return coll.toString();
}
项目:HCFCore    文件:AbstractMultiValuedMap.java   
@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
    final Collection<V> coll = getMapping();
    if (coll == null) {
        return (T[]) CollectionUtils.EMPTY_COLLECTION.toArray(a);
    }
    return coll.toArray(a);
}
项目:docker-image-builder    文件:Image.java   
private List<Script> sortScriptByPriority(List<Script> scripts) {
    if ( !CollectionUtils.isEmpty(scripts) ){
        scripts = scripts.stream()
                .sorted((p1, p2) -> p1.getPriority().compareTo(p2.getPriority()))
                .collect(Collectors.toList());
        return scripts;
    }else {
        return null;
    }

}
项目:tauren    文件:BizPayOrderDaoTest.java   
@Test
public void testQuery2() throws SQLException {
    Assert.assertNotNull(dao);

    String sql = "SELECT * FROM biz_pay_order";

    List<BizPayOrder> ret = dao.query(sql, BizPayOrder.class, (Object[]) null);

    Assert.assertTrue(CollectionUtils.isNotEmpty(ret));
    Assert.assertTrue(ret.size() == 2);
    System.out.println(JSON.toJSONString(ret));
}
项目:SAPNetworkMonitor    文件:TaskService.java   
public void  assignTask(List<String> monitorIds, String taskId) throws NiPingException {
    try {
        //validate has assigned TODO
        monitorTaskDao.removeMonitorTask(taskId);
        if (CollectionUtils.isNotEmpty(monitorIds)) {
            monitorTaskDao.insertMonitorTask(monitorIds, taskId);
        }
        log.debug("task {} has been assigned to monitors {}", taskId, Arrays.toString(monitorIds.toArray(new String[]{})));
    } catch (DBIException e) {
        log.error("assign task {} to monitor {} error: {}", taskId, Arrays.toString(monitorIds.toArray(new String[]{})),
                ExceptionUtils.getMessage(e));
        throw new NiPingException(DBError);
    }
}
项目:JuniperBotJ    文件:RankingServiceImpl.java   
@Override
public boolean isBanned(RankingConfig config, Member member) {
    if (config.getBannedRoles() == null) {
        return false;
    }
    List<String> bannedRoles = Arrays.asList(config.getBannedRoles());
    return CollectionUtils.isNotEmpty(member.getRoles()) && member.getRoles().stream()
            .anyMatch(e -> bannedRoles.contains(e.getName().toLowerCase()) || bannedRoles.contains(e.getId()));
}
项目:SAPNetworkMonitor    文件:MonitorService.java   
public boolean modifyMonitorsStatus(List<String> monitorIds, Monitor.Status status) throws NiPingException {
    if (CollectionUtils.isNotEmpty(monitorIds)) {
        try {
            monitorDao.updateMonitorsStatus(monitorIds, status.getStatus(), new Date(System.currentTimeMillis()));
            log.error("modify monitors {} status {}", Arrays.toString(monitorIds.toArray(new String[]{})), status);
        } catch (DBIException e) {
            log.error("modify monitors {} status {} error: {}", Arrays.toString(monitorIds.toArray(new String[]{})), status,
                    ExceptionUtils.getMessage(e));
            throw new NiPingException(DBError);
        }
    }
    return true;
}
项目:NGB-master    文件:ProteinSequenceManager.java   
private Map<Variation, List<Gene>> findIntersections(final Track<Variation> variations, final Set<Gene> allCds) {
    Map<Variation, List<Gene>> intersections = new HashMap<>();
    for (Variation variation : variations.getBlocks()) {
        List<Gene> currIntersections = allCds.stream().filter(geneFeature ->
                variation.getStartIndex() >= geneFeature.getStartIndex() && variation.getStartIndex() <= geneFeature
                        .getEndIndex()).collect(
                Collectors.toList());
        if (CollectionUtils.isNotEmpty(currIntersections)) {
            intersections.put(variation, currIntersections);
        }
    }
    return intersections;
}
项目:simm-lib    文件:DeltaMarginAcrossBucketUtils.java   
/**
 * As defined in Appendix 1 of doc/ISDA_SIMM_2.0_(PUBLIC).pdf
 */
static BigDecimal aggregateCrossBucket(RiskClass riskClass, List<BucketWeightedAggregation> aggregateByBucket) {
  List<BucketWeightedAggregation> nonResiduals = BucketWeightedAggregationUtils.filterOutResiduals(aggregateByBucket);
  if (CollectionUtils.isNotEmpty(nonResiduals)) {
    BigDecimal sumSquaresByBucket = BucketWeightedAggregationUtils.sumSquared(nonResiduals);
    BigDecimal sumCorrelationsAcrossBuckets = sumCorrelationsAcrossBuckets(riskClass, nonResiduals);
    BigDecimal crossSum = sumSquaresByBucket.add(sumCorrelationsAcrossBuckets);
    BigDecimal crossSqrt = BigDecimalUtils.sqrt(crossSum);
    return crossSqrt;
  } else {
    return BigDecimal.ZERO;
  }
}
项目:spring-boot-start-current    文件:RoleServiceImpl.java   
@Override
public List< Role > listByUserRole ( List< UserRole > userRoles ) {
    if ( CollectionUtils.isEmpty( userRoles ) ) {
        return Collections.emptyList();
    }
    final List< Long > roleIds = userRoles.parallelStream()
                                          .map( UserRole::getRoleId )
                                          .collect( Collectors.toList() );
    return super.selectBatchIds( roleIds );
}
项目:docker-image-builder    文件:ComponentBuilder.java   
public ComponentBuilder withEnvironmentVariable(EnvironmentVariable environmentVariable) {
    if(CollectionUtils.isEmpty(this.environmentVariables)) {
        this.environmentVariables = new ArrayList<>();
    }
    this.environmentVariables.add(environmentVariable);
    return this;
}