Example usage for com.google.common.collect ImmutableMap entrySet

List of usage examples for com.google.common.collect ImmutableMap entrySet

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMap entrySet.

Prototype

public final ImmutableSet<Entry<K, V>> entrySet() 

Source Link

Usage

From source file:org.apache.abdera2.activities.model.ASBase.java

public <X extends ASBase, M extends Builder<X, M>> M templateWith(Map<String, Object> other) {
    ImmutableMap<String, Object> copy = other instanceof ImmutableMap ? (ImmutableMap<String, Object>) other
            : ImmutableMap.copyOf(other);
    M builder = this.<X, M>template(withoutFields(copy.keySet()));
    for (Map.Entry<String, Object> entry : copy.entrySet())
        builder.set(entry.getKey(), entry.getValue());
    return builder;
}

From source file:org.apache.abdera2.activities.model.ASBase.java

@SuppressWarnings("rawtypes")
public <T extends ASBase> T as(Class<T> type, Map<String, Object> other) {
    ImmutableMap<String, Object> copy = other instanceof ImmutableMap ? (ImmutableMap<String, Object>) other
            : ImmutableMap.copyOf(other);
    Builder builder = as(type, withoutFields(copy.keySet())).template();
    for (Entry<String, Object> entry : copy.entrySet())
        builder.set(entry.getKey(), entry.getValue());
    return (T) builder.get();
}

From source file:com.github.steveash.typedconfig.resolver.ProxyValueResolver.java

private boolean proxyEquals(Class<?> thisIface, ImmutableMap<Method, ValueResolver> thisResolvers,
        Object that) {/*from   w w w  .  j  av  a2s.  co  m*/

    if (!(that instanceof ProxiedConfiguration))
        return false;
    ProxiedConfiguration thatConfig = ((ProxiedConfiguration) that);

    Class<?> thatIface = thatConfig.getInterfaceClass();
    if (!thisIface.equals(thatIface))
        return false;

    ImmutableMap<Method, ValueResolver> thatResolvers = thatConfig.getResolvers();
    if (thisResolvers.size() != thatResolvers.size())
        throw new IllegalStateException("not sure how the same iface can have different resolver map");

    for (Entry<Method, ValueResolver> thisEntry : thisResolvers.entrySet()) {
        Object thisValue = thisEntry.getValue().resolve();
        Object thatValue = thatResolvers.get(thisEntry.getKey()).resolve();
        if (!thisValue.equals(thatValue))
            return false;
    }

    return true;
}

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

/**
 * Returns the valid annotated elements contained in all of the deferred elements. If none are
 * found for a deferred element, defers it again.
 *///w  w w.j a v  a2s. c o m
private ImmutableSetMultimap<Class<? extends Annotation>, Element> validElements(
        ImmutableMap<String, Optional<? extends Element>> deferredElements, RoundEnvironment roundEnv) {
    ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element> deferredElementsByAnnotationBuilder = ImmutableSetMultimap
            .builder();
    for (Entry<String, Optional<? extends Element>> deferredTypeElementEntry : deferredElements.entrySet()) {
        Optional<? extends Element> deferredElement = deferredTypeElementEntry.getValue();
        if (deferredElement.isPresent()) {
            findAnnotatedElements(deferredElement.get(), getSupportedAnnotationClasses(),
                    deferredElementsByAnnotationBuilder);
        } else {
            deferredElementNames.add(ElementName.forTypeName(deferredTypeElementEntry.getKey()));
        }
    }

    ImmutableSetMultimap<Class<? extends Annotation>, Element> deferredElementsByAnnotation = deferredElementsByAnnotationBuilder
            .build();

    ImmutableSetMultimap.Builder<Class<? extends Annotation>, Element> validElements = ImmutableSetMultimap
            .builder();

    Set<ElementName> validElementNames = new LinkedHashSet<ElementName>();

    // Look at the elements we've found and the new elements from this round and validate them.
    for (Class<? extends Annotation> annotationClass : getSupportedAnnotationClasses()) {
        // This should just call roundEnv.getElementsAnnotatedWith(Class) directly, but there is a bug
        // in some versions of eclipse that cause that method to crash.
        TypeElement annotationType = elements.getTypeElement(annotationClass.getCanonicalName());
        Set<? extends Element> elementsAnnotatedWith = (annotationType == null) ? ImmutableSet.<Element>of()
                : roundEnv.getElementsAnnotatedWith(annotationType);
        for (Element annotatedElement : Sets.union(elementsAnnotatedWith,
                deferredElementsByAnnotation.get(annotationClass))) {
            if (annotatedElement.getKind().equals(PACKAGE)) {
                PackageElement annotatedPackageElement = (PackageElement) annotatedElement;
                ElementName annotatedPackageName = ElementName
                        .forPackageName(annotatedPackageElement.getQualifiedName().toString());
                boolean validPackage = validElementNames.contains(annotatedPackageName)
                        || (!deferredElementNames.contains(annotatedPackageName)
                                && validateElement(annotatedPackageElement));
                if (validPackage) {
                    validElements.put(annotationClass, annotatedPackageElement);
                    validElementNames.add(annotatedPackageName);
                } else {
                    deferredElementNames.add(annotatedPackageName);
                }
            } else {
                TypeElement enclosingType = getEnclosingType(annotatedElement);
                ElementName enclosingTypeName = ElementName
                        .forTypeName(enclosingType.getQualifiedName().toString());
                boolean validEnclosingType = validElementNames.contains(enclosingTypeName)
                        || (!deferredElementNames.contains(enclosingTypeName)
                                && validateElement(enclosingType));
                if (validEnclosingType) {
                    validElements.put(annotationClass, annotatedElement);
                    validElementNames.add(enclosingTypeName);
                } else {
                    deferredElementNames.add(enclosingTypeName);
                }
            }
        }
    }

    return validElements.build();
}

From source file:com.opengamma.strata.pricer.rate.ImmutableRatesProvider.java

/**
 * Combines this provider with another.//w ww.j ava 2 s.c  o  m
 * <p> 
 * If the two providers have curves or time series for the same currency or index,
 * an {@link IllegalAccessException} is thrown. No attempt is made to combine the
 * FX providers, instead one is supplied.
 * 
 * @param other  the other rates provider
 * @param fxProvider  the FX rate provider to use
 * @return the combined provider
 */
public ImmutableRatesProvider combinedWith(ImmutableRatesProvider other, FxRateProvider fxProvider) {
    ImmutableRatesProviderBuilder merged = other.toBuilder();
    // discount
    ImmutableMap<Currency, Curve> dscMap1 = discountCurves;
    ImmutableMap<Currency, Curve> dscMap2 = other.discountCurves;
    for (Entry<Currency, Curve> entry : dscMap1.entrySet()) {
        ArgChecker.isTrue(!dscMap2.containsKey(entry.getKey()),
                "conflict on discount curve, currency '{}' appears twice in the providers", entry.getKey());
        merged.discountCurve(entry.getKey(), entry.getValue());
    }
    // forward
    ImmutableMap<Index, Curve> indexMap1 = indexCurves;
    ImmutableMap<Index, Curve> indexMap2 = other.indexCurves;
    for (Entry<Index, Curve> entry : indexMap1.entrySet()) {
        ArgChecker.isTrue(!indexMap2.containsKey(entry.getKey()),
                "conflict on index curve, index '{}' appears twice in the providers", entry.getKey());
        merged.indexCurve(entry.getKey(), entry.getValue());
    }
    // time series
    Map<Index, LocalDateDoubleTimeSeries> tsMap1 = timeSeries;
    Map<Index, LocalDateDoubleTimeSeries> tsMap2 = other.timeSeries;
    for (Entry<Index, LocalDateDoubleTimeSeries> entry : tsMap1.entrySet()) {
        ArgChecker.isTrue(!tsMap2.containsKey(entry.getKey()),
                "conflict on time series, index '{}' appears twice in the providers", entry.getKey());
        merged.timeSeries(entry.getKey(), entry.getValue());
    }
    merged.fxRateProvider(fxProvider);
    return merged.build();
}

From source file:com.facebook.buck.skylark.parser.SkylarkProjectBuildFileParser.java

private ImplicitlyLoadedExtension loadImplicitExtension(String basePath, Label containingLabel)
        throws IOException, InterruptedException {
    Optional<ImplicitInclude> implicitInclude = packageImplicitIncludeFinder
            .findIncludeForBuildFile(Paths.get(basePath));
    if (!implicitInclude.isPresent()) {
        return ImplicitlyLoadedExtension.empty();
    }/*w w w . java 2  s.c  om*/

    // Only export requested symbols, and ensure that all requsted symbols are present.
    ExtensionData data = loadExtension(LoadImport.of(containingLabel, implicitInclude.get().getLoadPath()));
    ImmutableMap<String, Object> symbols = data.getExtension().getBindings();
    ImmutableMap<String, String> expectedSymbols = implicitInclude.get().getSymbols();
    Builder<String, Object> loaded = ImmutableMap.builderWithExpectedSize(expectedSymbols.size());
    for (Entry<String, String> kvp : expectedSymbols.entrySet()) {
        Object symbol = symbols.get(kvp.getValue());
        if (symbol == null) {
            throw BuildFileParseException.createForUnknownParseError(
                    String.format("Could not find symbol '%s' in implicitly loaded extension '%s'",
                            kvp.getValue(), implicitInclude.get().getLoadPath().getImportString()));
        }
        loaded.put(kvp.getKey(), symbol);
    }
    return ImplicitlyLoadedExtension.of(data, loaded.build());
}

From source file:com.facebook.buck.cxx.AbstractCxxSourceRuleFactory.java

@VisibleForTesting
ImmutableMap<CxxPreprocessAndCompile, SourcePath> requirePreprocessAndCompileRules(
        ImmutableMap<String, CxxSource> sources) {

    return sources.entrySet().stream().map(entry -> {
        String name = entry.getKey();
        CxxSource source = entry.getValue();

        Preconditions.checkState(CxxSourceTypes.isPreprocessableType(source.getType())
                || CxxSourceTypes.isCompilableType(source.getType()));

        source = getSandboxedCxxSource(source);

        // If it's a preprocessable source, use a combine preprocess-and-compile build rule.
        // Otherwise, use a regular compile rule.
        if (CxxSourceTypes.isPreprocessableType(source.getType())) {
            return requirePreprocessAndCompileBuildRule(name, source);
        } else {//from   w ww.  j  a  va2 s. c  o m
            return requireCompileBuildRule(name, source);
        }
    }).collect(MoreCollectors.toImmutableMap(Function.identity(),
            input -> new BuildTargetSourcePath(input.getBuildTarget())));
}

From source file:com.google.errorprone.bugpatterns.ClassNewInstance.java

/**
 * Given a map of handled exception types and the trees of those handlers (i.e. catch clauses or
 * method throws clauses), determine which handlers are for reflective exceptions, and whether
 * all exceptions thrown by {#link Constructor#newInstance} are handled.
 *//*  w ww.  j  a  v a2 s. c o m*/
private <T> UnhandledResult<T> unhandled(ImmutableMap<Type, T> handles, VisitorState state) {
    LinkedHashSet<Type> toHandle = new LinkedHashSet<>();
    for (Class<?> e : Arrays.asList(InstantiationException.class, IllegalAccessException.class,
            InvocationTargetException.class, NoSuchMethodException.class)) {
        Type type = state.getTypeFromString(e.getName());
        if (type != null) {
            toHandle.add(type);
        }
    }
    Type roe = state.getTypeFromString(ReflectiveOperationException.class.getName());
    ImmutableMap.Builder<Type, T> newHandles = ImmutableMap.builder();
    for (Map.Entry<Type, T> entry : handles.entrySet()) {
        Type type = entry.getKey();
        if (ASTHelpers.isSubtype(type, roe, state)) {
            newHandles.put(type, entry.getValue());
        }
        for (Type precise : type.isUnion() ? ((Type.UnionClassType) type).getAlternativeTypes()
                : Collections.singleton(type)) {
            Iterator<Type> it = toHandle.iterator();
            while (it.hasNext()) {
                if (ASTHelpers.isSubtype(it.next(), precise, state)) {
                    it.remove();
                }
            }
        }
    }
    return new UnhandledResult<>(ImmutableSet.copyOf(toHandle), newHandles.build());
}

From source file:com.facebook.buck.artifact_cache.AbstractAsynchronousCache.java

private void doMultiCheck(ImmutableMap<RuleKey, ClaimedFetchRequest> ruleKeyToRequest) {
    try {// ww w .  j a v  a2s . c  o  m
        ImmutableMap<RuleKey, CacheResult> ruleKeyToResult = multiContainsImpl(ruleKeyToRequest.keySet())
                .getCacheResults();
        for (Map.Entry<RuleKey, CacheResult> result : ruleKeyToResult.entrySet()) {
            CacheResult cacheResult = result.getValue();
            ClaimedFetchRequest claimedFetchRequest = ruleKeyToRequest.get(result.getKey());
            if (claimedFetchRequest == null) {
                LOG.verbose("Recived cache result for not requested rule key.");
                continue;
            }
            if (!cacheResult.getType().isSuccess()) {
                // If rule key is not present in the cache, there is no point in trying to download
                // it.
                claimedFetchRequest.setResult(cacheResult);
            } else {
                // Otherwise reschedule it. It will be added to the fetch queue and it will be picked
                // by fetching thread.
                claimedFetchRequest.reschedule();
            }
        }
    } catch (IOException e) {
        String msg = String.format("multicheck(<%s>): %s: %s", Joiner.on(", ").join(ruleKeyToRequest.keySet()),
                e.getClass().getName(), e.getMessage());
        // Some of these might already be fulfilled. That's fine, this set() call will just be
        // ignored.
        for (ClaimedFetchRequest request : ruleKeyToRequest.values()) {
            request.setResult(CacheResult.error(name, mode, msg));
        }
    }
}

From source file:com.facebook.buck.versions.ParallelVersionedTargetGraphBuilder.java

@Override
protected VersionInfo getVersionInfo(TargetNode<?> node) {
    VersionInfo info = this.versionInfo.get(node.getBuildTarget());
    if (info != null) {
        return info;
    }/*from  w ww . j  a v  a 2 s.  c o m*/

    Map<BuildTarget, ImmutableSet<Version>> versionDomain = new HashMap<>();

    Optional<TargetNode<VersionedAliasDescriptionArg>> versionedNode = TargetGraphVersionTransformations
            .getVersionedNode(node);
    if (versionedNode.isPresent()) {
        ImmutableMap<Version, BuildTarget> versions = versionedNode.get().getConstructorArg().getVersions();

        // Merge in the versioned deps and the version domain.
        versionDomain.put(node.getBuildTarget(), versions.keySet());

        // If this version has only one possible choice, there's no need to wrap the constraints from
        // it's transitive deps in an implication constraint.
        if (versions.size() == 1) {
            Map.Entry<Version, BuildTarget> ent = versions.entrySet().iterator().next();
            VersionInfo depInfo = getVersionInfo(getNode(ent.getValue()));
            versionDomain.putAll(depInfo.getVersionDomain());
        } else {

            // For each version choice, inherit the transitive constraints by wrapping them in an
            // implication dependent on the specific version that pulls them in.
            for (Map.Entry<Version, BuildTarget> ent : versions.entrySet()) {
                VersionInfo depInfo = getVersionInfo(getNode(ent.getValue()));
                versionDomain.putAll(depInfo.getVersionDomain());
            }
        }
    } else {

        // Merge in the constraints and version domain/deps from transitive deps.
        for (BuildTarget depTarget : TargetGraphVersionTransformations.getDeps(typeCoercerFactory, node)) {
            TargetNode<?> dep = getNode(depTarget);
            if (TargetGraphVersionTransformations.isVersionPropagator(dep)
                    || TargetGraphVersionTransformations.getVersionedNode(dep).isPresent()) {
                VersionInfo depInfo = getVersionInfo(dep);
                versionDomain.putAll(depInfo.getVersionDomain());
            }
        }
    }

    info = VersionInfo.of(versionDomain);

    this.versionInfo.put(node.getBuildTarget(), info);
    return info;
}