Example usage for com.google.common.collect Multimap isEmpty

List of usage examples for com.google.common.collect Multimap isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect Multimap isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this multimap contains no key-value pairs.

Usage

From source file:com.torodb.torod.db.backends.query.QueryEvaluator.java

@Nonnull
private Map<Integer, DatabaseQuery> createDatabaseQueryByStructure(@Nullable QueryCriteria criteria,
        DSLContext dsl) {/*w  ww.  j a  v  a2s .c  o m*/

    Map<Integer, DatabaseQuery> result;

    if (criteria == null) {
        BiMap<Integer, DocStructure> allStructures = colSchema.getStructuresCache().getAllStructures();
        result = Maps.newHashMapWithExpectedSize(allStructures.size());

        DatabaseQuery databaseQuery = SelectAllDatabaseQuery.getInstance();

        for (Integer sid : colSchema.getStructuresCache().getAllStructures().keySet()) {
            result.put(sid, databaseQuery);
        }
    } else {
        Multimap<Integer, QueryCriteria> candidateStructures = QueryStructureFilter.filterStructures(colSchema,
                criteria);

        if (candidateStructures.isEmpty()) {
            result = Collections.emptyMap();
        } else {
            result = Maps.newHashMapWithExpectedSize(candidateStructures.size());

            for (Map.Entry<Integer, QueryCriteria> entry : candidateStructures.entries()) {
                Integer sid = entry.getKey();
                DocStructure rootStructure = colSchema.getStructuresCache().getStructure(sid);

                DatabaseQuery databaseQuery = createDatabaseQuery(entry.getValue(), sid, rootStructure, dsl);

                if (!(databaseQuery instanceof FalseDatabaseQuery)) {
                    result.put(sid, databaseQuery);
                }
            }
        }
    }

    return result;
}

From source file:com.palantir.atlasdb.keyvalue.partition.BasicPartitionMap.java

private <ValType> Map<KeyValueService, Multimap<Cell, ValType>> getServicesForCellsMultimap(String tableName,
        Multimap<Cell, ValType> cellMultimap) {
    Map<KeyValueService, Multimap<Cell, ValType>> result = Maps.newHashMap();
    for (Map.Entry<Cell, ValType> e : cellMultimap.entries()) {
        Set<KeyValueService> services = getServicesHavingRow(e.getKey().getRowName());
        for (KeyValueService kvs : services) {
            if (!result.containsKey(kvs)) {
                result.put(kvs, HashMultimap.<Cell, ValType>create());
            }//from   w  ww . j a v  a  2 s. co m
            assert !result.get(kvs).containsEntry(e.getKey(), e.getValue());
            result.get(kvs).put(e.getKey(), e.getValue());
        }
    }
    if (!cellMultimap.isEmpty()) {
        assert result.keySet().size() >= quorumParameters.getReplicationFactor();
    }
    return result;
}

From source file:com.facebook.buck.apple.ApplePackageDescription.java

/**
 * Get the correct package configuration based on the platform flavors of this build target.
 *
 * Validates that all named platforms yields the identical package config.
 *
 * @return If found, a package config for this target.
 * @throws HumanReadableException if there are multiple possible package configs.
 *///from   w ww.  j  a v a2 s .  c  om
private Optional<ApplePackageConfigAndPlatformInfo> getApplePackageConfig(BuildTarget target,
        Function<String, com.facebook.buck.rules.args.Arg> macroExpander) {
    Set<Flavor> platformFlavors = getPlatformFlavorsOrDefault(target);

    // Ensure that different platforms generate the same config.
    // The value of this map is just for error reporting.
    Multimap<Optional<ApplePackageConfigAndPlatformInfo>, Flavor> packageConfigs = MultimapBuilder.hashKeys()
            .arrayListValues().build();

    for (Flavor flavor : platformFlavors) {
        AppleCxxPlatform platform = appleCxxPlatformFlavorDomain.getValue(flavor);
        Optional<ApplePackageConfig> packageConfig = config
                .getPackageConfigForPlatform(platform.getAppleSdk().getApplePlatform());
        packageConfigs.put(packageConfig.isPresent()
                ? Optional
                        .of(ApplePackageConfigAndPlatformInfo.of(packageConfig.get(), macroExpander, platform))
                : Optional.empty(), flavor);
    }

    if (packageConfigs.isEmpty()) {
        return Optional.empty();
    } else if (packageConfigs.keySet().size() == 1) {
        return Iterables.getOnlyElement(packageConfigs.keySet());
    } else {
        throw new HumanReadableException(
                "In target %s: Multi-architecture package has different package configs for targets: %s",
                target.getFullyQualifiedName(), packageConfigs.asMap().values());
    }
}

From source file:org.eclipse.xtext.ui.refactoring.impl.AbstractReferenceUpdater.java

protected void createClusteredReferenceUpdates(ElementRenameArguments elementRenameArguments,
        Multimap<URI, IReferenceDescription> resource2references, ResourceSet resourceSet,
        IRefactoringUpdateAcceptor updateAcceptor, StatusWrapper status, IProgressMonitor monitor) {
    SubMonitor progress = SubMonitor.convert(monitor, resource2references.keySet().size() + 1);
    if (loadTargetResources(resourceSet, elementRenameArguments, status, progress.newChild(1))) {
        if (getClusterSize() > 0) {
            Set<Resource> targetResources = newHashSet(resourceSet.getResources());
            Multimap<URI, IReferenceDescription> cluster = HashMultimap.create();
            SubMonitor clusterMonitor = progress.newChild(1);
            for (URI referringResourceURI : resource2references.keySet()) {
                cluster.putAll(referringResourceURI, resource2references.get(referringResourceURI));
                if (cluster.keySet().size() == getClusterSize()) {
                    unloadNonTargetResources(resourceSet, targetResources);
                    createReferenceUpdatesForCluster(elementRenameArguments, cluster, resourceSet,
                            updateAcceptor, status, clusterMonitor);
                    cluster.clear();//from   w  ww  .ja  va2s  . c  o  m
                }
            }
            if (!cluster.isEmpty()) {
                unloadNonTargetResources(resourceSet, targetResources);
                createReferenceUpdatesForCluster(elementRenameArguments, cluster, resourceSet, updateAcceptor,
                        status, clusterMonitor);
            }
        } else {
            createReferenceUpdatesForCluster(elementRenameArguments, resource2references, resourceSet,
                    updateAcceptor, status, progress.newChild(resource2references.keySet().size()));
        }
    }
}

From source file:com.android.tools.lint.checks.FullBackupContentDetector.java

@Override
public void visitDocument(@NonNull XmlContext context, @NonNull Document document) {
    Element root = document.getDocumentElement();
    if (root == null) {
        return;//from w w  w  .  j a  v a2  s . co m
    }
    if (!TAG_FULL_BACKUP_CONTENT.equals(root.getTagName())) {
        return;
    }

    List<Element> includes = Lists.newArrayList();
    List<Element> excludes = Lists.newArrayList();
    NodeList children = root.getChildNodes();
    for (int i = 0, n = children.getLength(); i < n; i++) {
        Node child = children.item(i);
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) child;
            String tag = element.getTagName();
            if (TAG_INCLUDE.equals(tag)) {
                includes.add(element);
            } else if (TAG_EXCLUDE.equals(tag)) {
                excludes.add(element);
            } else {
                // See FullBackup#validateInnerTagContents
                context.report(ISSUE, element, context.getNameLocation(element),
                        String.format("Unexpected element `<%1$s>`", tag));
            }
        }
    }

    Multimap<String, String> includePaths = ArrayListMultimap.create(includes.size(), 4);
    for (Element include : includes) {
        String domain = validateDomain(context, include);
        String path = validatePath(context, include);
        if (domain == null) {
            continue;
        }
        includePaths.put(domain, path);
    }

    for (Element exclude : excludes) {
        String excludePath = validatePath(context, exclude);
        if (excludePath.isEmpty()) {
            continue;
        }
        String domain = validateDomain(context, exclude);
        if (domain == null) {
            continue;
        }
        if (includePaths.isEmpty()) {
            // There is no <include> anywhere: that means that everything
            // is considered included and there's no potential prefix mismatch
            continue;
        }

        boolean hasPrefix = false;
        Collection<String> included = includePaths.get(domain);
        if (included == null) {
            continue;
        }
        for (String includePath : included) {
            if (excludePath.startsWith(includePath)) {
                if (excludePath.equals(includePath)) {
                    Attr pathNode = exclude.getAttributeNode(ATTR_PATH);
                    assert pathNode != null;
                    Location location = context.getValueLocation(pathNode);
                    // Find corresponding include path so we can link to it in the
                    // chained location list
                    for (Element include : includes) {
                        Attr includePathNode = include.getAttributeNode(ATTR_PATH);
                        String includeDomain = include.getAttribute(ATTR_DOMAIN);
                        if (includePathNode != null && excludePath.equals(includePathNode.getValue())
                                && domain.equals(includeDomain)) {
                            Location earlier = context.getLocation(includePathNode);
                            earlier.setMessage("Unnecessary/conflicting <include>");
                            location.setSecondary(earlier);
                        }
                    }
                    context.report(ISSUE, exclude, location,
                            String.format("Include `%1$s` is also excluded", excludePath));
                }
                hasPrefix = true;
                break;
            }
        }
        if (!hasPrefix) {
            Attr pathNode = exclude.getAttributeNode(ATTR_PATH);
            assert pathNode != null;
            context.report(ISSUE, exclude, context.getValueLocation(pathNode),
                    String.format("`%1$s` is not in an included path", excludePath));
        }
    }
}

From source file:com.palantir.atlasdb.keyvalue.jdbc.JdbcKeyValueService.java

@Override
public void delete(final String tableName, final Multimap<Cell, Long> keys) {
    if (keys.isEmpty()) {
        return;/*  w w w . j av a 2s.c o  m*/
    }
    run(new Function<DSLContext, Void>() {
        @Override
        public Void apply(DSLContext ctx) {
            Collection<Row3<byte[], byte[], Long>> rows = Lists.newArrayListWithCapacity(keys.size());
            for (Entry<Cell, Long> entry : keys.entries()) {
                rows.add(row(entry.getKey().getRowName(), entry.getKey().getColumnName(), entry.getValue()));
            }
            ctx.deleteFrom(atlasTable(tableName).as(ATLAS_TABLE))
                    .where(row(A_ROW_NAME, A_COL_NAME, A_TIMESTAMP).in(rows)).execute();
            return null;
        }
    });
}

From source file:org.waveprotocol.wave.examples.fedone.waveserver.CertificateManagerImpl.java

/**
 * Dequeue all signer info requests for a given signer id and a specific domain.
 *
 * @param signerId to dequeue requests for
 * @param error if there was an error, null for success
 * @param domain to dequeue the signer requests for
 *///ww  w. j a v  a 2s  .c o m
private synchronized void dequeueSignerInfoRequestForDomain(ByteString signerId, FederationError error,
        String domain) {
    Multimap<String, SignerInfoPrefetchResultListener> domainListeners = signerInfoRequests.get(signerId);
    if (domainListeners == null) {
        LOG.info("There are no domain listeners for signer " + signerId + " domain " + domain);
        return;
    } else {
        LOG.info("Dequeuing " + domainListeners.size() + " listeners for domain " + domain);
    }

    for (SignerInfoPrefetchResultListener listener : domainListeners.get(domain)) {
        if (error == null) {
            listener.onSuccess(retrieveSignerInfo(signerId));
        } else {
            listener.onFailure(error);
        }
    }

    domainListeners.removeAll(domain);
    if (domainListeners.isEmpty()) {
        // No listeners for any domains, delete the signer id for the overall map
        signerInfoRequests.remove(signerId);
    }
}

From source file:org.glowroot.agent.live.ClasspathCache.java

synchronized void updateCache() {
    Multimap<String, Location> newClassNameLocations = HashMultimap.create();
    for (ClassLoader loader : getKnownClassLoaders()) {
        updateCache(loader, newClassNameLocations);
    }/*from   w  w  w  .java2 s .com*/
    updateCacheWithClasspathClasses(newClassNameLocations);
    updateCacheWithBootstrapClasses(newClassNameLocations);
    if (!newClassNameLocations.isEmpty()) {
        // multimap that sorts keys and de-dups values while maintains value ordering
        SetMultimap<String, Location> newMap = MultimapBuilder.treeKeys().linkedHashSetValues().build();
        newMap.putAll(classNameLocations);
        newMap.putAll(newClassNameLocations);
        classNameLocations = ImmutableMultimap.copyOf(newMap);
    }
}

From source file:org.eclipse.osee.orcs.db.internal.change.MissingChangeItemFactoryImpl.java

private Collection<ChangeItem> createMissingChangeItems(HasCancellation cancellation, OrcsSession session,
        TransactionReadable sourceTx, TransactionReadable destTx, final Set<Integer> modifiedArtIds,
        final Multimap<Integer, Integer> modifiedAttrIds, final Multimap<Integer, Integer> modifiedRels,
        final Set<Integer> missingArtIds, final Set<Integer> allArtIds) throws OseeCoreException {
    final Set<ChangeItem> toReturn = new LinkedHashSet<ChangeItem>();
    final Set<RelationData> relations = new LinkedHashSet<RelationData>();

    DataLoader loader = dataLoaderFactory.newDataLoaderFromIds(session, getBranch(sourceTx), missingArtIds);
    loader.withLoadLevel(LoadLevel.ALL);
    loader.includeDeletedArtifacts();/* ww w. ja v a  2  s .  c  o  m*/
    loader.fromTransaction(sourceTx.getGuid());

    loader.load(cancellation, new LoadDataHandlerAdapter() {

        @Override
        public void onData(ArtifactData data) throws OseeCoreException {
            if (!modifiedArtIds.contains(data.getLocalId())) {
                toReturn.add(createArtifactChangeItem(data));
            }
        }

        @Override
        public void onData(RelationData data) {
            int localId = data.getLocalId();
            if (!modifiedRels.get(data.getArtIdA()).contains(localId)
                    && !modifiedRels.get(data.getArtIdB()).contains(localId)) {
                relations.add(data);
            }
        }

        @Override
        public void onData(AttributeData data) throws OseeCoreException {
            if (!modifiedAttrIds.get(data.getArtifactId()).contains(data.getLocalId())) {
                toReturn.add(createAttributeChangeItem(data));
            }
        }

    });

    if (!relations.isEmpty()) {
        Multimap<Integer, RelationData> relationChangesToAdd = LinkedListMultimap.create();
        for (RelationData data : relations) {
            if (allArtIds.contains(data.getArtIdA())) {
                if (allArtIds.contains(data.getArtIdB())) {
                    toReturn.add(createRelationChangeItem(data));
                } else {
                    // check if artIdB exists on destination branch, addRelation if it does
                    relationChangesToAdd.put(data.getArtIdB(), data);
                }
            } else if (allArtIds.contains(data.getArtIdB())) {
                // if artIdA exists on destination, addRelation
                relationChangesToAdd.put(data.getArtIdA(), data);
            }
        }
        if (!relationChangesToAdd.isEmpty()) {
            toReturn.addAll(createExistingRelations(cancellation, session, destTx, relationChangesToAdd));
        }
    }
    return toReturn;
}

From source file:com.palantir.atlasdb.keyvalue.jdbc.JdbcKeyValueService.java

@Override
public void putWithTimestamps(final String tableName, final Multimap<Cell, Value> values)
        throws KeyAlreadyExistsException {
    if (values.isEmpty()) {
        return;/*from ww  w  .j  av  a 2  s. com*/
    }
    run(new Function<DSLContext, Void>() {
        @Override
        public Void apply(DSLContext ctx) {
            putBatch(ctx, tableName, new MultiTimestampPutBatch(values), true);
            return null;
        }
    });
}