Java Code Examples for com.google.common.collect.Maps#filterEntries()

The following examples show how to use com.google.common.collect.Maps#filterEntries() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PruneIndexSourceColumns.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
protected Optional<PlanNode> pushDownProjectOff(Context context, IndexSourceNode indexSourceNode, Set<Symbol> referencedOutputs)
{
    Set<Symbol> prunedLookupSymbols = indexSourceNode.getLookupSymbols().stream()
            .filter(referencedOutputs::contains)
            .collect(toImmutableSet());

    Map<Symbol, ColumnHandle> prunedAssignments = Maps.filterEntries(
            indexSourceNode.getAssignments(),
            entry -> referencedOutputs.contains(entry.getKey()));

    List<Symbol> prunedOutputList =
            indexSourceNode.getOutputSymbols().stream()
                    .filter(referencedOutputs::contains)
                    .collect(toImmutableList());

    return Optional.of(
            new IndexSourceNode(
                    indexSourceNode.getId(),
                    indexSourceNode.getIndexHandle(),
                    indexSourceNode.getTableHandle(),
                    prunedLookupSymbols,
                    prunedOutputList,
                    prunedAssignments));
}
 
Example 2
Source File: CountKeyOrValuesMap.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void filter_map_by_value_entries_guava() {

	Predicate<Map.Entry<Integer, String>> monthLenthFour = new Predicate<Map.Entry<Integer, String>>() {
		@Override
		public boolean apply(Entry<Integer, String> input) {
			return input.getValue().length() == 4;
		}
	};

	Map<Integer, String> monthsWithLengthFour = Maps.filterEntries(MONTHS,
			monthLenthFour);

	int count = monthsWithLengthFour.size();

	assertEquals(2, count);
}
 
Example 3
Source File: DomainFlowUtils.java    From nomulus with Apache License 2.0 6 votes vote down vote up
static void validateNoDuplicateContacts(Set<DesignatedContact> contacts)
    throws ParameterValuePolicyErrorException {
  ImmutableMultimap<Type, Key<ContactResource>> contactsByType =
      contacts.stream()
          .collect(
              toImmutableSetMultimap(
                  DesignatedContact::getType, contact -> contact.getContactKey().getOfyKey()));

  // If any contact type has multiple contacts:
  if (contactsByType.asMap().values().stream().anyMatch(v -> v.size() > 1)) {
    // Find the duplicates.
    Map<Type, Collection<Key<ContactResource>>> dupeKeysMap =
        Maps.filterEntries(contactsByType.asMap(), e -> e.getValue().size() > 1);
    ImmutableList<Key<ContactResource>> dupeKeys =
        dupeKeysMap.values().stream().flatMap(Collection::stream).collect(toImmutableList());
    // Load the duplicates in one batch.
    Map<Key<ContactResource>, ContactResource> dupeContacts = ofy().load().keys(dupeKeys);
    ImmutableMultimap.Builder<Type, Key<ContactResource>> typesMap =
        new ImmutableMultimap.Builder<>();
    dupeKeysMap.forEach(typesMap::putAll);
    // Create an error message showing the type and contact IDs of the duplicates.
    throw new DuplicateContactForRoleException(
        Multimaps.transformValues(typesMap.build(), key -> dupeContacts.get(key).getContactId()));
  }
}
 
Example 4
Source File: PatternsMatcher.java    From buck with Apache License 2.0 5 votes vote down vote up
/** @return a view of the given map where all non-matching keys are removed. */
public <V> Map<String, V> filterMatchingMapKeys(Map<String, V> entries) {
  if (matchesAny) {
    return entries;
  }

  return Maps.filterEntries(entries, entry -> matches(entry.getKey()));
}
 
Example 5
Source File: TestSearchApiController.java    From proctor with Apache License 2.0 5 votes vote down vote up
/**
 * API for proctor tests with filtering functionality
 *
 * @param branch           environment
 * @param limit            number of tests to return
 * @param q                query string to search
 * @param filterType       {@link FilterType}
 * @param filterActive     {@link FilterActive}
 * @param sort             {@link Sort}
 * @param favoriteTestsRaw comma-separated favorite tests saved in cookie
 * @return JSON of TestsResponse
 */
@ApiOperation(value = "Proctor tests with filters", response = List.class)
@GetMapping
public JsonView viewTestNames(
        @RequestParam(defaultValue = "trunk") final String branch,
        @RequestParam(defaultValue = "100") final int limit,
        @RequestParam(defaultValue = "") final String q,
        @RequestParam(defaultValue = "ALL") final FilterType filterType,
        @RequestParam(defaultValue = "ALL") final FilterActive filterActive,
        @RequestParam(defaultValue = "FAVORITESFIRST") final Sort sort,
        @CookieValue(value = "FavoriteTests", defaultValue = "") final String favoriteTestsRaw
) throws StoreException {
    final Set<String> favoriteTestNames = Sets.newHashSet(Splitter.on(",").split(favoriteTestsRaw));

    final Environment environment = determineEnvironmentFromParameter(branch);
    final TestMatrixDefinition testMatrixDefinition = getCurrentMatrix(environment).getTestMatrixDefinition();
    final Map<String, TestDefinition> allTestMatrix = testMatrixDefinition != null
            ? testMatrixDefinition.getTests()
            : Collections.emptyMap();

    final List<String> queries = Arrays.asList(q.split("\\s+"));
    final Map<String, TestDefinition> matchingTestMatrix = Maps.filterEntries(allTestMatrix,
            e -> e != null && matchesAllIgnoreCase(e.getKey(), e.getValue(), filterType, queries)
                    && matchesFilterActive(e.getValue().getAllocations(), filterActive)
    );

    final List<ProctorTest> searchResult =
            toProctorTests(matchingTestMatrix, determineStoreFromEnvironment(environment))
                    .stream()
                    .sorted(getComparator(sort, favoriteTestNames))
                    .limit(limit)
                    .collect(toList());

    return new JsonView(new TestsResponse(searchResult, allTestMatrix.size(), searchResult.size()));
}
 
Example 6
Source File: SlackAlarmCallbackTest.java    From graylog-plugin-slack with Apache License 2.0 5 votes vote down vote up
private Configuration validConfigurationWithout(final String key) {
    return new Configuration(Maps.filterEntries(VALID_CONFIG_SOURCE, new Predicate<Map.Entry<String, Object>>() {
        @Override
        public boolean apply(Map.Entry<String, Object> input) {
            return key.equals(input.getKey());
        }
    }));
}
 
Example 7
Source File: SlackMessageOutputTest.java    From graylog-plugin-slack with Apache License 2.0 5 votes vote down vote up
private Configuration validConfigurationWithout(final String key) {
    return new Configuration(Maps.filterEntries(VALID_CONFIG_SOURCE, new Predicate<Map.Entry<String, Object>>() {
        @Override
        public boolean apply(Map.Entry<String, Object> input) {
            return key.equals(input.getKey());
        }
    }));
}
 
Example 8
Source File: MapsExample.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Filter map by entries
 */
@Test
public void maps_filter_entries() {

	// create a map
	Map<String, State> statesKeyByCode = Maps.uniqueIndex(states,
			new Function<State, String>() {
				public String apply(State from) {
					return from.code;
				}
			});

	// predicate to filter states by region code
	Predicate<Entry<String, State>> byMDWStates = new Predicate<Map.Entry<String, State>>() {
		@Override
		public boolean apply(Entry<String, State> input) {
			return input.getValue().region.equals("MDW");
		}
	};

	// filter entries
	Map<String, State> midwestStates = Maps.filterEntries(statesKeyByCode,
			byMDWStates);

	logger.info(midwestStates);

	assertThat(midwestStates.keySet(), hasSize(4));
}
 
Example 9
Source File: JwtParserCallout.java    From iloveapis2015-jwt-jwe-jws with Apache License 2.0 5 votes vote down vote up
private Map<String, String> requiredClaimsProperties() {
    Predicate<Map.Entry<String, String>> p1 =
        new Predicate<Map.Entry<String, String>>() {
        @Override
        public boolean apply(Map.Entry<String, String> entry) {
            return entry.getKey().startsWith("claim_");
        }
    };
    Map<String, String> claimsProps = Maps.filterEntries(properties, p1);
    return claimsProps;
}
 
Example 10
Source File: JwtCreatorCallout.java    From iloveapis2015-jwt-jwe-jws with Apache License 2.0 5 votes vote down vote up
private Map<String, String> customClaimsProperties(final MessageContext msgCtxt) {
    Predicate<Map.Entry<String, String>> p1 =
        new Predicate<Map.Entry<String, String>>() {
        @Override
        public boolean apply(Map.Entry<String, String> entry) {
            boolean result = entry.getKey().startsWith("claim_");
            // diagnostics
            msgCtxt.setVariable("jwt_property_" + entry.getKey(), entry.getValue());
            return result;
        }
    };
    Map<String, String> claimsProps = Maps.filterEntries(properties, p1);
    return claimsProps;
}
 
Example 11
Source File: DefaultGroupEmailReceiver.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
private Map<ALERT_TYPE, Set<AlertEntity>> dbaAsReceiverAlerts(Map<ALERT_TYPE, Set<AlertEntity>> alerts) {
    Map<ALERT_TYPE, Set<AlertEntity>> filteredMap =  Maps.filterEntries(alerts, new Predicate<Map.Entry<ALERT_TYPE, Set<AlertEntity>>>() {
        @Override
        public boolean apply(Map.Entry<ALERT_TYPE, Set<AlertEntity>> input) {
            return dbaSensitive(input.getKey());
        }
    });
    return Maps.newHashMap(filteredMap);
}
 
Example 12
Source File: DefaultGroupEmailReceiver.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
private Map<ALERT_TYPE, Set<AlertEntity>> xpipeAdminAsReceiverAlerts(Map<ALERT_TYPE, Set<AlertEntity>> alerts) {
    Map<ALERT_TYPE, Set<AlertEntity>> filteredMap = Maps.filterEntries(alerts, new Predicate<Map.Entry<ALERT_TYPE, Set<AlertEntity>>>() {
        @Override
        public boolean apply(Map.Entry<ALERT_TYPE, Set<AlertEntity>> input) {
            return !dbaSensitive(input.getKey());
        }
    });
    return Maps.newHashMap(filteredMap);
}
 
Example 13
Source File: ProxyOrchestrationSchemaContexts.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, DataSource> getAddedDataSources(final SchemaContext oldSchemaContext, final Map<String, DataSourceConfiguration> newDataSources) throws Exception {
    Map<String, DataSourceParameter> newDataSourceParameters = DataSourceConverter.getDataSourceParameterMap(newDataSources);
    Map<String, DataSourceParameter> parameters = 
            Maps.filterEntries(newDataSourceParameters, input -> !oldSchemaContext.getSchema().getDataSourceParameters().containsKey(input.getKey()));
    return createDataSources(parameters);
}
 
Example 14
Source File: MoveTableTask.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter out) throws Exception {
    // Start table and facade moves as specified in query parameters.
    String srcPlacement = Iterables.getFirst(parameters.get("src"), null);
    String destPlacement = Iterables.getFirst(parameters.get("dest"), null);
    String movePlacement = Iterables.getFirst(parameters.get("placement"), null);
    Optional<Integer> numShards = parseNumShards(Iterables.getFirst(parameters.get("shards"), null));
    checkArgument(destPlacement == null || _tableDao.isMoveToThisPlacementAllowed(destPlacement),
            "Move to this placement is not allowed since it is currently on move.");
    moveTables(parameters.get("table"), destPlacement, numShards, out, MoveType.SINGLE_TABLE);
    moveFacades(parameters.get("facade"), srcPlacement, destPlacement, numShards, out, MoveType.SINGLE_TABLE);
    movePlacement(movePlacement, destPlacement, numShards, out);

    // Print currently scheduled table maintenance.
    boolean localOnly = Boolean.valueOf(Iterables.getFirst(parameters.get("localonly"), "false"));
    Map.Entry<String, MaintenanceOp> running = getLocallyRunningMaintenance();
    Map<String, MaintenanceOp> localMap = getLocallyScheduledMaintenance();
    Map<String, MaintenanceOp> remoteMap = Collections.emptyMap();
    if (!localOnly) {
        // Remote maintenance == ALL - LOCAL - RUNNING.
        remoteMap = Maps.filterEntries(
                Maps.difference(getGloballyScheduledMaintenance(), localMap).entriesOnlyOnLeft(),
                Predicates.not(Predicates.equalTo(running)));
    }
    if (running != null) {
        printMaintenance(running.getKey(), running.getValue(), "RUNNING", out);
    }
    printMaintenance(localMap, "LOCAL", out);
    printMaintenance(remoteMap, "REMOTE", out);
    if (running == null && localMap.isEmpty() && remoteMap.isEmpty()) {
        if (localOnly) {
            out.println("No local table maintenance is scheduled.");
        } else {
            out.println("No table maintenance is scheduled.");
        }
    }
}
 
Example 15
Source File: AbstractOrchestrationDataSource.java    From shardingsphere with Apache License 2.0 4 votes vote down vote up
private synchronized Map<String, DataSourceConfiguration> getAddedDataSources(final Map<String, DataSourceConfiguration> dataSourceConfigurations) {
    return Maps.filterEntries(dataSourceConfigurations, input -> !AbstractOrchestrationDataSource.this.dataSourceConfigurations.containsKey(input.getKey()));
}
 
Example 16
Source File: MemoryExperimentsCache.java    From alchemy with MIT License 4 votes vote down vote up
@Override
public Map<String, Experiment> getActiveExperiments() {
    final Map<String, Experiment> filtered = Maps.filterEntries(db, ACTIVE_FILTER);
    return Maps.transformEntries(filtered, EXPERIMENT_COPY_TRANSFORMER);
}
 
Example 17
Source File: SymlinkCache.java    From buck with Apache License 2.0 4 votes vote down vote up
public void registerInputsUnderSymlinks(
    Cell currentCell, Cell targetCell, AbsPath buildFile, TargetNode<?> node) throws IOException {
  Map<Path, Path> newSymlinksEncountered =
      inputFilesUnderSymlink(node.getInputs(), node.getFilesystem());
  Optional<ImmutableList<Path>> readOnlyPaths =
      targetCell.getBuckConfig().getView(ParserConfig.class).getReadOnlyPaths();

  if (readOnlyPaths.isPresent() && currentCell != null) {
    newSymlinksEncountered =
        Maps.filterEntries(
            newSymlinksEncountered,
            entry -> {
              for (Path readOnlyPath : readOnlyPaths.get()) {
                if (entry.getKey().startsWith(readOnlyPath)) {
                  LOG.debug(
                      "Target %s contains input files under a path which contains a symbolic "
                          + "link (%s). It will be cached because it belongs under %s, a "
                          + "read-only path white listed in .buckconfig. under [project] "
                          + "read_only_paths",
                      node.getBuildTarget(), entry, readOnlyPath);
                  return false;
                }
              }
              return true;
            });
  }

  if (newSymlinksEncountered.isEmpty()) {
    return;
  }

  ParserConfig.AllowSymlinks allowSymlinks =
      Objects.requireNonNull(cellSymlinkAllowability.get(node.getBuildTarget().getCell()));
  if (allowSymlinks == ParserConfig.AllowSymlinks.FORBID) {
    throw new HumanReadableException(
        "Target %s contains input files under a path which contains a symbolic link "
            + "(%s). To resolve this, use separate rules and declare dependencies instead of "
            + "using symbolic links.\n"
            + "If the symlink points to a read-only filesystem, you can specify it in the "
            + "project.read_only_paths .buckconfig setting. Buck will assume files under that "
            + "path will never change.",
        node.getBuildTarget(), newSymlinksEncountered);
  }

  // If we're not explicitly forbidding symlinks, either warn to the console or the log file
  // depending on the config setting.
  String msg =
      String.format(
          "Disabling parser cache for target %s, because one or more input files are under a "
              + "symbolic link (%s). This will severely impact the time spent in parsing! To "
              + "resolve this, use separate rules and declare dependencies instead of using "
              + "symbolic links.",
          node.getBuildTarget(), newSymlinksEncountered);
  if (allowSymlinks == ParserConfig.AllowSymlinks.WARN) {
    eventBus.post(ConsoleEvent.warning(msg));
  } else {
    LOG.warn(msg);
  }

  eventBus.post(ParsingEvent.symlinkInvalidation(buildFile.toString()));
  buildInputPathsUnderSymlink.add(buildFile);
}
 
Example 18
Source File: MapExtensions.java    From xtext-lib with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Replies the elements of the left map without the pairs in the right map.
 * If the pair's values differ from
 * the value within the map, the map entry is not removed.
 *
 * <p>
 * The difference is an immutable
 * snapshot of the state of the maps at the time this method is called. It
 * will never change, even if the maps change at a later time.
 * </p>
 *
 * <p>
 * Since this method uses {@code HashMap} instances internally, the keys of
 * the supplied maps must be well-behaved with respect to
 * {@link Object#equals} and {@link Object#hashCode}.
 * </p>
 *
 * @param <K> type of the map keys.
 * @param <V> type of the map values.
 * @param left the map to update.
 * @param right the pairs to remove.
 * @return the map with the content of the left map except the pairs of the right map.
 * @since 2.15
 */
@Pure
public static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Map<? extends K, ? extends V> right) {
	return Maps.filterEntries(left, new Predicate<Entry<K, V>>() {
		@Override
		public boolean apply(Entry<K, V> input) {
			final V value = right.get(input.getKey());
			if (value == null) {
				return input.getValue() == null && right.containsKey(input.getKey());
			}
			return !Objects.equal(input.getValue(), value);
		}
	});
}
 
Example 19
Source File: MapExtensions.java    From xtext-lib with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Remove the given pair from a given map for obtaining a new map.
 *
 * <p>
 * If the given key is inside the map, but is not mapped to the given value, the
 * map will not be changed.
 * </p>
 *
 * <p>
 * The replied map is a view on the given map. It means that any change
 * in the original map is reflected to the result of this operation.
 * </p>
 *
 * @param <K> type of the map keys.
 * @param <V> type of the map values.
 * @param left the map to consider.
 * @param right the entry (key, value) to remove from the map.
 * @return an immutable map with the content of the map and with the given entry.
 * @throws IllegalArgumentException - when the right operand key exists in the left operand.
 * @since 2.15
 */
@Pure
public static <K, V> Map<K, V> operator_minus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {
	return Maps.filterEntries(left, new Predicate<Entry<K, V>>() {
		@Override
		public boolean apply(Entry<K, V> input) {
			return !Objects.equal(input.getKey(), right.getKey()) || !Objects.equal(input.getValue(), right.getValue());
		}
	});
}
 
Example 20
Source File: MapExtensions.java    From xtext-lib with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * <p>
 * Returns a filtered live view on top of the original map. Changes to one affect the other.
 * </p>
 * 
 * <p>
 * The mapping is done lazily. That is, subsequent access of the values in the map will repeatedly apply the
 * transformation. Characteristics of the original map, such as iteration order, are left intact. Changes in the
 * original map are reflected in the result map. The results supports removal if the original map supports removal.
 * </p>
 * 
 * @param original
 *            the original map. May not be <code>null</code>.
 * @param predicate
 *            the predicate. May not be <code>null</code>.
 * @return a filtered view on top of the original map. Never <code>null</code>.
 */
public static <K, V> Map<K, V> filter(Map<K, V> original, final Function2<? super K, ? super V, Boolean> predicate) {
	if (predicate == null)
		throw new NullPointerException("predicate");
	return Maps.filterEntries(original, new Predicate<Map.Entry<K, V>>() {
		@Override
		public boolean apply(Map.Entry<K, V> input) {
			Boolean result = predicate.apply(input.getKey(), input.getValue());
			return result.booleanValue();
		}
	});
}