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.apache.sling.tooling.lc.LaunchpadComparer.java

public void run() throws Exception {

    System.out.format("Computing differences between Launchpad versions %s and %s...%n", firstVersion,
            secondVersion);// w w w. j a v a  2 s  .c  om

    // 1. download artifacts
    AetherSetup aether = new AetherSetup();

    File fromFile = aether.download(Artifacts.launchpadCoordinates(firstVersion));
    File toFile = aether.download(Artifacts.launchpadCoordinates(secondVersion));

    // 2. parse artifact definitions
    Model model;
    try (BufferedReader reader = Files.newBufferedReader(toFile.toPath())) {
        model = ModelUtility.getEffectiveModel(ModelReader.read(reader, null));
    }

    Map<ArtifactKey, Artifact> to = model.getFeatures().stream().flatMap(f -> f.getRunModes().stream())
            .flatMap(r -> r.getArtifactGroups().stream())
            .flatMap(g -> StreamSupport.stream(g.spliterator(), false))
            .collect(Collectors.toMap(a -> new ArtifactKey(a), Function.identity()));

    BundleList readBundleList = BundleListUtils.readBundleList(fromFile);

    Map<ArtifactKey, Artifact> from = readBundleList.getStartLevels().stream()
            .flatMap(sl -> sl.getBundles().stream())
            .collect(Collectors.toMap(b -> new ArtifactKey(b), LaunchpadComparer::newArtifact));

    // 3. generate added / removed / changed
    Set<Artifact> removed = Sets.difference(from.keySet(), to.keySet()).stream().map(k -> from.get(k))
            .collect(Collectors.toSet());

    Set<Artifact> added = Sets.difference(to.keySet(), from.keySet()).stream().map(k -> to.get(k))
            .collect(Collectors.toSet());

    Map<ArtifactKey, VersionChange> changed = to.values().stream()
            .filter(k -> !added.contains(k) && !removed.contains(k)).map(k -> new ArtifactKey(k))
            .filter(k -> !Objects.equals(to.get(k).getVersion(), from.get(k).getVersion()))
            .collect(Collectors.toMap(Function.identity(),
                    k -> new VersionChange(from.get(k).getVersion(), to.get(k).getVersion())));

    // 4. output changes

    System.out.println("Added ");
    added.stream().sorted().forEach(LaunchpadComparer::outputFormatted);

    System.out.println("Removed ");
    removed.stream().sorted().forEach(LaunchpadComparer::outputFormatted);

    System.out.println("Changed");
    changed.entrySet().stream().sorted((a, b) -> a.getKey().compareTo(b.getKey()))
            .forEach(LaunchpadComparer::outputFormatted);

}

From source file:org.obiba.mica.access.service.DataAccessRequestService.java

@Override
public DataAccessRequest save(@NotNull DataAccessRequest request) {
    DataAccessRequest saved = request;/*from   www.  java 2  s.co  m*/
    DataAccessEntityStatus from = null;
    Iterable<Attachment> attachmentsToDelete = null;
    Iterable<Attachment> attachmentsToSave = null;

    if (request.isNew()) {
        setAndLogStatus(saved, DataAccessEntityStatus.OPENED);
        saved.setId(generateId());
        attachmentsToSave = saved.getAttachments();
    } else {
        saved = dataAccessRequestRepository.findOne(request.getId());
        if (saved != null) {
            if (!SecurityUtils.getSubject().hasRole(Roles.MICA_DAO)
                    && !SecurityUtils.getSubject().hasRole(Roles.MICA_ADMIN)) {
                // preserve current actionLogs as no other user role can add or remove them
                request.setActionLogHistory(saved.getActionLogHistory());
            }

            attachmentsToDelete = Sets.difference(Sets.newHashSet(saved.getAttachments()),
                    Sets.newHashSet(request.getAttachments()));
            attachmentsToSave = Sets.difference(Sets.newHashSet(request.getAttachments()),
                    Sets.newHashSet(saved.getAttachments()));

            from = saved.getStatus();
            // validate the status
            dataAccessRequestUtilService.checkStatusTransition(saved, request.getStatus());
            saved.setStatus(request.getStatus());
            if (request.hasStatusChangeHistory())
                saved.setStatusChangeHistory(request.getStatusChangeHistory());
            // merge beans
            BeanUtils.copyProperties(request, saved, "id", "version", "createdBy", "createdDate",
                    "lastModifiedBy", "lastModifiedDate", "statusChangeHistory");
        } else {
            saved = request;
            setAndLogStatus(saved, DataAccessEntityStatus.OPENED);
        }
    }

    schemaFormContentFileService.save(saved, dataAccessRequestRepository.findOne(request.getId()),
            String.format("/data-access-request/%s", saved.getId()));

    if (attachmentsToSave != null)
        attachmentsToSave.forEach(a -> {
            fileStoreService.save(a.getId());
            a.setJustUploaded(false);
            attachmentRepository.save(a);
        });

    saved.setLastModifiedDate(DateTime.now());
    dataAccessRequestRepository.saveWithReferences(saved);

    if (attachmentsToDelete != null)
        attachmentsToDelete.forEach(a -> fileStoreService.delete(a.getId()));

    eventBus.post(new DataAccessRequestUpdatedEvent(saved));
    sendNotificationEmails(saved, from);
    return saved;
}

From source file:com.facebook.buck.core.model.impl.AbstractImmutableUnconfiguredBuildTarget.java

@Override
public UnconfiguredBuildTarget withoutFlavors(Set<Flavor> flavors) {
    return ImmutableUnconfiguredBuildTarget.of(getUnflavoredBuildTarget(),
            Sets.difference(getFlavors(), flavors));
}

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

@Override
public final Set<ByteString> contained(Iterable<ByteString> keys) {
    Set<K> ikRequested = toInternalKeySet(keys);
    if (ikRequested.isEmpty()) {
        return ImmutableSet.of();
    }//ww w  .  j  a v a2  s.c o m
    Set<K> ikCached = Sets.intersection(ikRequested, cache.asMap().keySet()).immutableCopy();
    Set<K> ikNotCached = Sets.difference(ikRequested, ikCached).immutableCopy();
    Set<ByteString> kCached = toKeySet(ikCached);
    if (ikNotCached.isEmpty()) {
        return kCached;
    }
    Set<ByteString> kFound = bocas.contained(toKeySet(ikNotCached));
    return Sets.union(kCached, kFound).immutableCopy();
}

From source file:dagger2.internal.codegen.ProducerModuleProcessingStep.java

@Override
public void process(SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) {
    // first, check and collect all produces methods
    ImmutableSet.Builder<ExecutableElement> validProducesMethodsBuilder = ImmutableSet.builder();
    for (Element producesElement : elementsByAnnotation.get(Produces.class)) {
        if (producesElement.getKind().equals(METHOD)) {
            ExecutableElement producesMethodElement = (ExecutableElement) producesElement;
            ValidationReport<ExecutableElement> methodReport = producesMethodValidator
                    .validate(producesMethodElement);
            methodReport.printMessagesTo(messager);
            if (methodReport.isClean()) {
                validProducesMethodsBuilder.add(producesMethodElement);
            }//from   w w  w .j  a  va 2 s.c  om
        }
    }
    ImmutableSet<ExecutableElement> validProducesMethods = validProducesMethodsBuilder.build();

    // process each module
    for (Element moduleElement : Sets.difference(elementsByAnnotation.get(ProducerModule.class),
            processedModuleElements)) {
        if (SuperficialValidation.validateElement(moduleElement)) {
            ValidationReport<TypeElement> report = moduleValidator.validate(MoreElements.asType(moduleElement));
            report.printMessagesTo(messager);

            if (report.isClean()) {
                ImmutableSet.Builder<ExecutableElement> moduleProducesMethodsBuilder = ImmutableSet.builder();
                List<ExecutableElement> moduleMethods = ElementFilter
                        .methodsIn(moduleElement.getEnclosedElements());
                for (ExecutableElement methodElement : moduleMethods) {
                    if (isAnnotationPresent(methodElement, Produces.class)) {
                        moduleProducesMethodsBuilder.add(methodElement);
                    }
                }
                ImmutableSet<ExecutableElement> moduleProducesMethods = moduleProducesMethodsBuilder.build();

                if (Sets.difference(moduleProducesMethods, validProducesMethods).isEmpty()) {
                    // all of the produces methods in this module are valid!
                    // time to generate some factories!
                    ImmutableSet<ProductionBinding> bindings = FluentIterable.from(moduleProducesMethods)
                            .transform(new Function<ExecutableElement, ProductionBinding>() {
                                @Override
                                public ProductionBinding apply(ExecutableElement producesMethod) {
                                    return productionBindingFactory.forProducesMethod(producesMethod,
                                            producesMethod.getEnclosingElement().asType());
                                }
                            }).toSet();

                    try {
                        for (ProductionBinding binding : bindings) {
                            factoryGenerator.generate(binding);
                        }
                    } catch (SourceFileGenerationException e) {
                        e.printMessageTo(messager);
                    }
                }
            }

            processedModuleElements.add(moduleElement);
        }
    }
}

From source file:io.druid.client.BatchServerInventoryView.java

@Override
protected DruidServer updateInnerInventory(DruidServer container, String inventoryKey,
        Set<DataSegment> inventory) {
    Predicate<DataSegment> predicate = Predicates.or(defaultFilter, Predicates.or(segmentPredicates.values()));
    // make a copy of the set and not just a filtered view, in order to not keep all the segment data in memory
    Set<DataSegment> filteredInventory = Sets.newHashSet(Iterables.filter(inventory, predicate));

    Set<DataSegment> existing = zNodes.get(inventoryKey);
    if (existing == null) {
        throw new ISE("Trying to update an inventoryKey[%s] that didn't exist?!", inventoryKey);
    }//from   w  ww .  ja v  a2 s.  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:dagger.internal.codegen.ProducerModuleProcessingStep.java

@Override
public Set<Element> process(SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) {
    // first, check and collect all produces methods
    ImmutableSet.Builder<ExecutableElement> validProducesMethodsBuilder = ImmutableSet.builder();
    for (Element producesElement : elementsByAnnotation.get(Produces.class)) {
        if (producesElement.getKind().equals(METHOD)) {
            ExecutableElement producesMethodElement = (ExecutableElement) producesElement;
            ValidationReport<ExecutableElement> methodReport = producesMethodValidator
                    .validate(producesMethodElement);
            methodReport.printMessagesTo(messager);
            if (methodReport.isClean()) {
                validProducesMethodsBuilder.add(producesMethodElement);
            }/*from   w w  w .  java2s.com*/
        }
    }
    ImmutableSet<ExecutableElement> validProducesMethods = validProducesMethodsBuilder.build();

    // process each module
    for (Element moduleElement : Sets.difference(elementsByAnnotation.get(ProducerModule.class),
            processedModuleElements)) {
        if (SuperficialValidation.validateElement(moduleElement)) {
            ValidationReport<TypeElement> report = moduleValidator.validate(MoreElements.asType(moduleElement));
            report.printMessagesTo(messager);

            if (report.isClean()) {
                ImmutableSet.Builder<ExecutableElement> moduleProducesMethodsBuilder = ImmutableSet.builder();
                List<ExecutableElement> moduleMethods = ElementFilter
                        .methodsIn(moduleElement.getEnclosedElements());
                for (ExecutableElement methodElement : moduleMethods) {
                    if (isAnnotationPresent(methodElement, Produces.class)) {
                        moduleProducesMethodsBuilder.add(methodElement);
                    }
                }
                ImmutableSet<ExecutableElement> moduleProducesMethods = moduleProducesMethodsBuilder.build();

                if (Sets.difference(moduleProducesMethods, validProducesMethods).isEmpty()) {
                    // all of the produces methods in this module are valid!
                    // time to generate some factories!
                    ImmutableSet<ProductionBinding> bindings = FluentIterable.from(moduleProducesMethods)
                            .transform(new Function<ExecutableElement, ProductionBinding>() {
                                @Override
                                public ProductionBinding apply(ExecutableElement producesMethod) {
                                    return productionBindingFactory.forProducesMethod(producesMethod,
                                            producesMethod.getEnclosingElement().asType());
                                }
                            }).toSet();

                    try {
                        for (ProductionBinding binding : bindings) {
                            factoryGenerator.generate(binding);
                        }
                    } catch (SourceFileGenerationException e) {
                        e.printMessageTo(messager);
                    }
                }
            }

            processedModuleElements.add(moduleElement);
        }
    }
    return ImmutableSet.of();
}

From source file:com.streamsets.pipeline.lib.util.UDPTestUtil.java

public static void verifyCollectdRecord(Map<String, Field> expected, Record record) {
    Map<String, Field> actual = record.get("/").getValueAsMap();
    Assert.assertEquals(expected.size(), actual.size());
    Set<Map.Entry<String, Field>> difference = Sets.difference(expected.entrySet(), actual.entrySet());
    Assert.assertEquals(true, difference.isEmpty());
}

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

private void renderAttachments(StringBuilder display, Set<Attachment> currentAttachments,
        Set<Attachment> updateAttachments) {

    Map<String, Attachment> currentAttachmentById = getAttachmentsById(currentAttachments);
    Map<String, Attachment> updateAttachmentById = getAttachmentsById(updateAttachments);

    Set<String> currentAttachmentIds = currentAttachmentById.keySet();
    Set<String> updateAttachmentIds = updateAttachmentById.keySet();

    Set<String> deletedAttachmentIds = Sets.difference(currentAttachmentIds, updateAttachmentIds);
    Set<String> addedAttachmentIds = Sets.difference(updateAttachmentIds, currentAttachmentIds);

    Set<String> commonAttachmentIds = Sets.intersection(currentAttachmentIds, updateAttachmentIds);

    renderAttachmentList(display, currentAttachmentById, deletedAttachmentIds, "Deleted");
    renderAttachmentList(display, updateAttachmentById, addedAttachmentIds, "Added");
    renderAttachmentComparison(display, currentAttachmentById, updateAttachmentById, commonAttachmentIds);

}

From source file:grakn.core.graql.gremlin.ConjunctionQuery.java

/**
 * @param patternConjunction a pattern containing no disjunctions to find in the graph
 *///  w w w  .j a  v  a  2 s  .c  o m
ConjunctionQuery(Conjunction<Statement> patternConjunction, TransactionOLTP tx) {
    statements = patternConjunction.getPatterns();

    if (statements.size() == 0) {
        throw GraqlException.noPatterns();
    }

    ImmutableSet<EquivalentFragmentSet> fragmentSets = statements.stream()
            .flatMap(statements -> equivalentFragmentSetsRecursive(statements))
            .collect(ImmutableSet.toImmutableSet());

    // Get all variable names mentioned in non-starting, non-comparing fragments (these should have vars bound elsewhere too)
    Set<Variable> names = fragmentSets.stream().flatMap(EquivalentFragmentSet::stream)
            .filter(fragment -> !fragment.validStartIfDisconnected() && !(fragment instanceof ValueFragment)
                    && !(fragment instanceof NeqFragment))
            .flatMap(fragment -> fragment.vars().stream()).collect(ImmutableSet.toImmutableSet());

    // Get all dependencies fragments have on certain variables existing
    Set<Variable> dependencies = fragmentSets.stream().flatMap(EquivalentFragmentSet::stream)
            .flatMap(fragment -> fragment.dependencies().stream()).collect(ImmutableSet.toImmutableSet());

    Set<Variable> validNames = Sets.difference(names, dependencies);

    // Filter out any non-essential starting fragments (because other fragments refer to their starting variable)
    Set<EquivalentFragmentSet> initialEquivalentFragmentSets = fragmentSets.stream()
            .filter(set -> set.stream().anyMatch(
                    fragment -> !fragment.validStartIfDisconnected() || !validNames.contains(fragment.start())))
            .collect(toSet());

    // Apply final optimisations
    EquivalentFragmentSets.optimiseFragmentSets(initialEquivalentFragmentSets, tx);

    this.equivalentFragmentSets = ImmutableSet.copyOf(initialEquivalentFragmentSets);
}