Java Code Examples for com.google.common.collect.Collections2

The following are top voted examples for showing how to use com.google.common.collect.Collections2. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Reer   File: StructSchemaExtractionStrategySupport.java   View source code 6 votes vote down vote up
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();
        }
    });
}
 
Example 2
Project: smarti   File: MongoUserDetailsService.java   View source code 6 votes vote down vote up
@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;
}
 
Example 3
Project: vscrawler   File: FetchTaskProcessor.java   View source code 6 votes vote down vote up
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;
}
 
Example 4
Project: burp-vulners-scanner   File: SoftwareIssue.java   View source code 6 votes vote down vote up
@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();
}
 
Example 5
Project: burp-vulners-scanner   File: PathIssue.java   View source code 6 votes vote down vote up
@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();
}
 
Example 6
Project: hashsdn-controller   File: InstanceRuntime.java   View source code 6 votes vote down vote up
/**
 * 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;
    }));
}
 
Example 7
Project: appinventor-extensions   File: ProjectBuilder.java   View source code 6 votes vote down vote up
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);
      }
    }
  }
}
 
Example 8
Project: ProjectAres   File: QuotaConfig.java   View source code 6 votes vote down vote up
@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));
                }
            }
        ));
    }
}
 
Example 9
Project: redirector   File: NamespacedListsHolder.java   View source code 6 votes vote down vote up
@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;
    }
}
 
Example 10
Project: Equella   File: ShareWithOthersContentSection.java   View source code 6 votes vote down vote up
@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);
				}
			}));
}
 
Example 11
Project: Equella   File: ChangeOwnershipContentSection.java   View source code 6 votes vote down vote up
@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);
				}
			}));
}
 
Example 12
Project: Equella   File: AbstractSelectGroupSection.java   View source code 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 13
Project: CountryCurrencyPicker   File: Country.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 14
Project: CountryCurrencyPicker   File: Currency.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 15
Project: twister2   File: CppCheckstyle.java   View source code 6 votes vote down vote up
@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$"))
          )
  );
}
 
Example 16
Project: hashsdn-controller   File: TOAttribute.java   View source code 6 votes vote down vote up
@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);
    }
}
 
Example 17
Project: vscrawler   File: EventLoop.java   View source code 6 votes vote down vote up
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);


}
 
Example 18
Project: Elasticsearch   File: MapSideDataCollectOperation.java   View source code 5 votes vote down vote up
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();
                }
            };
        }
    });
}
 
Example 19
Project: redirector   File: StacksService.java   View source code 5 votes vote down vote up
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);
        }
    }));
}
 
Example 20
Project: Reer   File: AbstractTask.java   View source code 5 votes vote down vote up
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);
        }
    });
}
 
Example 21
Project: morf   File: ViewChanges.java   View source code 5 votes vote down vote up
/**
 * 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)));
}
 
Example 22
Project: empiria.player   File: SurfacesOffsetsExtractor.java   View source code 5 votes vote down vote up
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();
        }
    });
}
 
Example 23
Project: empiria.player   File: SurfacesOffsetsExtractor.java   View source code 5 votes vote down vote up
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();
        }
    });
}
 
Example 24
Project: empiria.player   File: SurfacesOffsetsExtractor.java   View source code 5 votes vote down vote up
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();
        }
    });
}
 
Example 25
Project: empiria.player   File: ResponseAnswerGrouper.java   View source code 5 votes vote down vote up
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;
    }
 
Example 26
Project: athena   File: StoragePartition.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 27
Project: morf   File: ViewChanges.java   View source code 5 votes vote down vote up
/**
 * @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);
}
 
Example 28
Project: verify-hub   File: IdentityProviderResource.java   View source code 5 votes vote down vote up
@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());
}
 
Example 29
Project: verify-hub   File: IdpPredicateFactoryTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 30
Project: verify-hub   File: IdpPredicateFactoryTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 31
Project: verify-hub   File: IdpPredicateFactoryTest.java   View source code 5 votes vote down vote up
@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();
}
 
Example 32
Project: burp-vulners-scanner   File: Utils.java   View source code 5 votes vote down vote up
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);
}
 
Example 33
Project: morf   File: ViewChanges.java   View source code 5 votes vote down vote up
/**
 * 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;
    }
  }));
}
 
Example 34
Project: redirector   File: StacksService.java   View source code 5 votes vote down vote up
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);
        }
    });
}
 
Example 35
Project: elastic-job-cloud   File: MesosStateService.java   View source code 5 votes vote down vote up
/**
 * 查找执行器信息.
 * 
 * @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);
            }
        }
    });
}
 
Example 36
Project: elastic-job-cloud   File: ReadyService.java   View source code 5 votes vote down vote up
/**
 * 从待执行队列中获取所有有资格执行的作业上下文.
 *
 * @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;
}
 
Example 37
Project: minijax   File: MinijaxSwaggerTest.java   View source code 5 votes vote down vote up
@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());
        }
    }
}
 
Example 38
Project: ProjectAres   File: PGMMapEnvironment.java   View source code 5 votes vote down vote up
@Override
public Set<Entry<String, Boolean>> entrySet() {
    return ImmutableSet.copyOf(Collections2.transform(
        keySet(),
        key -> Maps.immutableEntry(key, get(key))
    ));
}
 
Example 39
Project: ProjectAres   File: TouchableGoal.java   View source code 5 votes vote down vote up
@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);
            }
        }
    );
}
 
Example 40
Project: ProjectAres   File: MatchAnnouncer.java   View source code 5 votes vote down vote up
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));
}