Example usage for com.google.common.collect Maps filterKeys

List of usage examples for com.google.common.collect Maps filterKeys

Introduction

In this page you can find the example usage for com.google.common.collect Maps filterKeys.

Prototype

@CheckReturnValue
public static <K, V> BiMap<K, V> filterKeys(BiMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) 

Source Link

Document

Returns a bimap containing the mappings in unfiltered whose keys satisfy a predicate.

Usage

From source file:org.dcache.pool.nearline.HsmSet.java

@Override
public synchronized void afterSetup() {
    _isReadingSetup = false;/*ww w.j av  a 2  s .c o  m*/

    /* Remove the stores that are not in the new configuration.
     */
    Iterator<HsmInfo> iterator = Maps.filterKeys(_hsm, not(in(_newConfig.keySet()))).values().iterator();
    while (iterator.hasNext()) {
        iterator.next().shutdown();
        iterator.remove();
    }

    /* Apply configuration changes
     */
    for (HsmInfo hsm : _newConfig.values()) {
        hsm.refresh();
    }

    _hsm.putAll(_newConfig);
    _newConfig.clear();
}

From source file:org.jfrog.teamcity.agent.BaseBuildInfoExtractor.java

private void gatherBuildInfoParams(Map<String, String> allParamMap, Map propertyReceiver,
        final String propPrefix, final String... propTypes) {
    Map<String, String> filteredProperties = Maps.filterKeys(allParamMap, new Predicate<String>() {
        public boolean apply(String key) {
            if (StringUtils.isNotBlank(key)) {
                if (key.startsWith(propPrefix)) {
                    return true;
                }/*  w ww  .  jav  a 2 s . co m*/
                for (String propType : propTypes) {
                    if (key.startsWith(propType + propPrefix)) {
                        return true;
                    }
                }
            }
            return false;
        }
    });
    filteredProperties = Maps.filterValues(filteredProperties, new Predicate<String>() {
        public boolean apply(String value) {
            return StringUtils.isNotBlank(value);
        }
    });

    for (Map.Entry<String, String> entryToAdd : filteredProperties.entrySet()) {
        String key = entryToAdd.getKey();
        for (String propType : propTypes) {
            key = StringUtils.remove(key, propType);
        }
        key = StringUtils.remove(key, propPrefix);
        propertyReceiver.put(key, entryToAdd.getValue());
    }
}

From source file:org.apache.cassandra.cql.QueryProcessor.java

private static void validateSchemaAgreement() throws SchemaDisagreementException {
    // unreachable hosts don't count towards disagreement
    Map<String, List<String>> versions = Maps.filterKeys(StorageProxy.describeSchemaVersions(),
            Predicates.not(Predicates.equalTo(StorageProxy.UNREACHABLE)));
    if (versions.size() > 1)
        throw new SchemaDisagreementException();
}

From source file:com.palantir.atlasdb.transaction.impl.SerializableTransaction.java

private NavigableMap<Cell, byte[]> getReadsInRange(String table, Entry<RangeRequest, byte[]> e,
        RangeRequest range) {//w  w  w . j  a  v  a  2 s  .co  m
    NavigableMap<Cell, byte[]> reads = getReadsForTable(table);
    if (range.getStartInclusive().length != 0) {
        reads = reads.tailMap(Cells.createSmallestCellForRow(range.getStartInclusive()), true);
    }
    if (range.getEndExclusive().length != 0) {
        reads = reads.headMap(Cells.createSmallestCellForRow(range.getEndExclusive()), false);
    }
    ConcurrentNavigableMap<Cell, byte[]> writes = writesByTable.get(table);
    if (writes != null) {
        reads = Maps.filterKeys(reads, Predicates.not(Predicates.in(writes.keySet())));
    }
    return reads;
}

From source file:com.google.gwt.resources.rg.GssResourceGenerator.java

private Map<String, String> doClassRenaming(CssTree cssTree, JMethod method, TreeLogger logger,
        ResourceContext context) throws UnableToCompleteException {
    Map<String, Map<String, String>> replacementsWithPrefix = computeReplacements(method, logger, context);

    Set<String> externalClasses = collectExternalClasses(cssTree);

    RenamingSubstitutionMap substitutionMap = new RenamingSubstitutionMap(replacementsWithPrefix,
            externalClasses, isStrictResource(method), logger);

    new CssClassRenaming(cssTree.getMutatingVisitController(), substitutionMap, null).runPass();

    if (substitutionMap.hasError()) {
        throw new UnableToCompleteException();
    }/*from   w w w . j  av  a2  s  . co m*/

    Map<String, String> mapping = replacementsWithPrefix.get("");

    mapping = Maps.newHashMap(Maps.filterKeys(mapping, Predicates.in(substitutionMap.getStyleClasses())));

    // add external classes in the mapping
    for (String external : externalClasses) {
        mapping.put(external, external);
    }

    return mapping;
}

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

private void validateBuilders(BindingGraph subject, Builder<BindingGraph> reportBuilder) {
    ComponentDescriptor componentDesc = subject.componentDescriptor();
    if (!componentDesc.builderSpec().isPresent()) {
        // If no builder, nothing to validate.
        return;/*from w  w w  .j  a  v a 2  s  .  c  om*/
    }

    Set<TypeElement> allDependents = Sets.union(
            Sets.union(subject.transitiveModules().keySet(), componentDesc.dependencies()),
            componentDesc.executorDependency().asSet());
    Set<TypeElement> requiredDependents = Sets.filter(allDependents, new Predicate<TypeElement>() {
        @Override
        public boolean apply(TypeElement input) {
            return !Util.componentCanMakeNewInstances(input);
        }
    });
    final BuilderSpec spec = componentDesc.builderSpec().get();
    Map<TypeElement, ExecutableElement> allSetters = spec.methodMap();

    ErrorMessages.ComponentBuilderMessages msgs = ErrorMessages
            .builderMsgsFor(subject.componentDescriptor().kind());
    Set<TypeElement> extraSetters = Sets.difference(allSetters.keySet(), allDependents);
    if (!extraSetters.isEmpty()) {
        Collection<ExecutableElement> excessMethods = Maps.filterKeys(allSetters, Predicates.in(extraSetters))
                .values();
        Iterable<String> formatted = FluentIterable.from(excessMethods)
                .transform(new Function<ExecutableElement, String>() {
                    @Override
                    public String apply(ExecutableElement input) {
                        return methodSignatureFormatter.format(input,
                                Optional.of(MoreTypes.asDeclared(spec.builderDefinitionType().asType())));
                    }
                });
        reportBuilder.addItem(String.format(msgs.extraSetters(), formatted), spec.builderDefinitionType());
    }

    Set<TypeElement> missingSetters = Sets.difference(requiredDependents, allSetters.keySet());
    if (!missingSetters.isEmpty()) {
        reportBuilder.addItem(String.format(msgs.missingSetters(), missingSetters),
                spec.builderDefinitionType());
    }
}

From source file:org.apache.ambari.server.controller.internal.BlueprintConfigurationProcessor.java

/**
 * Drop every configuration property from advised configuration that is not found in the stack defaults.
 * @param advisedConfigurations advised configuration instance
 */// w w w.j  a  va2s. c om
private void doFilterStackDefaults(Map<String, AdvisedConfiguration> advisedConfigurations) {
    Blueprint blueprint = clusterTopology.getBlueprint();
    Configuration stackDefaults = blueprint.getStack().getConfiguration(blueprint.getServices());
    Map<String, Map<String, String>> stackDefaultProps = stackDefaults.getProperties();
    for (Map.Entry<String, AdvisedConfiguration> adConfEntry : advisedConfigurations.entrySet()) {
        AdvisedConfiguration advisedConfiguration = adConfEntry.getValue();
        if (stackDefaultProps.containsKey(adConfEntry.getKey())) {
            Map<String, String> defaultProps = stackDefaultProps.get(adConfEntry.getKey());
            Map<String, String> outFilteredProps = Maps.filterKeys(advisedConfiguration.getProperties(),
                    Predicates.not(Predicates.in(defaultProps.keySet())));
            advisedConfiguration.getProperties().keySet()
                    .removeAll(Sets.newCopyOnWriteArraySet(outFilteredProps.keySet()));

            if (advisedConfiguration.getPropertyValueAttributes() != null) {
                Map<String, ValueAttributesInfo> outFilteredValueAttrs = Maps.filterKeys(
                        advisedConfiguration.getPropertyValueAttributes(),
                        Predicates.not(Predicates.in(defaultProps.keySet())));
                advisedConfiguration.getPropertyValueAttributes().keySet()
                        .removeAll(Sets.newCopyOnWriteArraySet(outFilteredValueAttrs.keySet()));
            }
        } else {
            advisedConfiguration.getProperties().clear();
        }
    }
}

From source file:org.apache.impala.catalog.HdfsPartition.java

/**
 * Returns hmsParameters_ after filtering out all the partition
 * incremental stats information.//from www .j  ava2s . c  om
 */
private Map<String, String> getFilteredHmsParameters() {
    return Maps.filterKeys(hmsParameters_, isIncrementalStatsKey);
}

From source file:heros.solver.IDESolver.java

/**
 * Returns the resulting environment for the given statement.
 * The artificial zero value is automatically stripped.
 *///from  w  w w.  j  a  v  a  2 s.  co  m
public Map<D, V> resultsAt(N stmt) {
    //filter out the artificial zero-value
    return Maps.filterKeys(val.row(stmt), new Predicate<D>() {

        public boolean apply(D val) {
            return val != zeroValue;
        }
    });
}

From source file:com.facebook.buck.config.BuckConfig.java

public ImmutableMap<String, ImmutableMap<String, String>> getRawConfigForParser() {
    ImmutableMap<String, ImmutableMap<String, String>> rawSections = config.getSectionToEntries();

    // If the raw config doesn't have sections which have ignored fields, then just return it as-is.
    ImmutableSet<String> sectionsWithIgnoredFields = IGNORE_FIELDS_FOR_DAEMON_RESTART.keySet();
    if (Sets.intersection(rawSections.keySet(), sectionsWithIgnoredFields).isEmpty()) {
        return rawSections;
    }/* w  w  w.ja  v  a  2s .c  o m*/

    // Otherwise, iterate through the config to do finer-grain filtering.
    ImmutableMap.Builder<String, ImmutableMap<String, String>> filtered = ImmutableMap.builder();
    for (Map.Entry<String, ImmutableMap<String, String>> sectionEnt : rawSections.entrySet()) {
        String sectionName = sectionEnt.getKey();

        // If this section doesn't have a corresponding ignored section, then just add it as-is.
        if (!sectionsWithIgnoredFields.contains(sectionName)) {
            filtered.put(sectionEnt);
            continue;
        }

        // If none of this section's entries are ignored, then add it as-is.
        ImmutableMap<String, String> fields = sectionEnt.getValue();
        ImmutableSet<String> ignoredFieldNames = IGNORE_FIELDS_FOR_DAEMON_RESTART.getOrDefault(sectionName,
                ImmutableSet.of());
        if (Sets.intersection(fields.keySet(), ignoredFieldNames).isEmpty()) {
            filtered.put(sectionEnt);
            continue;
        }

        // Otherwise, filter out the ignored fields.
        ImmutableMap<String, String> remainingKeys = ImmutableMap
                .copyOf(Maps.filterKeys(fields, Predicates.not(ignoredFieldNames::contains)));

        if (!remainingKeys.isEmpty()) {
            filtered.put(sectionName, remainingKeys);
        }
    }

    return filtered.build();
}