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:com.facebook.presto.mysql.MySQLSplitManager.java

@Override
public PartitionResult getPartitions(TableHandle tableHandle, TupleDomain tupleDomain) {
    checkNotNull(tableHandle, "tableHandle is null");
    checkNotNull(tupleDomain, "tupleDomain is null");

    if (this.connector.equalsIgnoreCase("mysql")) {
        return new PartitionResult(ImmutableList.of((Partition) MySQLPartition.UNPARTITIONED), tupleDomain);
    }//from  w  ww.  j  av  a2 s. co m

    MySQLTableHandle mySQLTableHandle = (MySQLTableHandle) tableHandle;

    MySQLTable table = schemaProvider.getTable(mySQLTableHandle);

    //List<MySQLColumnHandle> partitionKeys = table.getPartitionKeyColumns();
    //        List<Comparable<?>> filterPrefix = new ArrayList<>();
    //        for (int i = 0; i < partitionKeys.size(); i++) {
    //            MySQLColumnHandle columnHandle = partitionKeys.get(i);
    //
    //            // only add to prefix if all previous keys have a value
    //            if (filterPrefix.size() == i && !tupleDomain.isNone()) {
    //                Domain domain = tupleDomain.getDomains().get(columnHandle);
    //                if (domain != null && domain.getRanges().getRangeCount() == 1) {
    //                    // We intentionally ignore whether NULL is in the domain since partition keys can never be NULL
    //                    Range range = Iterables.getOnlyElement(domain.getRanges());
    //                    if (range.isSingleValue()) {
    //                        Comparable<?> value = range.getLow().getValue();
    //                        checkArgument(value instanceof Boolean || value instanceof String || value instanceof Double || value instanceof Long,
    //                                "Only Boolean, String, Double and Long partition keys are supported");
    //                        filterPrefix.add(value);
    //                    }
    //                }
    //            }
    //        }

    HashMap<ColumnHandle, Comparable<?>> map = new HashMap<>();
    ImmutableList.Builder<MySQLPartition> partitionBuilder = ImmutableList.builder();

    List<ColumnHandle> columns = new ArrayList<ColumnHandle>();
    StringBuilder stringBuilder = new StringBuilder();
    int i = 0;
    for (Map.Entry<ColumnHandle, Domain> entry : tupleDomain.getDomains().entrySet()) {
        Domain domain = entry.getValue();

        if (domain != null && domain.getRanges().getRangeCount() == 1) {
            Range range = Iterables.getOnlyElement(domain.getRanges());
            MySQLColumnHandle columnHandle = (MySQLColumnHandle) entry.getKey();
            if (!range.isSingleValue()) {
                continue;
            }

            Comparable<?> value = range.getLow().getValue();
            checkArgument(
                    value instanceof Boolean || value instanceof String || value instanceof Double
                            || value instanceof Long,
                    "Only Boolean, String, Double and Long partition keys are supported");

            columns.add(columnHandle);

            map.put(columnHandle, value);
            if (i > 0) {
                stringBuilder.append(" AND ");
            }
            stringBuilder.append(MySQLUtils.validColumnName(columnHandle.getName()));
            stringBuilder.append(" = ");
            stringBuilder
                    .append(MYSQLType.getMySQLColumnStringValue(value.toString(), columnHandle.getMySQLType()));
            i++;
        }
    }

    if (stringBuilder.length() > 0) {
        TupleDomain tuple = TupleDomain.withFixedValues(map);
        String partitionId = stringBuilder.toString();
        partitionBuilder.add(new MySQLPartition(partitionId, tuple));
    } else {
        partitionBuilder.add(MySQLPartition.UNPARTITIONED);
    }

    List<MySQLPartition> allPartitions = partitionBuilder.build();

    log.debug("%s.%s #partitions: %d", mySQLTableHandle.getSchemaName(), mySQLTableHandle.getTableName(),
            allPartitions.size());

    // do a final pass to filter based on fields that could not be used to build the prefix
    //        List<Partition> partitions = FluentIterable.from(allPartitions)
    //                .filter(partitionMatches(tupleDomain))
    //                .filter(P artition.class)
    //                .toList();

    List<Partition> partitions = FluentIterable.from(allPartitions).filter(Partition.class).toList();

    // All partition key domains will be fully evaluated, so we don't need to include those
    TupleDomain remainingTupleDomain = TupleDomain.none();
    if (!tupleDomain.isNone()) {
        remainingTupleDomain = TupleDomain
                .withColumnDomains(Maps.filterKeys(tupleDomain.getDomains(), not(in(columns))));
    }

    return new PartitionResult(partitions, remainingTupleDomain);
}

From source file:clocker.docker.location.DockerContainerLocation.java

@Override
public int execScript(Map<String, ?> props, String summaryForLogging, List<String> commands,
        Map<String, ?> env) {
    Iterable<String> filtered = Iterables.filter(commands, DockerCallbacks.FILTER);
    for (String commandString : filtered) {
        parseDockerCallback(commandString);
    }/*from w  w  w  . ja va  2s  .c o  m*/
    boolean entitySsh = Boolean.TRUE.equals(entity.config().get(DockerContainer.DOCKER_USE_SSH));
    boolean dockerSsh = Boolean.TRUE.equals(getOwner().config().get(DockerContainer.DOCKER_USE_SSH));
    if (entitySsh && dockerSsh) {
        return super.execScript(props, summaryForLogging, commands, env);
    } else {
        Map<String, ?> nonPortProps = Maps.filterKeys(props,
                Predicates.not(Predicates.containsPattern("port")));
        return hostMachine.execCommands(nonPortProps, summaryForLogging, getDockerExecCommand(commands, env));
    }
}

From source file:no.ssb.vtl.script.operations.join.AbstractJoinOperation.java

@Deprecated
private Comparator<Map<Component, VTLObject>> createKeyComparator(Dataset rightDataset, Order order) {

    // Only check the values of the common identifiers.

    HashSet<Component> commonComponents = Sets.newHashSet(getCommonIdentifiers());
    final Map<Component, Order.Direction> commonOrder = Maps.filterKeys(order, commonComponents::contains);
    final Table<Component, Dataset, Component> componentMap = getComponentMapping();
    return (left, right) -> {

        if (left == null)
            return -1;
        if (right == null)
            return 1;
        if (left == right)
            return 0;

        int result;
        for (Map.Entry<Component, Order.Direction> entry : commonOrder.entrySet()) {
            Component component = entry.getKey();
            Order.Direction direction = entry.getValue();

            Map<Dataset, Component> map = componentMap.row(component);

            Component leftComponent = component; // kept for clarity
            Component rightComponent = map.get(rightDataset);

            VTLObject leftValue = left.get(leftComponent);
            VTLObject rightValue = right.get(rightComponent);

            result = Order.NULLS_FIRST.compare(leftValue, rightValue);

            if (result != 0)
                return direction == ASC ? result : -1 * result;

        }/*from  w ww  .ja v  a  2  s.  co  m*/
        return 0;
    };
}

From source file:com.google.caliper.runner.CaliperRun.java

private static Collection<BenchmarkMethod> chooseBenchmarkMethods(BenchmarkClass benchmarkClass,
        Instrument instrument, CaliperOptions options) throws InvalidBenchmarkException {
    ImmutableMap<String, BenchmarkMethod> methodMap = benchmarkClass.findAllBenchmarkMethods(instrument);

    ImmutableSet<String> names = options.benchmarkMethodNames();

    // TODO(kevinb): this doesn't seem to prevent bogus names on cmd line yet
    return names.isEmpty() ? methodMap.values() : Maps.filterKeys(methodMap, Predicates.in(names)).values();
}

From source file:eu.lp0.cursus.scoring.scores.impl.GenericRaceLapsData.java

private Set<Pilot> filteredPilots(Race race) {
    ImmutableSet.Builder<Pilot> pilots = ImmutableSet.builder();
    for (RaceAttendee attendee : Maps.filterKeys(race.getAttendees(), Predicates.in(scores.getFleet()))
            .values()) {//from   w  ww. ja  va 2s  .c  o m
        if (attendee.getType() == RaceAttendee.Type.PILOT) {
            pilots.add(attendee.getPilot());
        }
    }
    return pilots.build();
}

From source file:com.romeikat.datamessie.core.rss.task.rssCrawling.SourceCrawler.java

private Map<String, SyndEntry> getEntriesToBeDownloaded(final HibernateSessionProvider sessionProvider,
        final long sourceId, final SyndFeed syndFeed) {
    final Map<String, SyndEntry> entriesPerUrl = getUniqueEntriesPerUrl(sourceId, syndFeed);

    // Filter URLs that should be downloaded
    final Predicate<String> shouldUrlBeDownloadedPredicate = new Predicate<String>() {
        @Override//from  w w w. ja  v a  2 s .  com
        public boolean apply(final String url) {
            return shouldUrlBeDownloaded(sessionProvider, sourceId, url);
        }
    };
    final Map<String, SyndEntry> syndEntriesPerUrlToBeDownloaded = Maps.filterKeys(entriesPerUrl,
            shouldUrlBeDownloadedPredicate);
    return Maps.newLinkedHashMap(syndEntriesPerUrlToBeDownloaded);
}

From source file:google.registry.testing.TaskQueueHelper.java

/**
 * Ensures that the only tasks in the named queue are exactly those that match the expected
 * matchers./* w w w . ja v  a 2  s . c om*/
 */
public static void assertTasksEnqueued(String queueName, List<TaskMatcher> taskMatchers) throws Exception {
    QueueStateInfo qsi = getQueueInfo(queueName);
    assertThat(qsi.getTaskInfo()).hasSize(taskMatchers.size());
    LinkedList<TaskStateInfo> taskInfos = new LinkedList<>(qsi.getTaskInfo());
    for (final TaskMatcher taskMatcher : taskMatchers) {
        try {
            taskInfos.remove(Iterables.find(taskInfos, taskMatcher));
        } catch (NoSuchElementException e) {
            final Map<String, Object> taskMatcherMap = taskMatcher.expected.toMap();
            assert_().fail("Task not found in queue %s:\n\n%s\n\nPotential candidate match diffs:\n\n%s",
                    queueName, taskMatcher,
                    FluentIterable.from(taskInfos).transform(new Function<TaskStateInfo, String>() {
                        @Override
                        public String apply(TaskStateInfo input) {
                            return prettyPrintEntityDeepDiff(taskMatcherMap, Maps.filterKeys(
                                    new MatchableTaskInfo(input).toMap(), in(taskMatcherMap.keySet())));
                        }
                    }).join(Joiner.on('\n')));
        }
    }
}

From source file:edu.udo.scaffoldhunter.model.dataimport.ImportJob.java

/**
 * @return the propertyMappings defined for this source. The
 *         sourceMergeByProperty is filtered out.
 *///  w  w  w.  j av a2 s. c o  m
public Map<String, SourcePropertyMapping> getPropertyMappings() {
    return Collections.unmodifiableMap(Maps.filterKeys(propertyMappings,
            not(getStringFilterPredicate(Collections.singleton(sourceMergeBy)))));
}

From source file:org.apache.brooklyn.location.jclouds.JCloudsPropertiesBuilder.java

public JCloudsPropertiesBuilder setCustomJcloudsProperties() {
    Map<String, Object> extra = Maps.filterKeys(conf.getAllConfig(), Predicates.containsPattern("^jclouds\\."));
    if (extra.size() > 0) {
        String provider = getProviderFromConfig(conf);
        LOG.debug("Configuring custom jclouds property overrides for {}: {}", provider,
                Sanitizer.sanitize(extra));
    }//from w  ww.  j av a 2  s  . c o m
    properties.putAll(Maps.filterValues(extra, Predicates.notNull()));
    return this;
}

From source file:no.ssb.jsonstat.v2.Dataset.java

/**
 * Return the dimensions of the dataset.
 *
 * @see Dimension//w ww  .j a va  2  s.c  om
 * @see <a href="https://json-stat.org/format/#dimension">json-stat.org/format/#dimension</a>
 */
@JsonIgnore
public Map<String, Dimension> getDimension(Collection<String> filter) {
    if (firstNonNull(filter, Collections.emptySet()).isEmpty())
        return Collections.emptyMap();

    return Maps.filterKeys(getDimension(), Predicates.in(filter));
}