Search in sources :

Example 16 with SetMultimap

use of com.google.common.collect.SetMultimap in project molgenis by molgenis.

the class EntityManagerImpl method resolveReferences.

private List<Entity> resolveReferences(List<Attribute> resolvableAttrs, List<Entity> entities, Fetch fetch) {
    // entity name --> entity ids
    SetMultimap<String, Object> lazyRefEntityIdsMap = HashMultimap.create(resolvableAttrs.size(), 16);
    // entity name --> attributes referring to this entity
    SetMultimap<String, Attribute> refEntityAttrsMap = HashMultimap.create(resolvableAttrs.size(), 2);
    // fill maps
    for (Attribute attr : resolvableAttrs) {
        String refEntityName = attr.getRefEntity().getId();
        if (isSingleReferenceType(attr)) {
            for (Entity entity : entities) {
                Entity lazyRefEntity = entity.getEntity(attr.getName());
                if (lazyRefEntity != null) {
                    lazyRefEntityIdsMap.put(refEntityName, lazyRefEntity.getIdValue());
                }
            }
        } else if (isMultipleReferenceType(attr)) {
            for (Entity entity : entities) {
                Iterable<Entity> lazyRefEntities = entity.getEntities(attr.getName());
                for (Entity lazyRefEntity : lazyRefEntities) {
                    lazyRefEntityIdsMap.put(refEntityName, lazyRefEntity.getIdValue());
                }
            }
        }
        refEntityAttrsMap.put(refEntityName, attr);
    }
    // batch retrieve referred entities and replace entity references with actual entities
    for (Entry<String, Collection<Object>> entry : lazyRefEntityIdsMap.asMap().entrySet()) {
        String refEntityName = entry.getKey();
        // create a fetch for the referenced entity which is a union of the fetches defined by attributes
        // referencing this entity
        Set<Attribute> attrs = refEntityAttrsMap.get(refEntityName);
        Fetch subFetch = createSubFetch(fetch, attrs);
        // retrieve referenced entities
        Stream<Entity> refEntities = dataService.findAll(refEntityName, entry.getValue().stream(), subFetch);
        Map<Object, Entity> refEntitiesIdMap = refEntities.collect(Collectors.toMap(Entity::getIdValue, Function.identity()));
        for (Attribute attr : attrs) {
            if (isSingleReferenceType(attr)) {
                String attrName = attr.getName();
                for (Entity entity : entities) {
                    Entity lazyRefEntity = entity.getEntity(attrName);
                    if (lazyRefEntity != null) {
                        // replace lazy entity with real entity
                        Object refEntityId = lazyRefEntity.getIdValue();
                        Entity refEntity = refEntitiesIdMap.get(refEntityId);
                        entity.set(attrName, refEntity);
                    }
                }
            } else if (isMultipleReferenceType(attr)) {
                String attrName = attr.getName();
                for (Entity entity : entities) {
                    // replace lazy entities with real entities
                    Iterable<Entity> lazyRefEntities = entity.getEntities(attrName);
                    List<Entity> mrefEntities = stream(lazyRefEntities.spliterator(), true).map(lazyRefEntity -> {
                        // replace lazy entity with real entity
                        Object refEntityId = lazyRefEntity.getIdValue();
                        return refEntitiesIdMap.get(refEntityId);
                    }).filter(Objects::nonNull).collect(Collectors.toList());
                    entity.set(attrName, mrefEntities);
                }
            }
        }
    }
    return entities;
}
Also used : POPULATE(org.molgenis.data.EntityManager.CreationMode.POPULATE) java.util(java.util) EntityTypeUtils(org.molgenis.data.support.EntityTypeUtils) Attribute(org.molgenis.data.meta.model.Attribute) EntityType(org.molgenis.data.meta.model.EntityType) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) Iterators(com.google.common.collect.Iterators) SetMultimap(com.google.common.collect.SetMultimap) EntityTypeUtils.isMultipleReferenceType(org.molgenis.data.support.EntityTypeUtils.isMultipleReferenceType) Collections.singletonList(java.util.Collections.singletonList) EntityPopulator(org.molgenis.data.populate.EntityPopulator) EntityWithComputedAttributes(org.molgenis.data.support.EntityWithComputedAttributes) Component(org.springframework.stereotype.Component) HashMultimap(com.google.common.collect.HashMultimap) PartialEntity(org.molgenis.data.support.PartialEntity) Stream(java.util.stream.Stream) DynamicEntity(org.molgenis.data.support.DynamicEntity) StreamSupport.stream(java.util.stream.StreamSupport.stream) Objects.requireNonNull(java.util.Objects.requireNonNull) Entry(java.util.Map.Entry) StreamSupport(java.util.stream.StreamSupport) NO_POPULATE(org.molgenis.data.EntityManager.CreationMode.NO_POPULATE) EntityTypeUtils.isSingleReferenceType(org.molgenis.data.support.EntityTypeUtils.isSingleReferenceType) PartialEntity(org.molgenis.data.support.PartialEntity) DynamicEntity(org.molgenis.data.support.DynamicEntity) Attribute(org.molgenis.data.meta.model.Attribute) Collections.singletonList(java.util.Collections.singletonList)

Example 17 with SetMultimap

use of com.google.common.collect.SetMultimap in project batfish by batfish.

the class CommonUtil method initPrivateIpsByPublicIp.

@VisibleForTesting
static SetMultimap<Ip, IpWildcardSetIpSpace> initPrivateIpsByPublicIp(Map<String, Configuration> configurations) {
    /*
     * Very hacky mapping from public IP to set of spaces of possible natted private IPs.
     * Does not currently support source-nat acl.
     *
     * The current implementation just considers every IP in every prefix on a non-masquerading
     * interface (except the local address in each such prefix) to be a possible private IP
     * match for every public IP referred to by every source-nat pool on a masquerading interface.
     */
    ImmutableSetMultimap.Builder<Ip, IpWildcardSetIpSpace> builder = ImmutableSetMultimap.builder();
    for (Configuration c : configurations.values()) {
        Collection<Interface> interfaces = c.getInterfaces().values();
        Set<InterfaceAddress> nonNattedInterfaceAddresses = interfaces.stream().filter(i -> i.getSourceNats().isEmpty()).flatMap(i -> i.getAllAddresses().stream()).collect(ImmutableSet.toImmutableSet());
        Set<IpWildcard> blacklist = nonNattedInterfaceAddresses.stream().map(address -> new IpWildcard(address.getIp(), Ip.ZERO)).collect(ImmutableSet.toImmutableSet());
        Set<IpWildcard> whitelist = nonNattedInterfaceAddresses.stream().map(address -> new IpWildcard(address.getPrefix())).collect(ImmutableSet.toImmutableSet());
        IpWildcardSetIpSpace ipSpace = IpWildcardSetIpSpace.builder().including(whitelist).excluding(blacklist).build();
        interfaces.stream().flatMap(i -> i.getSourceNats().stream()).forEach(sourceNat -> {
            for (long ipAsLong = sourceNat.getPoolIpFirst().asLong(); ipAsLong <= sourceNat.getPoolIpLast().asLong(); ipAsLong++) {
                Ip currentPoolIp = new Ip(ipAsLong);
                builder.put(currentPoolIp, ipSpace);
            }
        });
    }
    return builder.build();
}
Also used : SSLEngineConfigurator(org.glassfish.grizzly.ssl.SSLEngineConfigurator) SSLContext(javax.net.ssl.SSLContext) FileTime(java.nio.file.attribute.FileTime) StringUtils(org.apache.commons.lang3.StringUtils) Configurations(org.apache.commons.configuration2.builder.fluent.Configurations) Interface(org.batfish.datamodel.Interface) DirectoryStream(java.nio.file.DirectoryStream) BfConsts(org.batfish.common.BfConsts) Flow(org.batfish.datamodel.Flow) Topology(org.batfish.datamodel.Topology) Map(java.util.Map) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) Pair(org.batfish.common.Pair) Path(java.nio.file.Path) DataPlane(org.batfish.datamodel.DataPlane) VrrpGroup(org.batfish.datamodel.VrrpGroup) ClientTracingFeature(io.opentracing.contrib.jaxrs2.client.ClientTracingFeature) Set(java.util.Set) FileAttribute(java.nio.file.attribute.FileAttribute) StandardCharsets(java.nio.charset.StandardCharsets) DirectoryIteratorException(java.nio.file.DirectoryIteratorException) IOUtils(org.apache.commons.io.IOUtils) Stream(java.util.stream.Stream) Supplier(java.util.function.Supplier) TreeSet(java.util.TreeSet) JSONAssert(org.skyscreamer.jsonassert.JSONAssert) MustBeClosed(com.google.errorprone.annotations.MustBeClosed) SSLSession(javax.net.ssl.SSLSession) FlowProcessor(org.batfish.common.plugin.FlowProcessor) BiConsumer(java.util.function.BiConsumer) SSLContextConfigurator(org.glassfish.grizzly.ssl.SSLContextConfigurator) ImmutableSortedMap(com.google.common.collect.ImmutableSortedMap) Nullable(javax.annotation.Nullable) Files(java.nio.file.Files) Route(org.batfish.datamodel.Route) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) KeyManager(javax.net.ssl.KeyManager) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) X509TrustManager(javax.net.ssl.X509TrustManager) BufferedReader(java.io.BufferedReader) X509Certificate(java.security.cert.X509Certificate) IpsecVpn(org.batfish.datamodel.IpsecVpn) NoSuchFileException(java.nio.file.NoSuchFileException) IpProtocol(org.batfish.datamodel.IpProtocol) SortedSet(java.util.SortedSet) URL(java.net.URL) TrustManager(javax.net.ssl.TrustManager) FlowTrace(org.batfish.datamodel.FlowTrace) InterfaceAddress(org.batfish.datamodel.InterfaceAddress) OspfNeighbor(org.batfish.datamodel.OspfNeighbor) Edge(org.batfish.datamodel.Edge) IpWildcardSetIpSpace(org.batfish.datamodel.IpWildcardSetIpSpace) OspfProcess(org.batfish.datamodel.OspfProcess) URI(java.net.URI) HostnameVerifier(javax.net.ssl.HostnameVerifier) NamedPort(org.batfish.datamodel.NamedPort) Vrf(org.batfish.datamodel.Vrf) OspfArea(org.batfish.datamodel.OspfArea) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) ImmutableSet(com.google.common.collect.ImmutableSet) IdentityHashMap(java.util.IdentityHashMap) PatternSyntaxException(java.util.regex.PatternSyntaxException) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) Collection(java.util.Collection) FlowDisposition(org.batfish.datamodel.FlowDisposition) KeyStore(java.security.KeyStore) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) FileNotFoundException(java.io.FileNotFoundException) List(java.util.List) Entry(java.util.Map.Entry) Pattern(java.util.regex.Pattern) BgpNeighbor(org.batfish.datamodel.BgpNeighbor) SortedMap(java.util.SortedMap) IpWildcard(org.batfish.datamodel.IpWildcard) Ip(org.batfish.datamodel.Ip) NodeInterfacePair(org.batfish.datamodel.collections.NodeInterfacePair) Hashing(com.google.common.hash.Hashing) HashMap(java.util.HashMap) BatfishException(org.batfish.common.BatfishException) BgpProcess(org.batfish.datamodel.BgpProcess) Function(java.util.function.Function) HashSet(java.util.HashSet) ClientBuilder(javax.ws.rs.client.ClientBuilder) Configuration(org.batfish.datamodel.Configuration) OutputStreamWriter(java.io.OutputStreamWriter) OutputStream(java.io.OutputStream) IpLink(org.batfish.datamodel.IpLink) Iterator(java.util.Iterator) MalformedURLException(java.net.MalformedURLException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) GlobalTracer(io.opentracing.util.GlobalTracer) FileInputStream(java.io.FileInputStream) SetMultimap(com.google.common.collect.SetMultimap) Consumer(java.util.function.Consumer) GrizzlyHttpServerFactory(org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) InputStream(java.io.InputStream) Prefix(org.batfish.datamodel.Prefix) Configuration(org.batfish.datamodel.Configuration) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) InterfaceAddress(org.batfish.datamodel.InterfaceAddress) Ip(org.batfish.datamodel.Ip) IpWildcard(org.batfish.datamodel.IpWildcard) IpWildcardSetIpSpace(org.batfish.datamodel.IpWildcardSetIpSpace) Interface(org.batfish.datamodel.Interface) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 18 with SetMultimap

use of com.google.common.collect.SetMultimap in project presto by prestodb.

the class TestPrestoSparkSourceDistributionSplitAssigner method testAssignSplitsToPartitionWithRandomSplitSizes.

@Test
public void testAssignSplitsToPartitionWithRandomSplitSizes() {
    DataSize maxSplitDataSizePerPartition = new DataSize(2048, BYTE);
    int initialPartitionCount = 3;
    int minSparkInputPartitionCountForAutoTune = 2;
    int maxSparkInputPartitionCountForAutoTune = 5;
    int maxSplitSizeInBytes = 2048;
    AtomicInteger sequenceId = new AtomicInteger();
    for (int i = 0; i < 3; ++i) {
        List<Long> splitSizes = new ArrayList<>(1000);
        for (int j = 0; j < 1000; j++) {
            splitSizes.add(ThreadLocalRandom.current().nextLong((long) (maxSplitSizeInBytes * 1.2)));
        }
        PrestoSparkSplitAssigner assigner = new PrestoSparkSourceDistributionSplitAssigner(new PlanNodeId("test"), createSplitSource(splitSizes), 333, maxSplitDataSizePerPartition.toBytes(), initialPartitionCount, true, minSparkInputPartitionCountForAutoTune, maxSparkInputPartitionCountForAutoTune);
        HashMultimap<Integer, ScheduledSplit> actualAssignment = HashMultimap.create();
        while (true) {
            Optional<SetMultimap<Integer, ScheduledSplit>> assignment = assigner.getNextBatch();
            if (!assignment.isPresent()) {
                break;
            }
            actualAssignment.putAll(assignment.get());
        }
        long expectedSizeInBytes = splitSizes.stream().mapToLong(Long::longValue).sum();
        long actualTotalSizeInBytes = actualAssignment.values().stream().mapToLong(split -> split.getSplit().getConnectorSplit().getSplitSizeInBytes().orElseThrow(() -> new IllegalArgumentException("split size is expected to be present"))).sum();
        // check if all splits got assigned
        assertEquals(expectedSizeInBytes, actualTotalSizeInBytes);
    }
}
Also used : PlanNodeId(com.facebook.presto.spi.plan.PlanNodeId) ConnectorPartitionHandle(com.facebook.presto.spi.connector.ConnectorPartitionHandle) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) ConnectorTransactionHandle(com.facebook.presto.spi.connector.ConnectorTransactionHandle) ArrayList(java.util.ArrayList) NOT_PARTITIONED(com.facebook.presto.spi.connector.NotPartitionedPartitionHandle.NOT_PARTITIONED) OptionalLong(java.util.OptionalLong) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) HashMultimap(com.google.common.collect.HashMultimap) ImmutableList(com.google.common.collect.ImmutableList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Objects.requireNonNull(java.util.Objects.requireNonNull) ScheduledSplit(com.facebook.presto.execution.ScheduledSplit) SplitSource(com.facebook.presto.split.SplitSource) Futures.immediateFuture(com.google.common.util.concurrent.Futures.immediateFuture) Lifespan(com.facebook.presto.execution.Lifespan) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) HostAddress(com.facebook.presto.spi.HostAddress) NodeSelectionStrategy(com.facebook.presto.spi.schedule.NodeSelectionStrategy) Ints.min(com.google.common.primitives.Ints.min) TestingTransactionHandle(com.facebook.presto.testing.TestingTransactionHandle) NodeProvider(com.facebook.presto.spi.NodeProvider) SetMultimap(com.google.common.collect.SetMultimap) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ConnectorSplit(com.facebook.presto.spi.ConnectorSplit) DataSize(io.airlift.units.DataSize) List(java.util.List) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) Split(com.facebook.presto.metadata.Split) Optional(java.util.Optional) ConnectorId(com.facebook.presto.spi.ConnectorId) Comparator(java.util.Comparator) BYTE(io.airlift.units.DataSize.Unit.BYTE) ScheduledSplit(com.facebook.presto.execution.ScheduledSplit) ArrayList(java.util.ArrayList) PlanNodeId(com.facebook.presto.spi.plan.PlanNodeId) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SetMultimap(com.google.common.collect.SetMultimap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DataSize(io.airlift.units.DataSize) OptionalLong(java.util.OptionalLong) Test(org.testng.annotations.Test)

Example 19 with SetMultimap

use of com.google.common.collect.SetMultimap in project gerrit by GerritCodeReview.

the class LabelsJson method labelsForSubmittedChange.

private Map<String, LabelWithStatus> labelsForSubmittedChange(AccountLoader accountLoader, ChangeData cd, LabelTypes labelTypes, boolean standard, boolean detailed) throws PermissionBackendException {
    Set<Account.Id> allUsers = new HashSet<>();
    if (detailed) {
        // the latest patch set (in the next loop).
        for (PatchSetApproval psa : cd.approvals().values()) {
            allUsers.add(psa.accountId());
        }
    }
    Set<String> labelNames = new HashSet<>();
    SetMultimap<Account.Id, PatchSetApproval> current = MultimapBuilder.hashKeys().hashSetValues().build();
    for (PatchSetApproval a : cd.currentApprovals()) {
        allUsers.add(a.accountId());
        Optional<LabelType> type = labelTypes.byLabel(a.labelId());
        if (type.isPresent()) {
            labelNames.add(type.get().getName());
            // Not worth the effort to distinguish between votable/non-votable for 0
            // values on closed changes, since they can't vote anyway.
            current.put(a.accountId(), a);
        }
    }
    // Since voting on merged changes is allowed all labels which apply to
    // the change must be returned. All applying labels can be retrieved from
    // the submit records, which is what initLabels does.
    // It's not possible to only compute the labels based on the approvals
    // since merged changes may not have approvals for all labels (e.g. if not
    // all labels are required for submit or if the change was auto-closed due
    // to direct push or if new labels were defined after the change was
    // merged).
    Map<String, LabelWithStatus> labels;
    labels = initLabels(accountLoader, cd, labelTypes, standard);
    // it wouldn't be included in the submit records.
    for (String name : labelNames) {
        if (!labels.containsKey(name)) {
            labels.put(name, LabelWithStatus.create(new LabelInfo(), null));
        }
    }
    labels.entrySet().stream().filter(e -> labelTypes.byLabel(e.getKey()).isPresent()).forEach(e -> setLabelValues(labelTypes.byLabel(e.getKey()).get(), e.getValue()));
    for (Account.Id accountId : allUsers) {
        Map<String, ApprovalInfo> byLabel = Maps.newHashMapWithExpectedSize(labels.size());
        Map<String, VotingRangeInfo> pvr = Collections.emptyMap();
        if (detailed) {
            pvr = getPermittedVotingRanges(permittedLabels(accountId, cd));
        }
        for (Map.Entry<String, LabelWithStatus> entry : labels.entrySet()) {
            ApprovalInfo ai = approvalInfo(accountLoader, accountId, 0, null, null, null);
            byLabel.put(entry.getKey(), ai);
            addApproval(entry.getValue().label(), ai);
        }
        for (PatchSetApproval psa : current.get(accountId)) {
            Optional<LabelType> type = labelTypes.byLabel(psa.labelId());
            if (!type.isPresent()) {
                continue;
            }
            short val = psa.value();
            ApprovalInfo info = byLabel.get(type.get().getName());
            if (info != null) {
                info.value = Integer.valueOf(val);
                info.permittedVotingRange = pvr.getOrDefault(type.get().getName(), null);
                info.setDate(psa.granted());
                info.tag = psa.tag().orElse(null);
                if (psa.postSubmit()) {
                    info.postSubmit = true;
                }
            }
            if (!standard) {
                continue;
            }
            setLabelScores(accountLoader, type.get(), labels.get(type.get().getName()), val, accountId);
        }
    }
    return labels;
}
Also used : Iterables(com.google.common.collect.Iterables) AccountLoader(com.google.gerrit.server.account.AccountLoader) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) LabelInfo(com.google.gerrit.extensions.common.LabelInfo) MultimapBuilder(com.google.common.collect.MultimapBuilder) Inject(com.google.inject.Inject) HashBasedTable(com.google.common.collect.HashBasedTable) HashMap(java.util.HashMap) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) LabelTypes(com.google.gerrit.entities.LabelTypes) Lists(com.google.common.collect.Lists) LabelValue(com.google.gerrit.entities.LabelValue) LabelType(com.google.gerrit.entities.LabelType) Map(java.util.Map) ChangeUtil(com.google.gerrit.server.ChangeUtil) LinkedHashMultimap(com.google.common.collect.LinkedHashMultimap) ApprovalInfo(com.google.gerrit.extensions.common.ApprovalInfo) ImmutableMap(com.google.common.collect.ImmutableMap) ReviewerStateInternal(com.google.gerrit.server.notedb.ReviewerStateInternal) Collection(java.util.Collection) Account(com.google.gerrit.entities.Account) Set(java.util.Set) Instant(java.time.Instant) Maps(com.google.common.collect.Maps) Ints(com.google.common.primitives.Ints) SubmitRecord(com.google.gerrit.entities.SubmitRecord) SetMultimap(com.google.common.collect.SetMultimap) Preconditions.checkState(com.google.common.base.Preconditions.checkState) VotingRangeInfo(com.google.gerrit.extensions.common.VotingRangeInfo) Collectors.toList(java.util.stream.Collectors.toList) ChangeData(com.google.gerrit.server.query.change.ChangeData) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) TreeMap(java.util.TreeMap) AutoValue(com.google.auto.value.AutoValue) Optional(java.util.Optional) Table(com.google.common.collect.Table) Collections(java.util.Collections) FluentLogger(com.google.common.flogger.FluentLogger) LabelPermission(com.google.gerrit.server.permissions.LabelPermission) Singleton(com.google.inject.Singleton) Account(com.google.gerrit.entities.Account) VotingRangeInfo(com.google.gerrit.extensions.common.VotingRangeInfo) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) LabelInfo(com.google.gerrit.extensions.common.LabelInfo) ApprovalInfo(com.google.gerrit.extensions.common.ApprovalInfo) LabelType(com.google.gerrit.entities.LabelType) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) TreeMap(java.util.TreeMap) HashSet(java.util.HashSet)

Example 20 with SetMultimap

use of com.google.common.collect.SetMultimap in project gerrit by GerritCodeReview.

the class StalenessChecker method check.

/**
 * Returns a {@link StalenessCheckResult} with structured information about staleness of the
 * provided {@link com.google.gerrit.entities.Project.NameKey}.
 */
public StalenessCheckResult check(Project.NameKey project) {
    ProjectData projectData = projectCache.get(project).orElseThrow(illegalState(project)).toProjectData();
    ProjectIndex i = indexes.getSearchIndex();
    if (i == null) {
        return StalenessCheckResult.notStale();
    }
    Optional<FieldBundle> result = i.getRaw(project, QueryOptions.create(indexConfig, 0, 1, FIELDS));
    if (!result.isPresent()) {
        return StalenessCheckResult.stale("Document %s missing from index", project);
    }
    SetMultimap<Project.NameKey, RefState> indexedRefStates = RefState.parseStates(result.get().getValue(ProjectField.REF_STATE));
    SetMultimap<Project.NameKey, RefState> currentRefStates = MultimapBuilder.hashKeys().hashSetValues().build();
    projectData.tree().stream().filter(p -> p.getProject().getConfigRefState() != null).forEach(p -> currentRefStates.put(p.getProject().getNameKey(), RefState.create(RefNames.REFS_CONFIG, p.getProject().getConfigRefState())));
    if (currentRefStates.equals(indexedRefStates)) {
        return StalenessCheckResult.notStale();
    }
    return StalenessCheckResult.stale("Document has unexpected ref states (%s != %s)", currentRefStates, indexedRefStates);
}
Also used : RefState(com.google.gerrit.index.RefState) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) ImmutableSet(com.google.common.collect.ImmutableSet) IndexConfig(com.google.gerrit.index.IndexConfig) ProjectCache(com.google.gerrit.server.project.ProjectCache) MultimapBuilder(com.google.common.collect.MultimapBuilder) ProjectField(com.google.gerrit.index.project.ProjectField) Inject(com.google.inject.Inject) QueryOptions(com.google.gerrit.index.QueryOptions) ProjectData(com.google.gerrit.index.project.ProjectData) SetMultimap(com.google.common.collect.SetMultimap) StalenessCheckResult(com.google.gerrit.server.index.StalenessCheckResult) ProjectIndex(com.google.gerrit.index.project.ProjectIndex) ProjectIndexCollection(com.google.gerrit.index.project.ProjectIndexCollection) Project(com.google.gerrit.entities.Project) RefNames(com.google.gerrit.entities.RefNames) FieldBundle(com.google.gerrit.index.query.FieldBundle) Optional(java.util.Optional) RefState(com.google.gerrit.index.RefState) FieldBundle(com.google.gerrit.index.query.FieldBundle) ProjectIndex(com.google.gerrit.index.project.ProjectIndex) ProjectData(com.google.gerrit.index.project.ProjectData)

Aggregations

SetMultimap (com.google.common.collect.SetMultimap)21 List (java.util.List)11 Map (java.util.Map)11 Set (java.util.Set)11 HashSet (java.util.HashSet)9 Optional (java.util.Optional)9 ImmutableSet (com.google.common.collect.ImmutableSet)8 ArrayList (java.util.ArrayList)8 HashMap (java.util.HashMap)8 ImmutableMap (com.google.common.collect.ImmutableMap)7 Collections (java.util.Collections)7 HashMultimap (com.google.common.collect.HashMultimap)6 Sets (com.google.common.collect.Sets)6 ImmutableList (com.google.common.collect.ImmutableList)5 ImmutableSetMultimap (com.google.common.collect.ImmutableSetMultimap)5 Collection (java.util.Collection)4 VisibleForTesting (com.google.common.annotations.VisibleForTesting)3 Preconditions.checkState (com.google.common.base.Preconditions.checkState)3 LinkedHashMultimap (com.google.common.collect.LinkedHashMultimap)3 MultimapBuilder (com.google.common.collect.MultimapBuilder)3