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:com.thoughtworks.go.server.dashboard.GoDashboardCurrentStateLoader.java

public List<GoDashboardPipeline> allPipelines(CruiseConfig config) {
    List<CaseInsensitiveString> allPipelineNames = config.getAllPipelineNames();

    HashSet<CaseInsensitiveString> currentPipelineNames = new HashSet<>(allPipelineNames);

    Collection<CaseInsensitiveString> pipelinesToRemove = Sets.difference(lastKnownPipelineNames,
            currentPipelineNames);/*from w ww .ja va2s  . c  om*/
    Collection<CaseInsensitiveString> pipelinesToAdd = Sets.difference(currentPipelineNames,
            lastKnownPipelineNames);

    if (!pipelinesToAdd.isEmpty()) {
        historyForDashboard.addAll(
                loadHistoryForPipelines(new ArrayList<>(CaseInsensitiveString.toStringList(pipelinesToAdd))));
    }

    for (CaseInsensitiveString pipelineNameToRemove : new ArrayList<>(pipelinesToRemove)) {
        clearEntryFor(pipelineNameToRemove);
    }

    lastKnownPipelineNames = currentPipelineNames;

    LOGGER.debug("Loading permissions from authority");
    final Map<CaseInsensitiveString, Permissions> pipelinesAndTheirPermissions = permissionsAuthority
            .pipelinesAndTheirPermissions();

    final List<GoDashboardPipeline> pipelines = new ArrayList<>(1024);

    LOGGER.debug("Populating dashboard pipelines");
    config.accept((PipelineGroupVisitor) group -> group.accept(pipelineConfig -> {
        long start = System.currentTimeMillis();
        Permissions permissions = permissionsFor(pipelineConfig, pipelinesAndTheirPermissions);

        pipelines.add(createGoDashboardPipeline(pipelineConfig, permissions, historyForDashboard, group));

        LOGGER.debug("It took {}ms to process pipeline {}", (System.currentTimeMillis() - start),
                pipelineConfig.getName());
    }));
    LOGGER.debug("Done populating dashboard pipelines");
    this.everLoadedCurrentState = true;
    return pipelines;
}

From source file:com.google.devtools.cyclefinder.GraphBuilder.java

private void addSubtypeEdges() {
    for (TypeNode type : allTypes.values()) {
        for (Edge e : ImmutableList.copyOf(graph.getEdges(type))) {
            Set<TypeNode> targetSubtypes = subtypes.get(e.getTarget());
            Set<TypeNode> whitelisted = new HashSet<>();
            String fieldName = e.getFieldQualifiedName();
            if (fieldName == null) {
                continue; // Outer or capture field.
            }/*w  w  w .  j a v  a2 s  .com*/
            for (TypeNode subtype : targetSubtypes) {
                if (whitelist.isWhitelistedTypeForField(fieldName, subtype)
                        || whitelist.containsType(subtype)) {
                    whitelisted.add(subtype);
                    whitelisted.addAll(subtypes.get(subtype));
                }
            }
            for (TypeNode subtype : Sets.difference(targetSubtypes, whitelisted)) {
                addEdge(Edge.newSubtypeEdge(e, subtype));
            }
        }
    }
}

From source file:edu.mit.streamjit.impl.distributed.node.BlobsManagerImpl.java

public BlobsManagerImpl(ImmutableSet<Blob> blobSet, Map<Token, TCPConnectionInfo> conInfoMap,
        StreamNode streamNode, TCPConnectionProvider conProvider) {
    this.conInfoMap = conInfoMap;
    this.streamNode = streamNode;
    this.conProvider = conProvider;

    this.cmdProcessor = new CommandProcessorImpl();
    this.drainProcessor = new CTRLRDrainProcessorImpl();

    bufferMap = createBufferMap(blobSet);

    for (Blob b : blobSet) {
        b.installBuffers(bufferMap);//from  w ww  .j a v a  2s. c o  m
    }

    Set<Token> locaTokens = getLocalTokens(blobSet);
    blobExecuters = new HashSet<>();
    for (Blob b : blobSet) {
        ImmutableMap<Token, BoundaryInputChannel> inputChannels = createInputChannels(
                Sets.difference(b.getInputs(), locaTokens), bufferMap);
        ImmutableMap<Token, BoundaryOutputChannel> outputChannels = createOutputChannels(
                Sets.difference(b.getOutputs(), locaTokens), bufferMap);
        blobExecuters.add(new BlobExecuter(b, inputChannels, outputChannels));
    }
}

From source file:org.obiba.mica.network.service.NetworkService.java

@SuppressWarnings("OverlyLongMethod")
private void saveInternal(@NotNull Network network, String comment, boolean cascade) {
    Network saved = network;//from   w  w w.j a v  a2s .co m

    if (network.isNew()) {
        generateId(saved);
    } else {
        saved = networkRepository.findOne(network.getId());

        if (saved != null) {
            BeanUtils.copyProperties(network, saved, "id", "version", "createdBy", "createdDate",
                    "lastModifiedBy", "lastModifiedDate");
        } else {
            saved = network;
        }
    }

    if (saved.getLogo() != null && saved.getLogo().isJustUploaded()) {
        fileStoreService.save(saved.getLogo().getId());
        saved.getLogo().setJustUploaded(false);
    }

    ImmutableSet<String> invalidRoles = ImmutableSet.copyOf(Sets.difference(saved.membershipRoles(),
            Sets.newHashSet(micaConfigService.getConfig().getRoles())));

    for (String r : invalidRoles) {
        saved.removeRole(r);
    }

    NetworkState networkState = findEntityState(network, () -> {
        NetworkState defaultState = new NetworkState();
        defaultState.setName(network.getName());

        return defaultState;
    });

    if (!network.isNew())
        ensureGitRepository(networkState);

    networkState.incrementRevisionsAhead();
    networkStateRepository.save(networkState);

    saved.setLastModifiedDate(DateTime.now());

    if (cascade)
        networkRepository.saveWithReferences(saved);
    else
        networkRepository.save(saved);

    eventBus.post(new NetworkUpdatedEvent(saved));
    gitService.save(saved, comment);
}

From source file:org.kuali.rice.xml.ingest.RiceConfigUtils.java

public static void add(Properties oldProps, Properties newProps) {
    SortedSet<String> newKeys = Sets
            .newTreeSet(Sets.difference(newProps.stringPropertyNames(), oldProps.stringPropertyNames()));
    if (newKeys.size() == 0) {
        return;//from w w w. j a  va2s . c  om
    }
    logger.info("Adding {} properties", newKeys.size());
    for (String newKey : newKeys) {
        String value = newProps.getProperty(newKey);
        logger.debug("Adding - [{}]=[{}]", newKey, toLogMsg(newKey, value));
        oldProps.setProperty(newKey, value);
    }
}

From source file:clocker.docker.location.DockerResolver.java

@Override
public LocationSpec<? extends Location> newLocationSpecFromString(String spec, Map<?, ?> locationFlags,
        LocationRegistry registry) {//from   w  w  w.jav  a2  s  .  com
    if (LOG.isDebugEnabled()) {
        LOG.debug("Resolving location '" + spec + "' with flags "
                + Joiner.on(",").withKeyValueSeparator("=").join(locationFlags));
    }

    Matcher matcher = PATTERN.matcher(spec);
    if (!matcher.matches()) {
        throw new IllegalArgumentException("Invalid location '" + spec
                + "'; must specify something like docker:locId or docker:locId:(name=abc)");
    }

    String infrastructureLocId = matcher.group(2);
    if (Strings.isBlank(infrastructureLocId)) {
        throw new IllegalArgumentException(
                "Invalid location '" + spec + "'; infrastructure location id must be non-empty");
    }
    String hostLocId = matcher.group(4);

    // TODO Could validate that the namePart matches the existing loc
    String argsPart = matcher.group(6);
    Map<String, String> argsMap = (argsPart != null) ? KeyValueParser.parseMap(argsPart)
            : Collections.<String, String>emptyMap();
    String namePart = argsMap.get("name");

    if (!ACCEPTABLE_ARGS.containsAll(argsMap.keySet())) {
        Set<String> illegalArgs = Sets.difference(argsMap.keySet(), ACCEPTABLE_ARGS);
        throw new IllegalArgumentException("Invalid location '" + spec + "'; illegal args " + illegalArgs
                + "; acceptable args are " + ACCEPTABLE_ARGS);
    }
    if (argsMap.containsKey("name") && Strings.isEmpty(namePart)) {
        throw new IllegalArgumentException(
                "Invalid location '" + spec + "'; if name supplied then value must be non-empty");
    }

    Location infrastructureLoc = managementContext.getLocationManager().getLocation(infrastructureLocId);
    if (infrastructureLoc == null) {
        throw new IllegalArgumentException(
                "Unknown Clocker infrastructure location id " + infrastructureLocId + ", spec " + spec);
    } else if (!(infrastructureLoc instanceof DockerLocation)) {
        throw new IllegalArgumentException("Invalid location id for Clocker infrastructure, spec " + spec
                + "; instead matches " + infrastructureLoc);
    }

    if (hostLocId != null) {
        Location hostLoc = managementContext.getLocationManager().getLocation(hostLocId);
        if (hostLoc == null) {
            throw new IllegalArgumentException(
                    "Unknown Clocker host location id " + hostLocId + ", spec " + spec);
        } else if (!(hostLoc instanceof DockerHostLocation)) {
            throw new IllegalArgumentException(
                    "Invalid location id for Clocker host, spec " + spec + "; instead matches " + hostLoc);
        }

        return LocationSpec.create(DockerHostLocation.class).configure(LocationConstructor.LOCATION, hostLoc)
                .configure(SpecialBrooklynObjectConstructor.Config.SPECIAL_CONSTRUCTOR,
                        LocationConstructor.class);

    } else {
        return LocationSpec.create(DockerLocation.class)
                .configure(LocationConstructor.LOCATION, infrastructureLoc).configure(
                        SpecialBrooklynObjectConstructor.Config.SPECIAL_CONSTRUCTOR, LocationConstructor.class);
    }
}

From source file:org.semanticweb.elk.justifications.BloomSet.java

@Override
public Justification<C, A> removeElements(Set<? extends A> removed) {
    if (Sets.intersection(this, removed).isEmpty()) {
        return this;
    }/*ww  w  .j  a  v  a 2  s .  c  om*/
    // else
    return new BloomSet<C, A>(conclusion_, Sets.difference(this, removed));
}

From source file:org.jetbrains.kotlin.generators.di.DependencyInjectorGenerator.java

private void reportUnusedParameters(String injectorPackageName, String injectorClassName) {
    Sets.SetView<Field> unusedParameters = Sets.difference(backsParameter, dependencies.getUsedFields());
    for (Field parameter : unusedParameters) {
        if (!parameter.isPublic()) {
            System.err.println(//from   w  w  w.j  a va2  s . c  o  m
                    "Unused parameter: " + parameter + " for " + injectorPackageName + "." + injectorClassName);
        }
    }
}

From source file:org.codice.ddf.catalog.ui.metacard.associations.Associated.java

public void putAssociations(String id, Collection<Edge> edges)
        throws UnsupportedQueryException, SourceUnavailableException, FederationException, IngestException {
    Collection<Edge> oldEdges = getAssociations(id);

    List<String> ids = Stream.concat(oldEdges.stream(), edges.stream())
            .flatMap(e -> Stream.of(e.child, e.parent)).filter(Objects::nonNull).map(m -> m.get(Metacard.ID))
            .filter(Objects::nonNull).map(Object::toString).distinct().collect(Collectors.toList());

    Map<String, Metacard> metacards = util.getMetacardsWithTagById(ids, getNonrestrictedTagsFilter()).entrySet()
            .stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getMetacard()));

    Map<String, Metacard> changedMetacards = new HashMap<>();
    Set<Edge> oldEdgeSet = new HashSet<>(oldEdges);
    Set<Edge> newEdgeSet = new HashSet<>(edges);

    Set<Edge> oldDiff = Sets.difference(oldEdgeSet, newEdgeSet);
    Set<Edge> newDiff = Sets.difference(newEdgeSet, oldEdgeSet);

    for (Edge edge : oldDiff) {
        removeEdge(edge, metacards, changedMetacards);
    }//from w  w w.jav a2s.c  o  m
    for (Edge edge : newDiff) {
        addEdge(edge, metacards, changedMetacards);
    }

    if (changedMetacards.isEmpty()) {
        return;
    }

    catalogFramework.update(new UpdateRequestImpl(changedMetacards.keySet().toArray(new String[0]),
            new ArrayList<>(changedMetacards.values())));
}

From source file:org.apache.ranger.plugin.policyresourcematcher.RangerDefaultPolicyResourceMatcher.java

@Override
public void init() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerDefaultPolicyResourceMatcher.init()");
    }/*w  ww  . ja  va2s.c o  m*/

    String errorText = "";

    if (policyResources != null && policyResources.size() > 0 && serviceDef != null) {

        Set<String> policyResourceKeySet = policyResources.keySet();

        RangerServiceDefHelper serviceDefHelper = new RangerServiceDefHelper(serviceDef, false);
        int policyType = policy != null && policy.getPolicyType() != null ? policy.getPolicyType()
                : RangerPolicy.POLICY_TYPE_ACCESS;
        Set<List<RangerResourceDef>> validResourceHierarchies = serviceDefHelper
                .getResourceHierarchies(policyType);

        for (List<RangerResourceDef> validResourceHierarchy : validResourceHierarchies) {

            Set<String> resourceDefNameSet = serviceDefHelper.getAllResourceNames(validResourceHierarchy);

            if ((Sets.difference(policyResourceKeySet, resourceDefNameSet)).isEmpty()) {

                firstValidResourceDefHierarchy = validResourceHierarchy;
                break;

            }

        }

        if (firstValidResourceDefHierarchy != null) {
            List<String> resourceDefNameOrderedList = serviceDefHelper
                    .getAllResourceNamesOrdered(firstValidResourceDefHierarchy);

            boolean foundGapsInResourceSpecs = false;
            boolean skipped = false;

            for (String resourceDefName : resourceDefNameOrderedList) {
                RangerPolicyResource policyResource = policyResources.get(resourceDefName);
                if (policyResource == null) {
                    skipped = true;
                } else if (skipped) {
                    foundGapsInResourceSpecs = true;
                    break;
                }
            }

            if (foundGapsInResourceSpecs) {

                errorText = "policyResources does not specify contiguous sequence in any valid resourcedef hiearchy.";
                if (LOG.isDebugEnabled()) {
                    LOG.debug(
                            "RangerDefaultPolicyResourceMatcher.init() failed: Gaps found in policyResources, internal error, skipping..");
                }
                firstValidResourceDefHierarchy = null;

            } else {

                matchers = new HashMap<String, RangerResourceMatcher>();

                for (RangerResourceDef resourceDef : firstValidResourceDefHierarchy) {

                    String resourceName = resourceDef.getName();
                    RangerPolicyResource policyResource = policyResources.get(resourceName);

                    if (policyResource != null) {
                        RangerResourceMatcher matcher = createResourceMatcher(resourceDef, policyResource);

                        if (matcher != null) {
                            if (!needsDynamicEval && matcher.getNeedsDynamicEval()) {
                                needsDynamicEval = true;
                            }
                            matchers.put(resourceName, matcher);
                            if (!matcher.isMatchAny()) {
                                lastNonAnyMatcherIndex = matchers.size();
                            }
                        } else {
                            LOG.error("failed to find matcher for resource " + resourceName);
                        }
                    } else {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("RangerDefaultPolicyResourceMatcher.init() - no matcher created for "
                                    + resourceName + ". Continuing ...");
                        }
                    }
                }
            }
        } else {
            errorText = "policyResources elements are not part of any valid resourcedef hierarchy.";
        }
    } else {
        errorText = " policyResources is null or empty, or serviceDef is null.";
    }

    if (matchers == null) {
        Set<String> policyResourceKeys = policyResources == null ? null : policyResources.keySet();
        StringBuilder sb = new StringBuilder();
        if (CollectionUtils.isNotEmpty(policyResourceKeys)) {
            for (String policyResourceKeyName : policyResourceKeys) {
                sb.append(" ").append(policyResourceKeyName).append(" ");
            }
        }
        String keysString = sb.toString();
        String serviceDefName = serviceDef == null ? "" : serviceDef.getName();
        String validHierarchy = "";
        if (serviceDef != null && CollectionUtils.isNotEmpty(firstValidResourceDefHierarchy)) {
            RangerServiceDefHelper serviceDefHelper = new RangerServiceDefHelper(serviceDef, false);
            List<String> resourceDefNameOrderedList = serviceDefHelper
                    .getAllResourceNamesOrdered(firstValidResourceDefHierarchy);

            for (String resourceDefName : resourceDefNameOrderedList) {
                validHierarchy += " " + resourceDefName + " ";
            }
        }
        LOG.warn("RangerDefaultPolicyResourceMatcher.init() failed: " + errorText + " (serviceDef="
                + serviceDefName + ", policyResourceKeys=" + keysString + ", validHierarchy=" + validHierarchy
                + ")");
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerDefaultPolicyResourceMatcher.init()");
    }
}