Example usage for com.google.common.collect ImmutableSet forEach

List of usage examples for com.google.common.collect ImmutableSet forEach

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet forEach.

Prototype

default void forEach(Consumer<? super T> action) 

Source Link

Document

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Usage

From source file:org.obiba.mica.study.service.HarmonizationStudyService.java

@Override
protected void saveInternal(final HarmonizationStudy study, String comment, boolean cascade) {
    log.info("Saving harmonization study: {}", study.getId());

    // checks if population and dce are still the same
    String studyId = study.getId();
    if (studyId != null) {
        List<String> list = populationsAffected(study, harmonizationStudyRepository.findOne(study.getId()));
        if (list != null && list.size() > 0) {
            checkPopulationMissingConstraints(studyId, list);
        }//from   ww  w.  j  av a  2  s  .  c o m
    }

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

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

    invalidRoles.forEach(study::removeRole);

    HarmonizationStudyState studyState = findEntityState(study, HarmonizationStudyState::new);

    if (!study.isNew())
        ensureGitRepository(studyState);

    studyState.incrementRevisionsAhead();
    harmonizationStudyStateRepository.save(studyState);

    study.setLastModifiedDate(DateTime.now());

    if (cascade)
        harmonizationStudyRepository.saveWithReferences(study);
    else
        harmonizationStudyRepository.save(study);

    gitService.save(study, comment);
    eventBus.post(new DraftStudyUpdatedEvent(study));
}

From source file:com.google.devtools.build.android.aapt2.ProtoResourceUsageAnalyzer.java

/**
 * Calculate and removes unused resource from the {@link ProtoApk}.
 *
 * @param apk An apk in the aapt2 proto format.
 * @param classes The associated classes for the apk.
 * @param destination Where to write the reduced resources.
 * @param keep A list of resource urls to keep, unused or not.
 * @param discard A list of resource urls to always discard.
 *//*  w  ww  . ja  va  2  s .  c  o m*/
public void shrink(ProtoApk apk, Path classes, Path destination, Collection<String> keep,
        Collection<String> discard) throws IOException, ParserConfigurationException, SAXException {

    // record resources and manifest
    apk.visitResources(
            // First, collect all declarations using the declaration visitor.
            // This allows the model to start with a defined set of resources to build the reference
            // graph on.
            apk.visitResources(new ResourceDeclarationVisitor(model())).toUsageVisitor());

    recordClassUsages(classes);

    // Have to give the model xml attributes with keep and discard urls.
    final NamedNodeMap toolAttributes = XmlUtils.parseDocument(String.format(
            "<resources xmlns:tools='http://schemas.android.com/tools' tools:keep='%s'"
                    + " tools:discard='%s'></resources>",
            keep.stream().collect(joining(",")), discard.stream().collect(joining(","))), true)
            .getDocumentElement().getAttributes();

    for (int i = 0; i < toolAttributes.getLength(); i++) {
        model().recordToolsAttributes((Attr) toolAttributes.item(i));
    }
    model().processToolsAttributes();

    keepPossiblyReferencedResources();

    dumpReferences();

    // Remove unused.
    final ImmutableSet<Resource> unused = ImmutableSet.copyOf(model().findUnused());

    // ResourceUsageAnalyzer uses the logger to generate the report.
    Logger logger = Logger.getLogger(getClass().getName());
    unused.forEach(resource -> logger
            .fine("Deleted unused file " + ((resource.locations != null && resource.locations.getFile() != null)
                    ? resource.locations.getFile().toString()
                    : "<apk>" + " for resource " + resource)));

    apk.copy(destination,
            (resourceType,
                    name) -> !unused
                            .contains(Preconditions.checkNotNull(model().getResource(resourceType, name),
                                    "%s/%s was not declared but is copied!", resourceType, name)));
}

From source file:org.obiba.mica.study.service.IndividualStudyService.java

public void saveInternal(final Study study, String comment, boolean cascade, boolean weightChanged) {
    log.info("Saving study: {}", study.getId());

    // checks if population and dce are still the same
    if (study.getId() != null) {
        List<String> list = populationsOrDceAffected(study, studyRepository.findOne(study.getId()), false);
        if (list != null && list.size() > 0) {
            checkPopulationOrDceMissingConstraints(list);
        }//from w  ww. ja va2 s .  c o m
    }

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

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

    invalidRoles.forEach(study::removeRole);

    StudyState studyState = findEntityState(study, StudyState::new);

    if (!study.isNew())
        ensureGitRepository(studyState);

    studyState.incrementRevisionsAhead();

    if (weightChanged) {
        studyState.setPopulationOrDceWeightChange(true);
    }

    studyStateRepository.save(studyState);
    study.setLastModifiedDate(DateTime.now());

    if (cascade)
        studyRepository.saveWithReferences(study);
    else
        studyRepository.save(study);

    gitService.save(study, comment);
    eventBus.post(new DraftStudyUpdatedEvent(study));
}

From source file:nextmethod.threading.WaitHandle.java

public boolean set() {
    final ImmutableSet<Thread> threads;
    synchronized (this) {
        checkDisposed();//from  w w  w  .  ja v a2 s  .c  o m

        if (!state.compareAndSet(false, true)) {
            return false;
        }
        threads = ImmutableSet.copyOf(waiters);
        waiters.clear();
    }
    threads.forEach(LockSupport::unpark);
    return true;
}

From source file:com.google.errorprone.dataflow.nullnesspropagation.inference.NullnessQualifierInference.java

@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void unused) {
    JCMethodInvocation sourceNode = (JCMethodInvocation) node;
    MethodSymbol callee = (MethodSymbol) TreeInfo.symbol(sourceNode.getMethodSelect());

    ImmutableList<TypeAndSymbol> formalParameters = callee.isVarArgs()
            ? expandVarargsToArity(callee.getParameters(), sourceNode.args.size())
            : callee.getParameters().stream().map(var -> TypeAndSymbol.create(var.type, var))
                    .collect(ImmutableList.toImmutableList());

    // Generate constraints for each argument write.
    Streams.forEachPair(formalParameters.stream(), sourceNode.getArguments().stream(), (formal, actual) -> {
        // formal parameter type (no l-val b/c that would wrongly constrain the method return)
        // TODO(b/116977632): constraints for actual parameter type (i.e. after type variable
        // substitution) without ignoring annotations directly on the parameter or vararg
        generateConstraintsForWrite(formal.type(), formal.symbol(), actual, /*lVal=*/ null);
    });//  ww  w.j  av  a  2s .c o m

    // Generate constraints for method return
    generateConstraintsFromAnnotations(sourceNode.type, callee, callee.getReturnType(), sourceNode,
            new ArrayDeque<>());

    // If return type is parameterized by a generic type on receiver, collate references to that
    // generic between the receiver and the result/argument types.
    if (!callee.isStatic() && node.getMethodSelect() instanceof JCFieldAccess) {
        JCFieldAccess fieldAccess = ((JCFieldAccess) node.getMethodSelect());
        for (TypeVariableSymbol tvs : fieldAccess.selected.type.tsym.getTypeParameters()) {
            Type rcvrtype = fieldAccess.selected.type.tsym.type;
            ImmutableSet<InferenceVariable> rcvrReferences = findUnannotatedTypeVarRefs(tvs, rcvrtype,
                    /*decl=*/ null, fieldAccess.selected);
            Type restype = fieldAccess.sym.type.asMethodType().restype;
            // TODO(b/116977632): Propagate constraints for instantiated receiver types as well?
            findUnannotatedTypeVarRefs(tvs, restype, fieldAccess.sym, node).forEach(
                    resRef -> rcvrReferences.forEach(rcvrRef -> qualifierConstraints.putEdge(resRef, rcvrRef)));
            Streams.forEachPair(formalParameters.stream(), node.getArguments().stream(),
                    (formal, actual) -> findUnannotatedTypeVarRefs(tvs, formal.type(), formal.symbol(), actual)
                            .forEach(argRef -> rcvrReferences
                                    .forEach(rcvrRef -> qualifierConstraints.putEdge(argRef, rcvrRef))));
        }
    }

    // Get all references to each typeVar in the return type and formal parameters and relate them
    // in the constraint graph; covariant in the return type, contravariant in the argument types.
    // Annotated type var references override the type var's inferred qualifier, so ignore them.
    //
    // Additionally generate equality constraints between inferred types that are instantiations of
    // type parameters.  For instance, if a method type parameter <T> was instantiated List<String>
    // for a given call site m(x), and T appears in the return type as Optional<T>, then the
    // expression's inferred type will be Optional<List<String>> and we generate constraints to
    // equate T[0] = m(x)[0, 0].  If m's parameter's type is T then the argument type's inferred
    // type is List<String> and we also generate constraints to equate T[0] = x[0], which will
    // allow the inference to conclude later that x[0] = m(x)[0, 0], meaning the nullness qualifier
    // for x's <String> is the same as the one for m(x)'s <String>.
    for (TypeVariableSymbol typeVar : callee.getTypeParameters()) {
        TypeVariableInferenceVar typeVarIV = TypeVariableInferenceVar.create(typeVar, node);
        visitUnannotatedTypeVarRefsAndEquateInferredComponents(typeVarIV, callee.getReturnType(), callee, node,
                iv -> qualifierConstraints.putEdge(typeVarIV, iv));
        Streams.forEachPair(formalParameters.stream(), node.getArguments().stream(),
                (formal, actual) -> visitUnannotatedTypeVarRefsAndEquateInferredComponents(typeVarIV,
                        formal.type(), formal.symbol(), actual,
                        iv -> qualifierConstraints.putEdge(iv, typeVarIV)));
    }
    return super.visitMethodInvocation(node, unused);
}

From source file:com.facebook.buck.features.project.intellij.IjProjectWriter.java

/** Update the modules.xml file with any new modules from the given set */
private void updateModulesIndex(ImmutableSet<IjModule> modulesEdited) throws IOException {
    final Set<ModuleIndexEntry> existingModules = modulesParser
            .getAllModules(projectFilesystem.newFileInputStream(getIdeaConfigDir().resolve("modules.xml")));
    final Set<Path> existingModuleFilepaths = existingModules.stream().map(ModuleIndexEntry::getFilePath)
            .map(MorePaths::pathWithUnixSeparators).map(Paths::get).collect(ImmutableSet.toImmutableSet());
    ImmutableSet<Path> remainingModuleFilepaths = modulesEdited.stream().map(projectPaths::getModuleImlFilePath)
            .map(MorePaths::pathWithUnixSeparators).map(Paths::get)
            .filter(modulePath -> !existingModuleFilepaths.contains(modulePath))
            .collect(ImmutableSet.toImmutableSet());

    // Merge the existing and new modules into a single sorted set
    ImmutableSortedSet.Builder<ModuleIndexEntry> finalModulesBuilder = ImmutableSortedSet
            .orderedBy(Comparator.<ModuleIndexEntry>naturalOrder());
    // Add the existing definitions
    finalModulesBuilder.addAll(existingModules);
    // Add any new module definitions that we haven't seen yet
    remainingModuleFilepaths.forEach(modulePath -> finalModulesBuilder
            .add(ModuleIndexEntry.builder().setFilePath(projectPaths.getProjectRelativePath(modulePath))
                    .setFileUrl(getUrl(projectPaths.getProjectQualifiedPath(modulePath)))
                    .setGroup(projectConfig.getModuleGroupName()).build()));

    // Write out the merged set to disk
    writeModulesIndex(finalModulesBuilder.build());
}

From source file:de.metas.ui.web.window.model.DocumentCollection.java

public void invalidateIncludedDocumentsByRecordId(final String tableName, final int recordId,
        final String childTableName, final int childRecordId) {
    final DocumentId documentId = DocumentId.of(recordId);
    final DocumentId rowId = childRecordId > 0 ? DocumentId.of(childRecordId) : null;

    final Function<DocumentEntityDescriptor, DocumentPath> toDocumentPath;
    if (rowId != null) {
        toDocumentPath = includedEntity -> DocumentPath.includedDocumentPath(includedEntity.getWindowId(),
                documentId, includedEntity.getDetailId(), rowId);
    } else {//from   ww  w. j a  v a  2  s  .c  o m
        // all rows for given tab/detail
        toDocumentPath = includedEntity -> DocumentPath.includedDocumentPath(includedEntity.getWindowId(),
                documentId, includedEntity.getDetailId());
    }

    //
    // Create possible documentKeys for given tableName/recordId
    final ImmutableSet<DocumentPath> documentPaths = getCachedWindowIdsForTableName(tableName).stream()
            .map(this::getDocumentEntityDescriptor)
            .flatMap(rootEntity -> rootEntity.streamIncludedEntitiesByTableName(childTableName))
            .map(toDocumentPath).collect(ImmutableSet.toImmutableSet());

    documentPaths.forEach(this::invalidateIncludedDocuments);
}

From source file:com.facebook.buck.ide.intellij.aggregation.AggregationTree.java

private void aggregateModules(AggregationTreeNode parentNode) {
    if (parentNode.getChildren().isEmpty()) {
        return;//from  w  ww  .  jav  a  2  s .  com
    }

    AggregationModule nodeModule = parentNode.getModule();

    if (nodeModule != null && !nodeModule.getModuleType().canBeAggregated()) {
        return;
    }

    Path moduleBasePath = parentNode.getModuleBasePath();

    LOG.info("Aggregating module at %s: %s", moduleBasePath, nodeModule);

    String aggregationTag;
    IjModuleType rootModuleType;
    if (nodeModule == null) {
        aggregationTag = findBestAggregationTag(parentNode);
        rootModuleType = null;
    } else {
        aggregationTag = nodeModule.getAggregationTag();
        rootModuleType = nodeModule.getModuleType();
    }

    ImmutableSet<Path> modulePathsToAggregate;
    if (aggregationTag == null) {
        modulePathsToAggregate = parentNode.getChildrenPathsByModuleType(IjModuleType.UNKNOWN_MODULE);
        if (modulePathsToAggregate.isEmpty()) {
            return;
        }
        rootModuleType = IjModuleType.UNKNOWN_MODULE;
    } else {
        modulePathsToAggregate = parentNode.getChildrenPathsByModuleTypeOrTag(IjModuleType.UNKNOWN_MODULE,
                aggregationTag);

        if (rootModuleType == null) {
            rootModuleType = parentNode.getChild(modulePathsToAggregate.iterator().next()).getModule()
                    .getModuleType();
        }
    }

    ImmutableSet<Path> excludes = findExcludes(parentNode, modulePathsToAggregate);

    List<AggregationModule> modulesToAggregate = modulePathsToAggregate.stream().map(parentNode::getChild)
            .map(AggregationTreeNode::getModule).collect(Collectors.toList());

    modulePathsToAggregate.forEach(parentNode::removeChild);

    if (nodeModule == null) {
        parentNode.setModule(ModuleAggregator.aggregate(moduleBasePath, rootModuleType,
                aggregationTag == null ? modulesToAggregate.iterator().next().getAggregationTag()
                        : aggregationTag,
                modulesToAggregate, excludes));
    } else {
        parentNode.setModule(ModuleAggregator.aggregate(nodeModule, modulesToAggregate, excludes));
    }
    LOG.info("Module after aggregation: %s", parentNode.getModule());
}