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.sonar.java.cfg.LiveVariables.java

private void analyzeCFG(Map<CFG.Block, Set<Symbol>> in, Map<CFG.Block, Set<Symbol>> kill,
        Map<CFG.Block, Set<Symbol>> gen) {
    Deque<CFG.Block> workList = new LinkedList<>();
    workList.addAll(cfg.reversedBlocks());
    while (!workList.isEmpty()) {
        CFG.Block block = workList.removeFirst();

        Set<Symbol> blockOut = out.get(block);
        if (blockOut == null) {
            blockOut = new HashSet<>();
            out.put(block, blockOut);/*from  w ww  . j av a 2 s . c o m*/
        }
        block.successors().stream().map(in::get).filter(Objects::nonNull).forEach(blockOut::addAll);
        block.exceptions().stream().map(in::get).filter(Objects::nonNull).forEach(blockOut::addAll);
        // in = gen and (out - kill)
        Set<Symbol> newIn = new HashSet<>(gen.get(block));
        newIn.addAll(Sets.difference(blockOut, kill.get(block)));

        if (newIn.equals(in.get(block))) {
            continue;
        }
        in.put(block, newIn);
        block.predecessors().forEach(workList::addLast);
    }
}

From source file:org.apache.druid.client.BatchServerInventoryView.java

@Override
protected DruidServer updateInnerInventory(DruidServer container, String inventoryKey,
        Set<DataSegment> inventory) {
    Set<DataSegment> filteredInventory = filterInventory(container, inventory);

    Set<DataSegment> existing = zNodes.get(inventoryKey);
    if (existing == null) {
        throw new ISE("Trying to update an inventoryKey[%s] that didn't exist?!", inventoryKey);
    }/*from  ww w. j a  v a  2s  .c  o  m*/

    for (DataSegment segment : Sets.difference(filteredInventory, existing)) {
        addSingleInventory(container, segment);
    }
    for (DataSegment segment : Sets.difference(existing, filteredInventory)) {
        removeSingleInventory(container, segment.getIdentifier());
    }
    zNodes.put(inventoryKey, filteredInventory);

    return container;
}

From source file:com.jeffjirsa.cassandra.db.compaction.TimeWindowCompactionStrategy.java

/**
 *
 * @param gcBefore/*ww w .  j a v  a  2  s . c  o m*/
 * @return
 */
private List<SSTableReader> getNextBackgroundSSTables(final int gcBefore) {
    if (Iterables.isEmpty(cfs.getSSTables(SSTableSet.LIVE)))
        return Collections.emptyList();

    Set<SSTableReader> uncompacting = ImmutableSet
            .copyOf(filter(cfs.getUncompactingSSTables(), sstables::contains));

    // Find fully expired SSTables. Those will be included no matter what.
    Set<SSTableReader> expired = Collections.emptySet();

    if (System.currentTimeMillis() - lastExpiredCheck > options.expiredSSTableCheckFrequency) {
        logger.debug("TWCS expired check sufficiently far in the past, checking for fully expired SSTables");
        expired = CompactionController.getFullyExpiredSSTables(cfs, uncompacting,
                cfs.getOverlappingSSTables(SSTableSet.CANONICAL, uncompacting), gcBefore);
        lastExpiredCheck = System.currentTimeMillis();
    } else {
        logger.debug("TWCS skipping check for fully expired SSTables");
    }

    Set<SSTableReader> candidates = Sets.newHashSet(filterSuspectSSTables(uncompacting));

    List<SSTableReader> compactionCandidates = new ArrayList<>(
            getNextNonExpiredSSTables(Sets.difference(candidates, expired), gcBefore));
    if (!expired.isEmpty()) {
        logger.debug("Including expired sstables: {}", expired);
        compactionCandidates.addAll(expired);
    }

    return compactionCandidates;
}

From source file:com.continuuity.loom.provisioner.mock.MockProvisionerWorkerService.java

@Override
protected void runOneIteration() throws Exception {
    for (String tenant : provisionerTenantStore.getAssignedTenants()) {
        int assigned = provisionerTenantStore.getAssignedWorkers(tenant);
        int live = provisionerTenantStore.getLiveWorkers(tenant);
        int diff = assigned - live;
        if (diff > 0) {
            addWorkers(tenant, diff);//w  w w.  j a v  a 2s  . c o  m
        } else if (diff < 0) {
            removeWorkers(tenant, 0 - diff);
        }
        provisionerTenantStore.setLiveTenantWorkers(tenant, assigned);
    }
    Set<String> tenantsToDelete = Sets.difference(provisionerTenantStore.getLiveTenants(),
            provisionerTenantStore.getAssignedTenants());
    for (String tenantToDelete : tenantsToDelete) {
        LOG.info("Deleting tenant {}", tenantsToDelete);
        removeWorkers(tenantToDelete, provisionerTenantStore.getLiveWorkers(tenantToDelete));
        provisionerTenantStore.deleteTenant(tenantToDelete);
    }
}

From source file:examples.baku.io.permissions.PermissionManager.java

void refreshPermissions() {
    Blessing.PermissionTree updatedPermissionTree = new Blessing.PermissionTree();
    //received blessings
    for (Blessing blessing : getReceivedBlessings()) {
        if (blessing.isSynched()) {
            updatedPermissionTree.merge(blessing.getPermissionTree());
        }//from  w  w  w.j  ava2 s . c  o m
    }

    //re-associate listeners with rules
    mNearestAncestors.clear();
    for (String path : mPermissionValueEventListeners.keySet()) {
        String nearestAncestor = Utils.getNearestCommonAncestor(path, updatedPermissionTree.keySet());
        if (nearestAncestor != null) {
            mNearestAncestors.put(nearestAncestor, path);
        }
    }

    Set<String> changedPermissions = new HashSet<>();

    //determine removed permissions
    Sets.SetView<String> removedPermissions = Sets.difference(mPermissionTree.keySet(),
            updatedPermissionTree.keySet());
    for (String path : removedPermissions) {
        String newPath = Utils.getNearestCommonAncestor(path, updatedPermissionTree.keySet());
        int previous = mPermissionTree.getPermissions(path);
        int current = updatedPermissionTree.getPermissions(newPath);
        if (previous != current) {
            changedPermissions.add(newPath);
        }
    }

    //compare previous tree
    for (Blessing.Permission permission : updatedPermissionTree.values()) {
        int previous = mPermissionTree.getPermissions(permission.path);
        int current = updatedPermissionTree.getPermissions(permission.path);
        if (previous != current) {
            changedPermissions.add(permission.path);
        }
    }

    mPermissionTree = updatedPermissionTree;

    //notify listeners
    for (String path : changedPermissions) {
        onPermissionsChange(path);
    }

}

From source file:org.apache.brooklyn.core.location.dynamic.clocker.StubResolver.java

@Override
public LocationSpec<? extends Location> newLocationSpecFromString(String spec, Map<?, ?> locationFlags,
        LocationRegistry registry) {//from  w  w w. java  2  s.c o m
    Map<?, ?> properties = registry.getProperties();

    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 stub:entityId or stub:entityId:(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();
    @SuppressWarnings("unused")
    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);
    }

    Location infrastructureLoc = managementContext.getLocationManager().getLocation(infrastructureLocId);
    if (infrastructureLoc == null) {
        throw new IllegalArgumentException(
                "Unknown Clocker infrastructure location id " + infrastructureLocId + ", spec " + spec);
    } else if (!(infrastructureLoc instanceof StubInfrastructureLocation)) {
        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 StubHostLocation)) {
            throw new IllegalArgumentException(
                    "Invalid location id for Clocker host, spec " + spec + "; instead matches " + hostLoc);
        }

        return LocationSpec.create(StubHostLocation.class).configure(StubLocationConstructor.LOCATION, hostLoc)
                .configure(Config.SPECIAL_CONSTRUCTOR, StubLocationConstructor.class);
    } else {
        return LocationSpec.create(StubInfrastructureLocation.class)
                .configure(StubLocationConstructor.LOCATION, infrastructureLoc)
                .configure(Config.SPECIAL_CONSTRUCTOR, StubLocationConstructor.class);
    }
}

From source file:com.siemens.sw360.portal.tags.DisplayReleaseChanges.java

private void renderReleaseIdToRelationship(StringBuilder display) {

    if (ensureSomethingTodoAndNoNull(Release._Fields.RELEASE_ID_TO_RELATIONSHIP)) {

        Set<String> changedReleaseIds = Sets.intersection(additions.getReleaseIdToRelationship().keySet(),
                deletions.getReleaseIdToRelationship().keySet());
        Set<String> releaseIdsInDb = nullToEmptyMap(actual.getReleaseIdToRelationship()).keySet();
        //keep only releases that are still in the database
        changedReleaseIds = Sets.intersection(changedReleaseIds, releaseIdsInDb);

        Set<String> removedReleaseIds = Sets.difference(deletions.getReleaseIdToRelationship().keySet(),
                changedReleaseIds);//from ww  w .  j a  v  a2s . co m
        removedReleaseIds = Sets.intersection(removedReleaseIds, releaseIdsInDb);

        Set<String> addedReleaseIds = Sets.difference(additions.getReleaseIdToRelationship().keySet(),
                changedReleaseIds);

        display.append("<h3> Changes in linked releases </h3>");
        LinkedReleaseRenderer renderer = new LinkedReleaseRenderer(display, tableClasses, idPrefix,
                actual.getCreatedBy());
        renderer.renderReleaseLinkList(display, deletions.getReleaseIdToRelationship(), removedReleaseIds,
                "Removed Release Links");
        renderer.renderReleaseLinkList(display, additions.getReleaseIdToRelationship(), addedReleaseIds,
                "Added Release Links");
        renderer.renderReleaseLinkListCompare(display, actual.getReleaseIdToRelationship(),
                deletions.getReleaseIdToRelationship(), additions.getReleaseIdToRelationship(),
                changedReleaseIds);
    }
}

From source file:org.apache.james.dlp.eventsourcing.aggregates.DLPDomainConfiguration.java

private Optional<Event> generateRemovedRulesEvent(ImmutableSet<DLPConfigurationItem> existingRules,
        ImmutableSet<DLPConfigurationItem> updateRulesSet) {
    Set<DLPConfigurationItem> removedRules = Sets.difference(existingRules, updateRulesSet);
    if (!removedRules.isEmpty()) {
        return Optional.of(new ConfigurationItemsRemoved(aggregateId, history.getNextEventId(), removedRules));
    }/*from   w  ww.ja  v  a 2 s  .  co m*/
    return Optional.empty();
}

From source file:com.ariht.maven.plugins.config.generator.ConfigGeneratorImpl.java

/**
 * Merge templates with filters to generate config, scripts and property io.
 *///ww  w . j  ava 2  s  .  c  o m
private void processTemplatesAndGenerateConfig() throws Exception {
    final DirectoryReader directoryReader = new DirectoryReader(log);
    final List<FileInfo> filters = directoryReader.readFiles(configGeneratorParameters.getFiltersBasePath(),
            configGeneratorParameters.getFiltersToIgnore());
    for (FileInfo fileInfo : filters) {
        fileInfo.lookForExternalFiles(configGeneratorParameters.getExternalFilterBasePaths());
    }
    final List<FileInfo> templates = directoryReader.readFiles(configGeneratorParameters.getTemplatesBasePath(),
            configGeneratorParameters.getTemplatesToIgnore());
    logOutputPath();

    // Get list of all properties in all filter io.
    final Set<String> allProperties = getAllProperties(filters);
    // Collection stores missing properties by file so this can be logged once at the end.
    final Map<String, Set<String>> missingPropertiesByFilename = new LinkedHashMap<String, Set<String>>();

    for (final FileInfo filter : filters) {
        final Properties properties = readFilterIntoProperties(filter);
        final LinkedHashMap<String, String> valueMap = Maps.newLinkedHashMap(Maps.fromProperties(properties));

        // No point checking for missing properties if all were found in the filter file
        boolean missingPropertyFound = false;
        for (String missingProperty : Sets.difference(allProperties, valueMap.keySet()).immutableCopy()) {
            valueMap.put(missingProperty, MISSING_PROPERTY_PREFIX + missingProperty + MISSING_PROPERTY_SUFFIX);
            missingPropertyFound = true;
        }
        final StrSubstitutor strSubstitutor = new StrSubstitutor(valueMap,
                configGeneratorParameters.getPropertyPrefix(), configGeneratorParameters.getPropertySuffix());
        for (final FileInfo template : templates) {
            generateConfig(template, filter, configGeneratorParameters.getOutputBasePath(), strSubstitutor,
                    missingPropertiesByFilename, missingPropertyFound);
        }
    }

    if (!missingPropertiesByFilename.keySet().isEmpty()) {
        final StringBuilder sb = new StringBuilder("Missing properties identified:\n");
        for (String filename : missingPropertiesByFilename.keySet()) {
            sb.append(filename).append(": ");
            sb.append(StringUtils.join(missingPropertiesByFilename.get(filename), ", ")).append("\n");
        }
        log.warn(sb.toString());
        if (configGeneratorParameters.isFailOnMissingProperty()) {
            throw new MojoExecutionException(sb.toString());
        }
    }
}

From source file:org.eclipse.emf.compare.ide.ui.internal.logical.resolver.ResourceDependencyLocalResolver.java

/**
 * Checks the current state of our {@link #resourceListener} and updates the dependency graph for all
 * resources that have been changed since we last checked.
 * /* w  w  w .jav a  2s .  co  m*/
 * @param resourceSet
 *            The resource set in which to load our temporary resources.
 * @param diagnostic
 *            The diagnostic.
 * @param tspm
 *            Monitor on which to report progress to the user.
 */
protected void updateChangedResources(SynchronizedResourceSet resourceSet, DiagnosticSupport diagnostic,
        ThreadSafeProgressMonitor tspm) {
    // this.diagnostic = createDiagnostic();
    final Set<URI> removedURIs = Sets.difference(resourceListener.popRemovedURIs(),
            scheduler.getComputedElements());
    final Set<URI> changedURIs = Sets.difference(resourceListener.popChangedURIs(),
            scheduler.getComputedElements());

    eventBus.post(new ResourceRemovedEvent<URI>(removedURIs));

    // We need to re-resolve the changed resources, along with their direct parents
    final Set<URI> recompute = new LinkedHashSet<URI>(changedURIs);
    final Multimap<URI, URI> parentToGrandParents = ArrayListMultimap.create();
    for (URI changed : changedURIs) {
        if (dependencyGraph.contains(changed)) {
            Set<URI> directParents = dependencyGraph.getDirectParents(changed);
            recompute.addAll(directParents);
            for (URI uri : directParents) {
                Set<URI> grandParents = dependencyGraph.getDirectParents(uri);
                parentToGrandParents.putAll(uri, grandParents);
            }
        }
    }

    eventBus.post(new ResourceRemovedEvent<URI>(recompute));

    demandResolveAll(recompute, diagnostic, resourceSet, tspm);

    // Re-connect changed resources parents' with their parents
    Set<URI> toResolve = new LinkedHashSet<URI>();
    for (URI parentURI : parentToGrandParents.keySet()) {
        if (dependencyGraph.contains(parentURI)) {
            toResolve.addAll(parentToGrandParents.get(parentURI));
        }
    }
    demandResolveAll(toResolve, diagnostic, resourceSet, tspm);
}