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:de.sep2011.funckit.controller.SelectTool.java

private static boolean canDropElementsHere(EditPanelModel epm) {
    Set<Element> ghosts = epm.getGhosts();
    Set<Element> circuitElements = epm.getCircuit().getElements();
    Set<Element> selectedElements = epm.getSelectedElements();
    Set<Element> unselectedElements = Sets.difference(circuitElements, selectedElements);
    Check collisionCheck = new MultipleCollisionCheck(ghosts);
    Circuit tmpCircuit = new CircuitImpl();
    tmpCircuit.getElements().addAll(unselectedElements);

    Result result = collisionCheck.perform(tmpCircuit);

    return result.isPassed();
}

From source file:brooklyn.location.cloud.CloudResolver.java

protected Location newLocationFromString(String spec, LocationRegistry registry, Map properties,
        Map locationFlags) {/*from  w  w w .  j  a v a 2s .  c  o m*/
    if (LOG.isDebugEnabled()) {
        LOG.debug("Resolving location '" + spec + "' with flags "
                + Joiner.on(",").withKeyValueSeparator("=").join(locationFlags));
    }
    String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());

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

    String argsPart = matcher.group(6);
    Map<String, String> argsMap = (argsPart != null) ? KeyValueParser.parseMap(argsPart)
            : Collections.<String, String>emptyMap();
    String displayNamePart = argsMap.get("displayName");
    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("displayName") && Strings.isEmpty(displayNamePart)) {
        throw new IllegalArgumentException(
                "Invalid location '" + spec + "'; if displayName supplied then value must be non-empty");
    }
    if (argsMap.containsKey("name") && Strings.isEmpty(namePart)) {
        throw new IllegalArgumentException(
                "Invalid location '" + spec + "'; if name supplied then value must be non-empty");
    }

    Map<String, Object> filteredProperties = new LocationPropertiesFromBrooklynProperties()
            .getLocationProperties(CLOUD, namedLocation, properties);
    MutableMap<String, Object> flags = MutableMap.<String, Object>builder().putAll(filteredProperties)
            .putAll(locationFlags).build();

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

    // Build the display name
    StringBuilder name = new StringBuilder();
    if (displayNamePart != null) {
        name.append(displayNamePart);
    } else {
        name.append("Cloud ");
        if (machineId == null) {
            name.append("Environemnt ").append(environmentId);
        } else {
            name.append("Machine ").append(machineId);
        }
    }
    final String displayName = name.toString();

    // Build the location name
    name = new StringBuilder();
    if (namePart != null) {
        name.append(namePart);
    } else {
        name.append("cloud-");
        name.append(environmentId);
        if (machineId != null) {
            name.append("-").append(machineId);
        }
    }
    final String locationName = name.toString();
    CloudEnvironment infrastructure = (CloudEnvironment) managementContext.getEntityManager()
            .getEntity(environmentId);

    if (machineId == null) {
        LocationSpec<CloudLocation> locationSpec = LocationSpec.create(CloudLocation.class).configure(flags)
                .configure(DynamicLocation.OWNER, infrastructure)
                .configure(LocationInternal.NAMED_SPEC_NAME, locationName).displayName(displayName);
        return managementContext.getLocationManager().createLocation(locationSpec);
    } else {
        CloudMachine machine = (CloudMachine) managementContext.getEntityManager().getEntity(machineId);

        LocationSpec<CloudMachineLocation> locationSpec = LocationSpec.create(CloudMachineLocation.class)
                .parent(infrastructure.getDynamicLocation()).configure(flags)
                .configure(DynamicLocation.OWNER, machine)
                .configure(LocationInternal.NAMED_SPEC_NAME, locationName).displayName(displayName);
        return managementContext.getLocationManager().createLocation(locationSpec);
    }
}

From source file:org.apache.zeppelin.impala.SqlCompleter.java

public void updateDataModelMetaData(Connection connection) {

    try {//w w  w  . ja  v  a  2s.  com
        Set<String> newModelCompletions = getDataModelMetadataCompletions(connection);
        logger.debug("New model metadata is:" + Joiner.on(',').join(newModelCompletions));

        // Sets.difference(set1, set2) - returned set contains all elements that are contained by set1
        // and not contained by set2. set2 may also contain elements not present in set1; these are
        // simply ignored.
        SetView<String> removedCompletions = Sets.difference(modelCompletions, newModelCompletions);
        logger.debug("Removed Model Completions: " + Joiner.on(',').join(removedCompletions));
        this.getStrings().removeAll(removedCompletions);

        SetView<String> newCompletions = Sets.difference(newModelCompletions, modelCompletions);
        logger.debug("New Completions: " + Joiner.on(',').join(newCompletions));
        this.getStrings().addAll(newCompletions);

        modelCompletions = newModelCompletions;

    } catch (SQLException e) {
        logger.error("Failed to update the metadata conmpletions", e);
    }
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.op.manifest.KubernetesPatchManifestOperation.java

private ReplaceResult replaceArtifacts(KubernetesCoordinates objToPatch, KubernetesHandler patchHandler) {
    List<Artifact> allArtifacts = description.getAllArtifacts() == null ? new ArrayList<>()
            : description.getAllArtifacts();

    ReplaceResult replaceResult = patchHandler.replaceArtifacts(description.getPatchBody(), allArtifacts,
            objToPatch.getNamespace(), description.getAccount());

    if (description.getRequiredArtifacts() != null) {
        Set<Artifact> unboundArtifacts = Sets.difference(new HashSet<>(description.getRequiredArtifacts()),
                replaceResult.getBoundArtifacts());
        if (!unboundArtifacts.isEmpty()) {
            throw new IllegalArgumentException("The following required artifacts could not be bound: '"
                    + unboundArtifacts + "' . Failing the stage as this is likely a configuration error.");
        }/* w  ww  .  j av a  2 s  .c o  m*/
    }
    return replaceResult;
}

From source file:omero.cmd.graphs.ChildOptionsPolicy.java

/**
 * Adjust an existing graph traversal policy so that child objects may be included or excluded
 * regardless of if they are truly orphans.
 * @param graphPolicyToAdjust the graph policy to adjust
 * @param childOptions the child options that the policy adjustments are to effect
 * @param requiredPermissions the abilities that the user must have to operate upon an object for it to be included
 * @return the adjusted graph policy/*from   ww  w  .  j  a  v  a  2  s. c o  m*/
 */
public static GraphPolicy getChildOptionsPolicy(final GraphPolicy graphPolicyToAdjust,
        final Collection<ChildOptionI> childOptions, final Set<GraphPolicy.Ability> requiredPermissions) {

    if (CollectionUtils.isEmpty(childOptions)) {
        /* there are no adjustments to make to the policy */
        return graphPolicyToAdjust;
    }

    /* wrap the traversal policy so that the child options are effected */

    return new BaseGraphPolicyAdjuster(graphPolicyToAdjust) {
        private final Map<String, String> namespaceCache = new HashMap<String, String>();
        private final Map<Entry<String, Long>, String> objectNamespaces = new HashMap<Entry<String, Long>, String>();

        /**
         * Note each annotation's namespace.
         */
        @Override
        public void noteDetails(Session session, IObject object, String realClass, long id) {
            if (object instanceof Annotation) {
                final String query = "SELECT ns FROM Annotation WHERE id = :id";
                final String namespace = (String) session.createQuery(query).setParameter("id", id)
                        .uniqueResult();
                if (namespace != null) {
                    String cachedNamespace = namespaceCache.get(namespace);
                    if (cachedNamespace == null) {
                        cachedNamespace = namespace;
                        namespaceCache.put(namespace, cachedNamespace);
                    }
                    objectNamespaces.put(Maps.immutableEntry(realClass, id), cachedNamespace);
                }
            }
            super.noteDetails(session, object, realClass, id);
        }

        /**
         * Check if the given object is in the target annotation namespace.
         * @param childOption the child option whose target annotation namespace applies
         * @param object the object to check
         * @return if the annotation is in the target namespace or if the object is not an annotation
         */
        private boolean isTargetNamespace(ChildOptionI childOption, IObject object) {
            if (object instanceof Annotation) {
                final Entry<String, Long> classAndId = Maps.immutableEntry(object.getClass().getName(),
                        object.getId());
                return childOption.isTargetNamespace(objectNamespaces.get(classAndId));
            } else {
                return true;
            }
        }

        @Override
        protected boolean isAdjustedBeforeReview(Details object) {
            if (object.action == GraphPolicy.Action.EXCLUDE && object.orphan == GraphPolicy.Orphan.RELEVANT) {
                /* the model object is [E]{r} */
                for (final ChildOptionI childOption : childOptions) {
                    final Boolean isIncludeVerdict = childOption.isIncludeType(object.subject.getClass());
                    if (isIncludeVerdict == Boolean.TRUE
                            && (requiredPermissions == null
                                    || Sets.difference(requiredPermissions, object.permissions).isEmpty())
                            && isTargetNamespace(childOption, object.subject)) {
                        object.orphan = GraphPolicy.Orphan.IS_LAST;
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("including all children of its type, so making " + object);
                        }
                        return true;
                    } else if (isIncludeVerdict == Boolean.FALSE
                            && isTargetNamespace(childOption, object.subject)) {
                        object.orphan = GraphPolicy.Orphan.IS_NOT_LAST;
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("excluding all children of its type, so making " + object);
                        }
                        return true;
                    }
                }
            }
            return false;
        }
    };
}

From source file:net.derquinse.bocas.SeededBocas.java

@Override
public Map<ByteString, ByteSource> get(Iterable<ByteString> keys) {
    final Set<ByteString> requested = getRequested(keys);
    if (requested.isEmpty()) {
        return ImmutableMap.of();
    }// w w w  .j  a v  a  2  s.  c om
    Map<ByteString, ByteSource> inPrimary = primary.get(requested);
    Set<ByteString> askFallback = Sets.difference(requested, inPrimary.keySet()).immutableCopy();
    if (askFallback.isEmpty()) {
        return inPrimary;
    }
    Map<ByteString, ByteSource> inSecondary = seed.get(askFallback);
    if (inSecondary.isEmpty()) {
        return inPrimary;
    }
    Map<ByteString, ByteSource> total = Maps.newHashMap(inPrimary);
    total.putAll(inSecondary);
    return total;
}

From source file:com.github.rwhogg.git_vcr.VelocityReport.java

/**
 * extract the changes between two reviews
 * @return A map of (old) files to changes in results
 */// w  ww . j ava  2 s  . c om
@SuppressWarnings("rawtypes")
private Map<String, Changes> extractChanges() {
    Map<String, Changes> changeMap = new HashMap<>();

    List<ImmutablePair<String, String>> changedFiles = Util.getFilesChanged(patch);
    // FIXME: for now, we'll just assume no files were added or deleted
    for (ImmutablePair<String, String> filePair : changedFiles) {
        String oldFileName = filePair.getLeft();
        String newFileName = filePair.getRight();
        Changes changesForThisFile = new Changes();
        Map<Class, List<String>> resultsForOldFile = oldResults.getResultsFor(oldFileName);
        Map<Class, List<String>> resultsForNewFile = newResults.getResultsFor(newFileName);
        Set<Class> toolsUsed = resultsForOldFile.keySet();
        assert toolsUsed.equals(resultsForNewFile.keySet());

        // for each tool, go through and detect changes
        for (Class toolUsed : toolsUsed) {
            List<String> oldResultListFromThisTool = resultsForOldFile.get(toolUsed);
            List<String> newResultListFromThisTool = resultsForNewFile.get(toolUsed);
            Set<String> oldResultsFromThisTool = new HashSet<>(oldResultListFromThisTool);
            Set<String> newResultsFromThisTool = new HashSet<>(newResultListFromThisTool);
            Set<String> additions = Sets.difference(newResultsFromThisTool, oldResultsFromThisTool);
            Set<String> subtractions = Sets.difference(oldResultsFromThisTool, newResultsFromThisTool);

            // construct the change
            List<String> additionList = Arrays.asList(additions.toArray(new String[additions.size()]));
            List<String> subtractionList = Arrays.asList(subtractions.toArray(new String[subtractions.size()]));
            ImmutablePair<List<String>, List<String>> changeListPair = ImmutablePair.of(additionList,
                    subtractionList);
            changesForThisFile.put(toolUsed, changeListPair);
        }

        changeMap.put(oldFileName, changesForThisFile);
    }

    return changeMap;
}

From source file:org.apache.brooklyn.core.mgmt.rebind.transformer.impl.DeleteOrphanedStateTransformer.java

/**
 * We inspect the state in two different ways to find the entities that will be deleted:
 * belt-and-braces! Only if the state is not referenced by either of those two approaches
 * will we delete it./*ww w .ja  v  a2 s.  co  m*/
 */
@Override
public BrooklynMementoRawData transform(BrooklynMementoRawData input) {
    ReferencedState stateReferencedFromXpath = new ReachabilityXpathInspector().inspect(input);
    ReferencedState stateToKeepFromGrep = new ReachabilityGrepInspector().inspect(input);
    ReferencedState stateToKeepFromXpath = stateReferencedFromXpath.filterForExtant(input);
    ReferencedState.warnOfDifferences(stateToKeepFromXpath, stateToKeepFromGrep);

    ReferencedState stateToKeep = ReferencedState.union(stateToKeepFromXpath, stateToKeepFromGrep);

    Map<String, String> locationsToKeep = copyRetainingKeys(input.getLocations(), stateToKeep.locations);
    Map<String, String> enrichersToKeep = copyRetainingKeys(input.getEnrichers(), stateToKeep.enrichers);
    Map<String, String> policiesToKeep = copyRetainingKeys(input.getPolicies(), stateToKeep.policies);
    Map<String, String> feedsToKeep = copyRetainingKeys(input.getFeeds(), stateToKeep.feeds);

    Set<String> locsToDelete = Sets.difference(input.getLocations().keySet(), locationsToKeep.keySet());
    Set<String> enrichersToDelete = Sets.difference(input.getEnrichers().keySet(), enrichersToKeep.keySet());
    Set<String> policiesToDelete = Sets.difference(input.getPolicies().keySet(), policiesToKeep.keySet());
    Set<String> feedsToDelete = Sets.difference(input.getFeeds().keySet(), feedsToKeep.keySet());
    LOG.info("Deleting {} orphaned location{}: {}",
            new Object[] { locsToDelete.size(), Strings.s(locsToDelete.size()), locsToDelete });
    LOG.info("Deleting {} orphaned enricher{}: {}",
            new Object[] { enrichersToDelete.size(), Strings.s(enrichersToDelete.size()), enrichersToDelete });
    LOG.info("Deleting {} orphaned polic{}: {}", new Object[] { policiesToDelete.size(),
            (policiesToDelete.size() == 1 ? "y" : "ies"), policiesToDelete });
    LOG.info("Deleting {} orphaned feed{}: {}",
            new Object[] { feedsToDelete.size(), Strings.s(feedsToDelete.size()), feedsToDelete });

    return BrooklynMementoRawData.builder().brooklynVersion(input.getBrooklynVersion())
            .catalogItems(input.getCatalogItems()).entities(input.getEntities()).locations(locationsToKeep)
            .enrichers(enrichersToKeep).policies(policiesToKeep).feeds(feedsToKeep).build();
}

From source file:org.apache.brooklyn.entity.machine.pool.ServerPoolLocationResolver.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*w  ww  . j  a  v  a2  s.  co  m*/
public Location newLocationFromString(Map locationFlags, String spec, LocationRegistry registry) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Resolving location '" + spec + "' with flags "
                + Joiner.on(",").withKeyValueSeparator("=").join(locationFlags));
    }
    String namedLocation = (String) locationFlags.get(LocationInternal.NAMED_SPEC_NAME.getName());

    Matcher matcher = PATTERN.matcher(spec);
    if (!matcher.matches()) {
        String m = String.format(
                "Invalid location '%s'; must specify either %s:entityId or %s:entityId:(key=argument)", spec,
                PREFIX, PREFIX);
        throw new IllegalArgumentException(m);
    }

    String argsPart = matcher.group(4);
    Map<String, String> argsMap = (argsPart != null) ? KeyValueParser.parseMap(argsPart)
            : Collections.<String, String>emptyMap();
    String displayNamePart = argsMap.get("displayName");
    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("displayName") && Strings.isEmpty(displayNamePart)) {
        throw new IllegalArgumentException(
                "Invalid location '" + spec + "'; if displayName supplied then value must be non-empty");
    }
    if (argsMap.containsKey("name") && Strings.isEmpty(namePart)) {
        throw new IllegalArgumentException(
                "Invalid location '" + spec + "'; if name supplied then value must be non-empty");
    }

    Map<String, Object> filteredProperties = new LocationPropertiesFromBrooklynProperties()
            .getLocationProperties(PREFIX, namedLocation, registry.getProperties());
    MutableMap<String, Object> flags = MutableMap.<String, Object>builder().putAll(filteredProperties)
            .putAll(locationFlags).build();

    String poolId = matcher.group(2);
    if (Strings.isBlank(poolId)) {
        throw new IllegalArgumentException(
                "Invalid location '" + spec + "'; pool's entity id must be non-empty");
    }

    final String displayName = displayNamePart != null ? displayNamePart : "Server Pool " + poolId;
    final String locationName = namePart != null ? namePart : "serverpool-" + poolId;

    Entity pool = managementContext.getEntityManager().getEntity(poolId);
    LocationSpec<ServerPoolLocation> locationSpec = LocationSpec.create(ServerPoolLocation.class)
            .configure(flags).configure(DynamicLocation.OWNER, pool)
            .configure(LocationInternal.NAMED_SPEC_NAME, locationName).displayName(displayName);
    return managementContext.getLocationManager().createLocation(locationSpec);
}

From source file:dagger.internal.codegen.ComponentHierarchyValidator.java

private void validateSubcomponentMethods(ValidationReport.Builder<?> report,
        ComponentDescriptor componentDescriptor,
        ImmutableMap<TypeElement, TypeElement> existingModuleToOwners) {
    for (Map.Entry<ComponentMethodDescriptor, ComponentDescriptor> subcomponentEntry : componentDescriptor
            .subcomponentsByFactoryMethod().entrySet()) {
        ComponentMethodDescriptor subcomponentMethodDescriptor = subcomponentEntry.getKey();
        ComponentDescriptor subcomponentDescriptor = subcomponentEntry.getValue();
        // validate the way that we create subcomponents
        for (VariableElement factoryMethodParameter : subcomponentMethodDescriptor.methodElement()
                .getParameters()) {/* w  w w  .  ja  v  a  2  s .  c  o m*/
            TypeElement moduleType = MoreTypes.asTypeElement(factoryMethodParameter.asType());
            TypeElement originatingComponent = existingModuleToOwners.get(moduleType);
            if (originatingComponent != null) {
                /* Factory method tries to pass a module that is already present in the parent.
                 * This is an error. */
                report.addError(String.format(
                        "%s is present in %s. A subcomponent cannot use an instance of a "
                                + "module that differs from its parent.",
                        moduleType.getSimpleName(), originatingComponent.getQualifiedName()),
                        factoryMethodParameter);
            }
        }
        validateSubcomponentMethods(report, subcomponentDescriptor,
                new ImmutableMap.Builder<TypeElement, TypeElement>().putAll(existingModuleToOwners)
                        .putAll(Maps.toMap(
                                Sets.difference(subcomponentDescriptor.transitiveModuleTypes(),
                                        existingModuleToOwners.keySet()),
                                constant(subcomponentDescriptor.componentDefinitionType())))
                        .build());
    }
}