Java 类com.google.common.collect.Collections2 实例源码

项目:Reer    文件:StructSchemaExtractionStrategySupport.java   
private Iterable<ModelPropertyExtractionContext> selectProperties(final ModelSchemaExtractionContext<?> context, CandidateMethods candidateMethods) {
    Map<String, ModelPropertyExtractionContext> propertiesMap = Maps.newTreeMap();
    for (Map.Entry<Wrapper<Method>, Collection<Method>> entry : candidateMethods.allMethods().entrySet()) {
        Method method = entry.getKey().get();
        PropertyAccessorType propertyAccessorType = PropertyAccessorType.of(method);
        Collection<Method> methodsWithEqualSignature = entry.getValue();
        if (propertyAccessorType != null) {
            String propertyName = propertyAccessorType.propertyNameFor(method);
            ModelPropertyExtractionContext propertyContext = propertiesMap.get(propertyName);
            if (propertyContext == null) {
                propertyContext = new ModelPropertyExtractionContext(propertyName);
                propertiesMap.put(propertyName, propertyContext);
            }
            propertyContext.addAccessor(new PropertyAccessorExtractionContext(propertyAccessorType, methodsWithEqualSignature));
        }
    }
    return Collections2.filter(propertiesMap.values(), new Predicate<ModelPropertyExtractionContext>() {
        @Override
        public boolean apply(ModelPropertyExtractionContext property) {
            return property.isReadable();
        }
    });
}
项目:smarti    文件:MongoUserDetailsService.java   
@Override
public AttributedUserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
    login = login.toLowerCase(Locale.ROOT);

    final SmartiUser smartiUser = getSmaritUser(login);

    if (smartiUser == null) {
        log.debug("User {} not found", login);
        throw new UsernameNotFoundException(String.format("Unknown user: '%s'", login));
    }

    final MongoUserDetails userDetails = new MongoUserDetails(
            smartiUser.getLogin(),
            smartiUser.getPassword(),
            Collections2.transform(smartiUser.getRoles(),
                    role -> new SimpleGrantedAuthority("ROLE_" + StringUtils.upperCase(role, Locale.ROOT))
            )
    );
    userDetails.addAttributes(smartiUser.getProfile());
    return userDetails;
}
项目:vscrawler    文件:FetchTaskProcessor.java   
private Object unPackSipNode(Object object) {
    if (object == null) {
        return null;
    }
    if (object instanceof SIPNode) {
        return handleSingleSipNode((SIPNode) object);
    }
    if (object instanceof Collection) {
        return Collections2.transform((Collection) object, new Function<Object, Object>() {
            @Override
            public Object apply(Object input) {
                if (!(input instanceof SIPNode)) {
                    return input;
                }
                return handleSingleSipNode((SIPNode) input);
            }
        });
    }
    return object;
}
项目:burp-vulners-scanner    文件:SoftwareIssue.java   
@Override
public String getSeverity() {
    if (hasVulnerabilities()) {
        Collection<Double> scores = Collections2.transform(
                software.getVulnerabilities(), new Function<Vulnerability, Double>() {
                    @Override
                    public Double apply(Vulnerability vulnerability) {
                        return vulnerability.getCvssScore();
                    }
                }
        );
        Double maxValue = Ordering.natural().max(scores);

        if (maxValue > 7) {
            return ScanIssueSeverity.HIGH.getName();
        } else if (maxValue > 4) {
            return ScanIssueSeverity.MEDIUM.getName();
        }
        return ScanIssueSeverity.LOW.getName();
    }

    return ScanIssueSeverity.INFO.getName();
}
项目:burp-vulners-scanner    文件:PathIssue.java   
@Override
public String getSeverity() {
    Collection<Double> scores = Collections2.transform(
            vulnerabilities, new Function<Vulnerability, Double>() {
                @Override
                public Double apply(Vulnerability vulnerability) {
                    return vulnerability.getCvssScore();
                }
            }
    );
    Double maxValue = Ordering.natural().max(scores);

    if (maxValue > 7) {
        return ScanIssueSeverity.HIGH.getName();
    } else if (maxValue > 4) {
        return ScanIssueSeverity.MEDIUM.getName();
    }
    return ScanIssueSeverity.LOW.getName();
}
项目:hashsdn-controller    文件:InstanceRuntime.java   
/**
 * Finds all children runtime beans, same properties and values as current root
 * + any number of additional properties.
 */
private Set<ObjectName> findChildren(ObjectName innerRootBean, Set<ObjectName> childRbeOns) {
    final Map<String, String> wantedProperties = innerRootBean.getKeyPropertyList();

    return Sets.newHashSet(Collections2.filter(childRbeOns, on -> {
        Map<String, String> localProperties = on.getKeyPropertyList();
        for (Entry<String, String> propertyEntry : wantedProperties.entrySet()) {
            if (!localProperties.containsKey(propertyEntry.getKey())) {
                return false;
            }
            if (!localProperties.get(propertyEntry.getKey()).equals(propertyEntry.getValue())) {
                return false;
            }
            if (localProperties.size() <= wantedProperties.size()) {
                return false;
            }
        }
        return true;
    }));
}
项目:appinventor-extensions    文件:ProjectBuilder.java   
private void genYailFilesIfNecessary(List<String> sourceFiles)
    throws IOException, YailGenerationException {
  // Filter out the files that aren't really source files (i.e. that don't end in .scm or .yail)
  Collection<String> formAndYailSourceFiles = Collections2.filter(
      sourceFiles,
      new Predicate<String>() {
        @Override
        public boolean apply(String input) {
          return input.endsWith(FORM_PROPERTIES_EXTENSION) || input.endsWith(YAIL_EXTENSION);
        }
      });
  for (String sourceFile : formAndYailSourceFiles) {
    if (sourceFile.endsWith(FORM_PROPERTIES_EXTENSION)) {
      String rootPath = sourceFile.substring(0, sourceFile.length()
                                                - FORM_PROPERTIES_EXTENSION.length());
      String yailFilePath = rootPath + YAIL_EXTENSION;
      // Note: Famous last words: The following contains() makes this method O(n**2) but n should
      // be pretty small.
      if (!sourceFiles.contains(yailFilePath)) {
        generateYail(rootPath);
      }
    }
  }
}
项目:ProjectAres    文件:QuotaConfig.java   
@Inject QuotaConfig(Configuration root) {
    this.config = root.getConfigurationSection("match-quotas");
    if(config == null) {
        quotas = new TreeSet<>();
    } else {
        quotas = new TreeSet<>(Collections2.transform(
            config.getKeys(false),
            new Function<String, Entry>() {
                @Override
                public Entry apply(@Nullable String key) {
                    return new Entry(config.getConfigurationSection(key));
                }
            }
        ));
    }
}
项目:redirector    文件:NamespacedListsHolder.java   
@VisibleForTesting
void loadFromDataStore() {
    try {
        Date date = new Date();
        int version = commonModelFacade.getNextNamespacedListsVersion();
        log.info("Start getting NamespacedList(listVersion={}) from WS - startTime={}", version, date.getTime());
        NamespacedListsBatch namespacedListsBatch = new NamespacedListsBatch();
        namespacedListsBatch.setDataNodeVersion(version);
        for (NamespacedList item : commonModelFacade.getAllNamespacedLists()) {
            namespacedListsBatch.addValues(item.getName(), Collections2.transform(item.getValueSet(),
                    item.getType().equals(NamespacedListType.ENCODED) ? NamespacedListValueForWS::getEncodedValue : NamespacedListValueForWS::getValue));
        }
        setNamespacedListsBatch(namespacedListsBatch);

        Long endTime = (new Date()).getTime();
        log.info("End getting NamespacedList from WS - endTime=" + endTime + ", total duration=" + (endTime - date.getTime()) + " millis");
    } catch (Exception e) {
        log.error("Failed to load NamespacedList from commonModelFacade: {}", e.getMessage());
        throw e;
    }
}
项目:Equella    文件:ShareWithOthersContentSection.java   
@Override
public List<SelectedUser> getCurrentSelectedUsers(SectionInfo info)
{
    return Lists.newArrayList(
        Collections2.transform(ParentViewItemSectionUtils.getItemInfo(info).getItem().getNotifications(),
            new Function<String, SelectedUser>()
            {
                @Override
                public SelectedUser apply(String uuidOrEmail)
                {
                    final UserBean userBean = userService.getInformationForUser(uuidOrEmail);
                    final String displayName;
                    if( userBean == null )
                    {
                        displayName = uuidOrEmail;
                    }
                    else
                    {
                        displayName = Format.format(userBean);
                    }
                    return new SelectedUser(uuidOrEmail, displayName);
                }
            }));
}
项目:Equella    文件:ChangeOwnershipContentSection.java   
@Override
public List<SelectedUser> getCurrentSelectedUsers(SectionInfo info)
{
    return Lists.newArrayList(
        Collections2.transform(ParentViewItemSectionUtils.getItemInfo(info).getItem().getCollaborators(),
            new Function<String, SelectedUser>()
            {
                @Override
                public SelectedUser apply(final String uuidOrEmail)
                {
                    final UserBean userBean = userService.getInformationForUser(uuidOrEmail);
                    final String displayName;
                    if( userBean == null )
                    {
                        displayName = uuidOrEmail;
                    }
                    else
                    {
                        displayName = Format.format(userBean);
                    }
                    return new SelectedUser(uuidOrEmail, displayName);
                }
            }));
}
项目:Equella    文件:AbstractSelectGroupSection.java   
/**
 * Must be set before registering the dialog
 * 
 * @param groupFilter
 */
public void setGroupFilter(Set<String> groupFilter)
{
    if( !Check.isEmpty(groupFilter) )
    {
        this.groupFilter = groupFilter;

        final Collection<GroupBean> groupBeans = userService.getInformationForGroups(groupFilter).values();
        final Collection<String> gn = Collections2.transform(groupBeans, new Function<GroupBean, String>()
        {
            @Override
            public String apply(GroupBean group)
            {
                return group.getName();
            }
        });
        groupFilterNames = Lists.newArrayList(gn);
        Collections.sort(groupFilterNames);
    }
}
项目:CountryCurrencyPicker    文件:Country.java   
public static ArrayList<Country> listAll(Context context, final String filter) {
    ArrayList<Country> list = new ArrayList<>();

    for (String countryCode : Locale.getISOCountries()) {
        Country country = getCountry(countryCode, context);

        list.add(country);
    }

    sortList(list);

    if (filter != null && filter.length() > 0) {
        return new ArrayList<>(Collections2.filter(list, new Predicate<Country>() {
            @Override
            public boolean apply(Country input) {
                return input.getName().toLowerCase().contains(filter.toLowerCase());
            }
        }));
    } else {
        return list;
    }
}
项目:CountryCurrencyPicker    文件:Currency.java   
public static ArrayList<Currency> listAll(Context context, final String filter) {
    ArrayList<Currency> list = new ArrayList<>();

    for (java.util.Currency currency : java.util.Currency.getAvailableCurrencies()) {
        list.add(getCurrency(currency, context));
    }

    sortList(list);

    if (filter != null && filter.length() > 0) {
        return new ArrayList<>(Collections2.filter(list, new Predicate<Currency>() {
            @Override
            public boolean apply(Currency input) {
                return input.getName().toLowerCase().contains(filter.toLowerCase()) ||
                        input.getSymbol().toLowerCase().contains(filter.toLowerCase());
            }
        }));
    } else {
        return list;
    }
}
项目:twister2    文件:CppCheckstyle.java   
@SuppressWarnings("unchecked")
private static Collection<String> getSourceFiles(String extraActionFile) {

  ExtraActionInfo info = ExtraActionUtils.getExtraActionInfo(extraActionFile);
  CppCompileInfo cppInfo = info.getExtension(CppCompileInfo.cppCompileInfo);

  return Collections2.filter(
          cppInfo.getSourcesAndHeadersList(),
          Predicates.and(
                  Predicates.not(Predicates.containsPattern("third_party/")),
                  Predicates.not(Predicates.containsPattern("config/heron-config.h")),
                  Predicates.not(Predicates.containsPattern(".*pb.h$")),
                  Predicates.not(Predicates.containsPattern(".*cc_wrapper.sh$")),
                  Predicates.not(Predicates.containsPattern(".*pb.cc$"))
          )
  );
}
项目:hashsdn-controller    文件:TOAttribute.java   
@Override
public CompositeType getOpenType() {
    final String description = getNullableDescription() == null ? getAttributeYangName() : getNullableDescription();

    final FunctionImpl functionImpl = new FunctionImpl();
    final Map<String, AttributeIfc> jmxPropertiesToTypesMap = getJmxPropertiesToTypesMap();
    final OpenType<?>[] itemTypes = Collections2.transform(
            jmxPropertiesToTypesMap.entrySet(), functionImpl).toArray(
            new OpenType<?>[] {});
    final String[] itemNames = functionImpl.getItemNames();
    try {
        // TODO add package name to create fully qualified name for this
        // type
        final CompositeType compositeType = new CompositeType(
                getUpperCaseCammelCase(), description, itemNames,
                itemNames, itemTypes);
        return compositeType;
    } catch (final OpenDataException e) {
        throw new RuntimeException("Unable to create CompositeType for "
                + this, e);
    }
}
项目:vscrawler    文件:EventLoop.java   
public void offerEvent(final Event event) {
    if (!isRunning.get()) {
        log.warn("程序已停止");
        return;
    }
    if (!allHandlers.containsKey(event.getTopic()) || allHandlers.get(event.getTopic()).size() < 0) {
        log.debug("cannot find handle for event:{}", event.getTopic());
        return;
    }
    if (event.isSync()) {
        disPatch(event);
        return;
    }
    if (event.isCleanExpire()) {
        eventQueue.removeAll(Collections2.filter(eventQueue, new Predicate<Event>() {
            @Override
            public boolean apply(Event input) {
                return StringUtils.equals(input.getTopic(), event.getTopic());
            }
        }));
    }
    eventQueue.put(event);


}
项目:Elasticsearch    文件:MapSideDataCollectOperation.java   
private Collection<Runnable> collectors2Runnables(Collection<CrateCollector> collectors) {
    return Collections2.transform(collectors, new Function<CrateCollector, Runnable>() {
        @Override
        public Runnable apply(final CrateCollector collector) {
            return new Runnable() {
                @Override
                public void run() {
                    collector.doCollect();
                }
            };
        }
    });
}
项目:redirector    文件:StacksService.java   
List<PathItem> getFlavorsPathItems(Map<XreStackPath, Integer> stackToNodesCount, Map<XreStackPath, Integer> whitelistedStackToNodesCount) {
    Map<String, Integer> flavorToCount = getFlavorToCountMap(stackToNodesCount);
    final Map<String, Integer> flavorToWhitelistedCount = getFlavorToCountMap(whitelistedStackToNodesCount);

    return Lists.newArrayList(Collections2.transform(flavorToCount.entrySet(), new Function<Map.Entry<String, Integer>, PathItem>() {
        @Override
        public PathItem apply(Map.Entry<String, Integer> input) {
            String flavor = input.getKey();
            int count = input.getValue();
            int whitelistedCount = flavorToWhitelistedCount.containsKey(flavor) ? flavorToWhitelistedCount.get(flavor) : 0;
            return new PathItem(flavor, count, whitelistedCount);
        }
    }));
}
项目:Reer    文件:AbstractTask.java   
private Collection<ContextAwareTaskAction> transformToContextAwareTaskActions(Collection<Object> c) {
    return Collections2.transform(c, new Function<Object, ContextAwareTaskAction>() {
        public ContextAwareTaskAction apply(@Nullable Object input) {
            return wrap((Action<? super Task>) input);
        }
    });
}
项目:morf    文件:ViewChanges.java   
/**
 * Construct a description of view changes based on the supplied drop and deploy requirements
 * together with some dependency analysis.
 *
 * <p>The drop set is expanded based on dependency analysis: any view that depends on a dropped
 * view will also be dropped.</p>
 *
 * <p>The deployment set is expanded only to include the items that are added to the drop set -
 * i.e. if we determine that a view needs to be recreated because a dependencies is dropped,
 * then it will be added to both the drop and deploy sets. Views will not be added to the
 * deploy set based on dependency analysis - it is assumed that all missing views will
 * already be in the deploy set.</p>
 *
 * <p>All parameters may be immutable.</p>
 *
 * @param allViews all the views as defined in the codeset and bound in to the application. This is the 'source of truth' as to which views are available.
 * @param viewsToDrop Views which should be dropped from the current schema. Caller must ensure names are unique within the collection.
 * @param viewsToDeploy Views which should be deployed from the target schema. Caller must ensure names are unique within the collection.
 */
public ViewChanges(Collection<View> allViews, Collection<View> viewsToDrop, Collection<View> viewsToDeploy) {
  super();

  // -- Store our dependency information as we may need to pass it on...
  //
  this.allViews = allViews;

  // -- Work with sets of strings internally, we switch back to views when we return ordered lists...
  //
  this.knownSet = newHashSet(Collections2.transform(allViews, viewToName()));
  this.dropSet = newHashSet(correctCase(Collections2.transform(viewsToDrop, viewToName())));
  this.deploySet = newHashSet(Collections2.transform(viewsToDeploy, viewToName()));

  // -- Maintain an index of name to view so we can convert back. Must contain allViews + viewsToDrop for obsolete views...
  //
  viewIndex.putAll(uniqueIndex(viewsToDrop, viewToName()));
  viewIndex.putAll(uniqueIndex(allViews, viewToName())); // known views take precedence as we have more complete info

  // -- Perform a topological sort of all dependent views (based on bound in views, not the contents of the DB)...
  //
  viewCreationOrder = topoSortViews(allViews, viewIndex);

  // -- Add any obsolete views back into the order in an arbitrary position (they need to be dropped
  //    but we have no dependency information to indicate where)...
  //
  viewCreationOrder.addAll(Sets.difference(newHashSet(this.dropSet), newHashSet(this.knownSet)));
}
项目:empiria.player    文件:SurfacesOffsetsExtractor.java   
public Collection<Integer> extractTopOffsets(ConnectionItems items) {
    return Collections2.transform(items.getAllItems(), new Function<ConnectionItem, Integer>() {

        @Override
        @Nullable
        public Integer apply(@Nullable ConnectionItem ci) {
            return ci.getOffsetTop();
        }
    });
}
项目:empiria.player    文件:SurfacesOffsetsExtractor.java   
public Collection<Integer> extractBottomOffsets(ConnectionItems items) {
    return Collections2.transform(items.getAllItems(), new Function<ConnectionItem, Integer>() {

        @Override
        @Nullable
        public Integer apply(@Nullable ConnectionItem ci) {
            return ci.getOffsetTop() + ci.getHeight();
        }
    });
}
项目:empiria.player    文件:SurfacesOffsetsExtractor.java   
public Collection<Integer> extractRightOffsets(ConnectionItems items) {
    return Collections2.transform(items.getAllItems(), new Function<ConnectionItem, Integer>() {

        @Override
        @Nullable
        public Integer apply(@Nullable ConnectionItem ci) {
            return ci.getOffsetLeft() + ci.getWidth();
        }
    });
}
项目:empiria.player    文件:ResponseAnswerGrouper.java   
private Collection<GroupedAnswer> findAllGroupedAnswersByValue(final String value) {

        Collection<GroupedAnswer> answersWithValue = Collections2.filter(groupedAnswers, new Predicate<GroupedAnswer>() {
            @Override
            public boolean apply(GroupedAnswer groupedAnswer) {
                return value.equals(groupedAnswer.getValue());
            }
        });

        return answersWithValue;
    }
项目:athena    文件:StoragePartition.java   
/**
 * Attempts to join the partition as a new member.
 * @return future that is completed after the operation is complete
 */
private CompletableFuture<Void> joinCluster() {
    Set<NodeId> otherMembers = partition.getMembers()
             .stream()
             .filter(nodeId -> !nodeId.equals(localNodeId))
             .collect(Collectors.toSet());
    StoragePartitionServer server = new StoragePartitionServer(toAddress(localNodeId),
            this,
            serializer,
            () -> new CopycatTransport(CopycatTransport.Mode.SERVER,
                                 partition.getId(),
                                 messagingService),
            logFolder);
    return server.join(Collections2.transform(otherMembers, this::toAddress)).thenRun(() -> this.server = server);
}
项目:morf    文件:ViewChanges.java   
/**
 * @param extraViewsToDeploy Additional views to deploy
 * @return a new {@link ViewChanges} which also deploys the specified views.
 */
public ViewChanges deployingAlso(Collection<View> extraViewsToDeploy) {
  Set<String> extraViewNames = ImmutableSet.copyOf(Collections2.transform(extraViewsToDeploy, viewToName()));
  return new ViewChanges(allViews,
    dropSet,
    Sets.union(deploySet, extraViewNames),
    viewIndex);
}
项目:verify-hub    文件:IdentityProviderResource.java   
@GET
@Path(Urls.ConfigUrls.ENABLED_IDENTITY_PROVIDERS_PARAM_PATH)
@Timed
@Deprecated
public Collection<String> getEnabledIdentityProviderEntityIdsPathParam(
        @PathParam(Urls.ConfigUrls.ENTITY_ID_PATH_PARAM) final Optional<String> transactionEntityId) {

    Collection<IdentityProviderConfigEntityData> matchingIdps = getIdentityProviderConfigEntityData(transactionEntityId);

    return Collections2.transform(matchingIdps, new IdpEntityIdExtractor());
}
项目:verify-hub    文件:IdpPredicateFactoryTest.java   
@Test
public void createPredicatesForTransactionEntityAndLoA_shouldNotIncludeExtraPredicate() throws Exception {
    Set<Predicate<IdentityProviderConfigEntityData>> predicates = idpPredicateFactory.createPredicatesForTransactionEntityAndLoa(TRANSACTION_ENTITY, LEVEL_OF_ASSURANCE);

    Predicate<Predicate> findEnabled = input -> input instanceof EnabledIdpPredicate;
    Predicate<Predicate> findOnboarding = input -> input instanceof OnboardingIdpPredicate;
    Predicate<Predicate> supportedLoa = input -> input instanceof SupportedLoaIdpPredicate;

    assertThat(predicates).hasSize(3);
    assertThat(Collections2.filter(predicates, findEnabled)).hasSize(1);
    assertThat(Collections2.filter(predicates, findOnboarding)).hasSize(1);
    assertThat(Collections2.filter(predicates, supportedLoa)).hasSize(1);
}
项目:verify-hub    文件:IdpPredicateFactoryTest.java   
@Test
public void createPredicatesForTransactionEntity_shouldIncludeTransactionEntityPredicateWhenTransactionEntityIdIsProvided() throws Exception {
    Set<Predicate<IdentityProviderConfigEntityData>> predicates =
            idpPredicateFactory.createPredicatesForTransactionEntity(ofNullable(TRANSACTION_ENTITY));

    Predicate<Predicate> findEnabled = input -> {
        if(!(input instanceof OnboardingForTransactionEntityPredicate)){
            return false;
        }

        return ((OnboardingForTransactionEntityPredicate)input).getTransactionEntity().equals(TRANSACTION_ENTITY);
    };

    assertThat(Collections2.filter(predicates, findEnabled)).hasSize(1);
}
项目:verify-hub    文件:IdpPredicateFactoryTest.java   
@Test
public void createPredicatesForTransactionEntity_shouldNotIncludeTransactionEntityPredicateWhenTransactionEntityIdIsNotProvided() throws Exception {
    Set<Predicate<IdentityProviderConfigEntityData>> predicates = idpPredicateFactory.createPredicatesForTransactionEntity(null);

    Predicate<Predicate> findEnabled = input -> {
        if(!(input instanceof OnboardingForTransactionEntityPredicate)){
            return false;
        }

        return ((OnboardingForTransactionEntityPredicate)input).getTransactionEntity().equals(TRANSACTION_ENTITY);
    };

    assertThat(Collections2.filter(predicates, findEnabled)).isEmpty();
}
项目:burp-vulners-scanner    文件:Utils.java   
public static Double getMaxScore(Set<Vulnerability> vulnerabilities) {
    if (vulnerabilities.size() <= 0) {
        return null;
    }

    Collection<Double> scores = Collections2.transform(
            vulnerabilities, new Function<Vulnerability, Double>() {
                @Override
                public Double apply(Vulnerability vulnerability) {
                    return vulnerability.getCvssScore();
                }
            }
    );
    return Ordering.natural().max(scores);
}
项目:morf    文件:ViewChanges.java   
/**
 * Correct case of names with respect to all the views we know about.
 *
 * @return equivalent collection with names case-corrected where possible.
 */
private Collection<String> correctCase(Collection<String> names) {
  return newHashSet(Collections2.transform(names, new Function<String, String>() {
    @Override public String apply(String name) {
      for (View view: allViews) {
        if (view.getName().equalsIgnoreCase(name)) {
          return view.getName();
        }
      }
      return name;
    }
  }));
}
项目:redirector    文件:StacksService.java   
private Collection<XreStackPath> getStackPathsForServiceAndFlavor(final String serviceName, final String flavor) {
    return Collections2.filter(stacksDAO.getAllStackPaths(), new Predicate<XreStackPath>() {
        @Override
        public boolean apply(XreStackPath input) {
            return input.getServiceName().equals(serviceName) && input.getFlavor().equals(flavor);
        }
    });
}
项目:elastic-job-cloud    文件:MesosStateService.java   
/**
 * 查找执行器信息.
 * 
 * @param appName 作业云配置App的名字
 * @return 执行器信息
 * @throws JSONException 解析JSON格式异常
 */
public Collection<ExecutorStateInfo> executors(final String appName) throws JSONException {
    return Collections2.transform(findExecutors(fetch(stateUrl).getJSONArray("frameworks"), appName), new Function<JSONObject, ExecutorStateInfo>() {
        @Override
        public ExecutorStateInfo apply(final JSONObject input) {
            try {
                return ExecutorStateInfo.builder().id(getExecutorId(input)).slaveId(input.getString("slave_id")).build();
            } catch (final JSONException ex) {
                throw new RuntimeException(ex);
            }
        }
    });
}
项目:elastic-job-cloud    文件:ReadyService.java   
/**
 * 从待执行队列中获取所有有资格执行的作业上下文.
 *
 * @param ineligibleJobContexts 无资格执行的作业上下文
 * @return 有资格执行的作业上下文集合
 */
public Collection<JobContext> getAllEligibleJobContexts(final Collection<JobContext> ineligibleJobContexts) {
    if (!regCenter.isExisted(ReadyNode.ROOT)) {
        return Collections.emptyList();
    }
    Collection<String> ineligibleJobNames = Collections2.transform(ineligibleJobContexts, new Function<JobContext, String>() {

        @Override
        public String apply(final JobContext input) {
            return input.getJobConfig().getJobName();
        }
    });
    List<String> jobNames = regCenter.getChildrenKeys(ReadyNode.ROOT);
    List<JobContext> result = new ArrayList<>(jobNames.size());
    for (String each : jobNames) {
        if (ineligibleJobNames.contains(each)) {
            continue;
        }
        Optional<CloudJobConfiguration> jobConfig = configService.load(each);
        if (!jobConfig.isPresent()) {
            regCenter.remove(ReadyNode.getReadyJobNodePath(each));
            continue;
        }
        if (!runningService.isJobRunning(each)) {
            result.add(JobContext.from(jobConfig.get(), ExecutionType.READY));
        }
    }
    return result;
}
项目:minijax    文件:MinijaxSwaggerTest.java   
@Test
public void returnProperBeanParamWithDefaultParameterExtension() throws NoSuchMethodException {
    final Method method = getClass().getDeclaredMethod("testRoute", BaseBean.class, ChildBean.class, RefBean.class, EnumBean.class, Integer.class);
    final List<Pair<Type, Annotation[]>> parameters = getParameters(method.getGenericParameterTypes(), method.getParameterAnnotations());

    for (final Pair<Type, Annotation[]> parameter : parameters) {
        final Type parameterType = parameter.first();
        final List<Parameter> swaggerParams = new DefaultParameterExtension().extractParameters(Arrays.asList(parameter.second()),
                parameterType, new HashSet<Type>(), SwaggerExtensions.chain());
        // Ensure proper number of parameters returned
        if (parameterType.equals(BaseBean.class)) {
            assertEquals(2, swaggerParams.size());
        } else if (parameterType.equals(ChildBean.class)) {
            assertEquals(5, swaggerParams.size());
        } else if (parameterType.equals(RefBean.class)) {
            assertEquals(5, swaggerParams.size());
        } else if (parameterType.equals(EnumBean.class)) {
            assertEquals(1, swaggerParams.size());
            final HeaderParameter enumParam = (HeaderParameter) swaggerParams.get(0);
            assertEquals("string", enumParam.getType());
            final List<String> enumValues = new ArrayList<>(Collections2.transform(Arrays.asList(TestEnum.values()), Functions.toStringFunction()));
            assertEquals(enumValues, enumParam.getEnum());
        } else if (parameterType.equals(Integer.class)) {
            assertEquals(0, swaggerParams.size());
        } else {
            fail(String.format("Parameter of type %s was not expected", parameterType));
        }

        // Ensure the proper parameter type and name is returned (The rest is handled by pre-existing logic)
        for (final Parameter param : swaggerParams) {
            assertEquals(param.getClass().getSimpleName().replace("eter", ""), param.getName());
        }
    }
}
项目:ProjectAres    文件:PGMMapEnvironment.java   
@Override
public Set<Entry<String, Boolean>> entrySet() {
    return ImmutableSet.copyOf(Collections2.transform(
        keySet(),
        key -> Maps.immutableEntry(key, get(key))
    ));
}
项目:ProjectAres    文件:TouchableGoal.java   
@Override
public Collection<? extends MatchDoc.TouchableGoal.Proximity> proximities() {
    return Collections2.transform(
        getMatch().getCompetitors(),
        new Function<Competitor, MatchDoc.TouchableGoal.Proximity>() {
            @Override
            public MatchDoc.TouchableGoal.Proximity apply(Competitor competitor) {
                return new Proximity(competitor);
            }
        }
    );
}
项目:ProjectAres    文件:MatchAnnouncer.java   
public void sendWelcomeMessage(MatchPlayer viewer) {
    MapInfo mapInfo = viewer.getMatch().getMapInfo();
    final Component name = new Component(mapInfo.name, ChatColor.BOLD, ChatColor.AQUA);
    final Component objective = new Component(mapInfo.objective, ChatColor.BLUE, ChatColor.ITALIC);

    if(Config.Broadcast.title()) {
        viewer.getBukkit().showTitle(name, objective, TITLE_FADE, TITLE_STAY, TITLE_FADE);
    }

    viewer.sendMessage(new HeaderComponent(ChatColor.WHITE, CHAT_WIDTH, name));

    for(BaseComponent line : Components.wordWrap(objective, CHAT_WIDTH)) {
        viewer.sendMessage(line);
    }

    final List<Contributor> authors = mapInfo.getNamedAuthors();
    if(!authors.isEmpty()) {
        viewer.sendMessage(
            new Component(" ", ChatColor.DARK_GRAY).extra(
                new TranslatableComponent(
                    "broadcast.welcomeMessage.createdBy",
                    new ListComponent(Lists.transform(authors, author -> author.getStyledName(NameStyle.MAPMAKER)))
                )
            )
        );
    }

    final MutationMatchModule mmm = viewer.getMatch().getMatchModule(MutationMatchModule.class);
    if(mmm != null && mmm.getActiveMutations().size() > 0) {
        viewer.sendMessage(
            new Component(" ", ChatColor.DARK_GRAY).extra(
                new TranslatableComponent("broadcast.welcomeMessage.mutations",
                                          new ListComponent(Collections2.transform(mmm.getActiveMutations(), Mutation.toComponent(ChatColor.GREEN)))
                )
            )
        );
    }

    viewer.sendMessage(new HeaderComponent(ChatColor.WHITE, CHAT_WIDTH));
}