Example usage for com.google.common.collect Sets difference

List of usage examples for com.google.common.collect Sets difference

Introduction

In this page you can find the example usage for com.google.common.collect Sets difference.

Prototype

public static <E> SetView<E> difference(final Set<E> set1, final Set<?> set2) 

Source Link

Document

Returns an unmodifiable view of the difference of two sets.

Usage

From source file:org.jclouds.location.suppliers.all.ZoneToRegionToProviderOrJustProvider.java

private Map<String, Location> setParentOfZoneToRegionOrProvider(Set<String> zoneIds,
        Set<? extends Location> locations) {
    // mutable, so that we can query current state when adding. safe as its temporary
    Map<String, Location> zoneIdToParent = Maps.newLinkedHashMap();

    Location provider = Iterables.find(locations, LocationPredicates.isProvider(), null);
    if (locations.size() == 1 && provider != null) {
        for (String zone : zoneIds)
            zoneIdToParent.put(zone, provider);
    } else {/*  w ww  .  jav  a 2  s. co  m*/
        // note that we only call regionIdToZoneIdsSupplier if there are region locations present
        // they cannot be, if the above is true
        Map<String, Supplier<Set<String>>> regionIdToZoneIds = regionIdToZoneIdsSupplier.get();
        for (Location region : Iterables.filter(locations, LocationPredicates.isRegion())) {
            provider = region.getParent();
            if (regionIdToZoneIds.containsKey(region.getId())) {
                for (String zoneId : regionIdToZoneIds.get(region.getId()).get())
                    zoneIdToParent.put(zoneId, region);
            } else {
                logger.debug("no zones configured for region: %s", region);
            }
        }
    }

    SetView<String> orphans = Sets.difference(zoneIds, zoneIdToParent.keySet());
    if (orphans.size() > 0) {
        // any unmatched zones should have their parents set to the provider
        checkState(provider != null,
                "cannot configure zones %s as we need a parent, and the only available location [%s] is not a provider",
                zoneIds, locations);
        for (String orphanedZoneId : orphans)
            zoneIdToParent.put(orphanedZoneId, provider);
    }

    checkState(zoneIdToParent.keySet().containsAll(zoneIds), "orphaned zones: %s ",
            Sets.difference(zoneIds, zoneIdToParent.keySet()));
    return zoneIdToParent;
}

From source file:org.eclipse.emf.compare.internal.merge.MergeDependenciesUtil.java

/**
 * Retrieves the set of all diffs related to the given <code>diff</code> when merging in the given
 * direction./*w w  w .j  a  va 2s .  c  o  m*/
 * <p>
 * This is expected to return the set of all differences that will be need to merged along when a user
 * wishes to merge <code>diff</code>, either because they are required by it or because they are implied
 * by it one way or another.
 * </p>
 * <p>
 * Note that <code>diff</code> will be included in the returned set.
 * </p>
 * 
 * @param diff
 *            The difference for which we seek all related ones.
 * @param mergerRegistry
 *            The {@link IMerger.Registry merger registry} currently in use.
 * @param mergeRightToLeft
 *            The direction in which we're considering a merge.
 * @return The set of all diffs related to the given <code>diff</code> when merging in the given
 *         direction.
 */
public static Set<Diff> getAllResultingMerges(Diff diff, IMerger.Registry mergerRegistry,
        boolean mergeRightToLeft) {
    final Set<Diff> resultingMerges = new LinkedHashSet<Diff>();
    resultingMerges.add(diff);

    Set<Diff> relations = internalGetResultingMerges(diff, mergerRegistry, mergeRightToLeft, diff.getSource());
    Set<Diff> difference = Sets.difference(relations, resultingMerges);
    while (!difference.isEmpty()) {
        final Set<Diff> newRelations = new LinkedHashSet<Diff>(difference);
        resultingMerges.addAll(newRelations);
        relations = new LinkedHashSet<Diff>();
        for (Diff newRelation : newRelations) {
            relations.addAll(internalGetResultingMerges(newRelation, mergerRegistry, mergeRightToLeft,
                    diff.getSource()));
        }
        difference = Sets.difference(relations, resultingMerges);
    }

    return resultingMerges;
}

From source file:com.linecorp.armeria.server.http.dynamic.Methods.java

/**
 * Returns a {@link DynamicHttpFunctionEntry} instance defined to {@code method} of {@code object} using
 * {@link Path} annotation./*from   w ww  .  j a v a 2 s  . c  o  m*/
 */
private static DynamicHttpFunctionEntry entry(Object object, Method method,
        Map<Class<?>, ResponseConverter> converters) {
    Set<HttpMethod> methods = httpMethods(method);
    if (methods.isEmpty()) {
        throw new IllegalArgumentException("HTTP Method specification is missing: " + method.getName());
    }
    DynamicPath dynamicPath = dynamicPath(method);
    DynamicHttpFunctionImpl function = new DynamicHttpFunctionImpl(object, method);

    Set<String> parameterNames = function.parameterNames();
    Set<String> pathVariableNames = dynamicPath.variables();
    if (!pathVariableNames.containsAll(parameterNames)) {
        Set<String> missing = Sets.difference(parameterNames, pathVariableNames);
        throw new IllegalArgumentException("Missing @PathParam exists: " + missing);
    }

    ResponseConverter converter = converter(method);
    if (converter != null) {
        return new DynamicHttpFunctionEntry(methods, dynamicPath, DynamicHttpFunctions.of(function, converter));
    } else {
        Map<Class<?>, ResponseConverter> converterMap = new HashMap<>();
        // Pre-defined converters
        converterMap.putAll(converters);
        // Converters given by @Converter annotation
        converterMap.putAll(converters(method.getDeclaringClass()));
        return new DynamicHttpFunctionEntry(methods, dynamicPath,
                DynamicHttpFunctions.of(function, converterMap));
    }
}

From source file:gg.uhc.uhc.modules.team.RandomTeamsCommand.java

@Override
protected boolean runCommand(CommandSender sender, OptionSet options) {
    int size = -1;
    int count = -1;

    if (options.has(teamCountSpec)) {
        count = teamCountSpec.value(options);
    }/*from   w ww. j  av  a  2 s .  c  o  m*/

    if (options.has(teamSizeSpec)) {
        size = teamSizeSpec.value(options);
    }

    if ((size == -1 && count == -1) || (size != -1 && count != -1)) {
        sender.sendMessage(messages.getRaw("count or size"));
        return true;
    }

    Set<Player> choice = Sets.newHashSet(playersSpec.values(options));

    // if none are provided then add all online players
    if (choice.size() == 0) {
        choice = Sets.newHashSet(Bukkit.getOnlinePlayers());
    }

    // parse excludes into online players
    Set<Player> excludes = Sets.newHashSet(
            Iterables.filter(Iterables.transform(excludingSpec.values(options), FunctionalUtil.ONLINE_VERSION),
                    Predicates.notNull()));

    // final list with excludes removed and players that already in a team
    List<Player> toAssign = Lists
            .newArrayList(Iterables.filter(Sets.difference(choice, excludes), Predicates.not(PLAYER_HAS_TEAM)));

    if (toAssign.size() == 0) {
        sender.sendMessage(messages.getRaw("no players"));
        return true;
    }

    Collections.shuffle(toAssign);

    // calculate team sizes to fit in count teams and assign it to size and carry on as if it was a sized command
    if (count != -1) {
        size = (int) Math.ceil((double) toAssign.size() / (double) count);
    }

    // partition into teams
    List<List<Player>> teams = Lists.newArrayList(Lists.partition(toAssign, size));

    int extras = toAssign.size() % size;

    // if we're excluding leftovers and there were leftovers in a final
    // team, then remove that team from the list. If it's the only team
    // then send a message saying no teams could be created.
    if (options.has(excludeExtrasSpec) && extras > 0) {
        if (teams.size() == 1) {
            sender.sendMessage(messages.evalTemplate("not enough players", ImmutableMap.of("size", size)));
            return true;
        }

        teams.remove(teams.size() - 1);
    }

    // start assigning teams
    for (List<Player> teamPlayers : teams) {
        Optional<Team> optional = module.findFirstEmptyTeam();

        if (!optional.isPresent()) {
            sender.sendMessage(messages.getRaw("not enough teams"));
            return true;
        }

        Team team = optional.get();
        String playerNames = Joiner.on(", ")
                .join(Iterables.transform(teamPlayers, FunctionalUtil.PLAYER_NAME_FETCHER));

        //"teamup notification" : ${colours.command}"You were teamed up into the team {{prefix}}{{name}}"${colours.reset}${colours.command}" with: "${colours.secondary}"{{players}}";

        Map<String, String> context = ImmutableMap.<String, String>builder().put("prefix", team.getPrefix())
                .put("name", team.getName()).put("display name", team.getDisplayName())
                .put("players", playerNames).build();

        String message = messages.evalTemplate("teamup notification", context);

        // add each player
        for (Player player : teamPlayers) {
            team.addPlayer(player);
            player.sendMessage(message);
        }
    }

    Map<String, Integer> context = ImmutableMap.<String, Integer>builder().put("count", teams.size())
            .put("size", teams.get(0).size()).put("players", toAssign.size()).build();

    sender.sendMessage(messages.evalTemplate("created", context));

    if (options.has(excludeExtrasSpec) && extras > 0) {
        sender.sendMessage(messages.evalTemplate("extras notice", ImmutableMap.of("extras", extras)));
    }

    return true;
}

From source file:com.b2international.snowowl.core.internal.validation.ValidationBootstrap.java

@Override
public void preRun(SnowOwlConfiguration configuration, Environment env) throws Exception {
    if (env.isEmbedded() || env.isServer()) {
        final ObjectMapper mapper = env.service(ObjectMapper.class);
        final Index validationIndex = Indexes.createIndex("validations", mapper,
                new Mappings(ValidationIssue.class, ValidationRule.class, ValidationWhiteList.class),
                env.service(IndexSettings.class));

        final ValidationRepository repository = new ValidationRepository(validationIndex);
        env.services().registerService(ValidationRepository.class, repository);

        // register always available validation rule evaluators
        ValidationRuleEvaluator.Registry
                .register(new GroovyScriptValidationRuleEvaluator(env.getConfigDirectory().toPath()));

        // initialize validation thread pool
        final ValidationConfiguration validationConfig = configuration
                .getModuleConfig(ValidationConfiguration.class);

        int numberOfValidationThreads = validationConfig.getNumberOfValidationThreads();
        int maxConcurrentExpensiveJobs = validationConfig.getMaxConcurrentExpensiveJobs();
        int maxConcurrentNormalJobs = validationConfig.getMaxConcurrentNormalJobs();

        env.services().registerService(ValidationConfiguration.class, validationConfig);
        env.services().registerService(ValidationThreadPool.class, new ValidationThreadPool(
                numberOfValidationThreads, maxConcurrentExpensiveJobs, maxConcurrentNormalJobs));

        final List<File> listOfFiles = Arrays.asList(env.getConfigDirectory().listFiles());
        final Set<File> validationRuleFiles = Sets.newHashSet();
        final Pattern validationFilenamePattern = Pattern.compile("(validation-rules)-(\\w+).(json)");
        for (File file : listOfFiles) {
            final String fileName = file.getName();
            final Matcher match = validationFilenamePattern.matcher(fileName);
            if (match.matches()) {
                validationRuleFiles.add(file);
            }/* ww w  .  j  a v a  2 s  .  c  o m*/
        }

        final List<ValidationRule> availableRules = Lists.newArrayList();
        for (File validationRulesFile : validationRuleFiles) {
            LOG.info("Synchronizing validation rules from file: " + validationRulesFile);
            availableRules
                    .addAll(mapper.readValue(validationRulesFile, new TypeReference<List<ValidationRule>>() {
                    }));
        }

        repository.write(writer -> {
            final Map<String, ValidationRule> existingRules = Maps.uniqueIndex(
                    ValidationRequests.rules().prepareSearch().all().buildAsync().getRequest().execute(env),
                    ValidationRule::getId);

            // index all rules from the file, this will update existing rules as well
            final Set<String> ruleIds = newHashSet();
            for (ValidationRule rule : availableRules) {
                writer.put(rule.getId(), rule);
                ruleIds.add(rule.getId());
            }

            // delete rules and associated issues
            Set<String> rulesToDelete = Sets.difference(existingRules.keySet(), ruleIds);
            if (!rulesToDelete.isEmpty()) {
                final Set<String> issuesToDelete = newHashSet(writer.searcher().search(Query
                        .select(String.class).from(ValidationIssue.class).fields(ValidationIssue.Fields.ID)
                        .where(Expressions.builder()
                                .filter(Expressions.matchAny(ValidationIssue.Fields.RULE_ID, rulesToDelete))
                                .build())
                        .limit(Integer.MAX_VALUE).build()).getHits());
                writer.removeAll(ImmutableMap.<Class<?>, Set<String>>of(ValidationRule.class, rulesToDelete,
                        ValidationIssue.class, issuesToDelete));
            }

            writer.commit();
            return null;
        });

    }
}

From source file:eu.fbk.materializer.PathAnalysis.java

public boolean isConnected(Edge[] edges) {
    final Set<String> visited = new HashSet<>(Arrays.asList(breadthFirst(edges[0].cLeft, edges)));
    final Set<String> allNodes = new HashSet<>(Arrays.asList(getNodes()));
    final Set<String> difference = Sets.difference(allNodes, visited);
    return difference.isEmpty();
}

From source file:org.apache.cassandra.io.sstable.SSTable.java

public static Set<Component> discoverComponentsFor(Descriptor desc) {
    Set<Component.Type> knownTypes = Sets.difference(Component.TYPES,
            Collections.singleton(Component.Type.CUSTOM));
    Set<Component> components = Sets.newHashSetWithExpectedSize(knownTypes.size());
    for (Component.Type componentType : knownTypes) {
        Component component = new Component(componentType);
        if (new File(desc.filenameFor(component)).exists())
            components.add(component);/*from   ww w  . j a  v a 2  s  .  c o  m*/
    }
    return components;
}

From source file:org.obm.push.backend.FolderSnapshotService.java

public HierarchyCollectionChanges buildDiff(final FolderSnapshot knownSnapshot,
        final FolderSnapshot currentSnapshot) throws DaoException {
    final Map<BackendId, Folder> knownFolders = knownSnapshot.getFoldersByBackendId();
    final Map<BackendId, Folder> currentFolders = currentSnapshot.getFoldersByBackendId();

    final Set<BackendId> adds = Sets.difference(currentFolders.keySet(), knownFolders.keySet());
    final Set<BackendId> dels = Sets.difference(knownFolders.keySet(), currentFolders.keySet());

    return HierarchyCollectionChanges.builder()
            .deletions(FluentIterable.from(dels).transform(folderToCollectionDeletion(knownFolders)).toSet())
            .additions(FluentIterable.from(adds).transform(folderToCollectionCreation(currentFolders)).toSet())
            .changes(FluentIterable.from(currentSnapshot.getFolders()).filter(new Predicate<Folder>() {

                @Override/*from w w w  .j  a v a 2s  . c om*/
                public boolean apply(Folder folder) {
                    return !adds.contains(folder.getBackendId()) && !dels.contains(folder.getBackendId())
                            && !knownSnapshot.getFolders().contains(folder);
                }
            }).transform(folderToCollectionChange(currentFolders)).toSet()).build();
}

From source file:com.facebook.presto.resourceGroups.db.DbResourceGroupConfigurationManager.java

@VisibleForTesting
public synchronized void load() {
    Map.Entry<ManagerSpec, Map<ResourceGroupIdTemplate, ResourceGroupSpec>> specsFromDb = buildSpecsFromDb();
    ManagerSpec managerSpec = specsFromDb.getKey();
    Map<ResourceGroupIdTemplate, ResourceGroupSpec> resourceGroupSpecs = specsFromDb.getValue();
    Set<ResourceGroupIdTemplate> changedSpecs = new HashSet<>();
    Set<ResourceGroupIdTemplate> deletedSpecs = Sets.difference(this.resourceGroupSpecs.keySet(),
            resourceGroupSpecs.keySet());

    for (Map.Entry<ResourceGroupIdTemplate, ResourceGroupSpec> entry : resourceGroupSpecs.entrySet()) {
        if (!entry.getValue().sameConfig(this.resourceGroupSpecs.get(entry.getKey()))) {
            changedSpecs.add(entry.getKey());
        }//  ww w .ja  v  a 2 s.com
    }

    this.resourceGroupSpecs = resourceGroupSpecs;
    this.cpuQuotaPeriod.set(managerSpec.getCpuQuotaPeriod());
    this.rootGroups.set(managerSpec.getRootGroups());
    this.selectors.set(buildSelectors(managerSpec));

    configureChangedGroups(changedSpecs);
    disableDeletedGroups(deletedSpecs);
}

From source file:org.eclipse.osee.orcs.db.internal.sql.SqlFieldResolver.java

private void addRequiredFields(DynamicObject object) {
    Family family = null;/*from   ww w  .  j  a va 2 s.c om*/
    int level = object.getLevel();
    Set<ObjectField> fields = new HashSet<ObjectField>();
    for (DynamicData child : object.getChildren()) {
        String fieldId = child.getGuid();
        if (fieldId != null) {
            ObjectField objectField = ObjectField.fromString(fieldId);
            if (objectField != null) {
                family = objectField.getFamily();
                fields.add(objectField);
                level = child.getLevel();
            }
        }
    }
    if (family != null && !fields.isEmpty()) {
        Set<ObjectField> required = ObjectField.getRequiredFieldsFor(family);
        SetView<ObjectField> missing = Sets.difference(required, fields);

        int index = 0;
        for (ObjectField field : missing) {
            String fieldId = field.name();
            DynamicData data = new DynamicData(fieldId, null);
            data.setLevel(level);
            data.setFieldName(fieldId);
            processField(data, true);
            object.addChild(index++, data);
        }
    }
}