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

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

Introduction

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

Prototype

@CheckReturnValue
public static <K, V> BiMap<K, V> filterEntries(BiMap<K, V> unfiltered,
        Predicate<? super Entry<K, V>> entryPredicate) 

Source Link

Document

Returns a bimap containing the mappings in unfiltered that satisfy a predicate.

Usage

From source file:org.jpmml.evaluator.scorecard.ScorecardEvaluator.java

static private ReasonCodeRanking createReasonCodeList(Map<String, Double> reasonCodes, Object value) {
    com.google.common.base.Predicate<Map.Entry<String, Double>> predicate = new com.google.common.base.Predicate<Map.Entry<String, Double>>() {

        @Override/*from   ww  w .  j  a  va2 s  . co m*/
        public boolean apply(Map.Entry<String, Double> entry) {
            return Double.compare(entry.getValue(), 0) >= 0;
        }
    };

    Map<String, Double> meaningfulReasonCodes = Maps.filterEntries(reasonCodes, predicate);

    ReasonCodeRanking result = new ReasonCodeRanking(value, meaningfulReasonCodes);

    return result;
}

From source file:org.openengsb.core.services.internal.deployer.connector.ConnectorFile.java

private ImmutableMap<String, String> getFilteredEntries(Map<String, String> propertyMap, final String prefix) {
    @SuppressWarnings("unchecked")
    Map<String, String> transformedMap = MapUtils.transformedMap(new HashMap<String, String>(),
            new Transformer() {
                @Override/*from w w  w. ja v a  2  s  .  c om*/
                public Object transform(Object input) {
                    return ((String) input).replaceFirst(prefix + ".", "");
                }
            }, null);
    Map<String, String> filterEntries = Maps.filterEntries(propertyMap,
            new Predicate<Map.Entry<String, String>>() {
                @Override
                public boolean apply(Entry<String, String> input) {
                    return input.getKey().startsWith(prefix + ".");
                }
            });
    transformedMap.putAll(filterEntries);
    return ImmutableMap.copyOf(transformedMap);
}

From source file:org.eclipse.sirius.diagram.ui.tools.internal.layout.provider.PinnedElementsLayoutProvider.java

private void handlePinnedElements(final Collection<IGraphicalEditPart> editParts,
        final Map<IGraphicalEditPart, Rectangle> initialBounds, final CompoundCommand cmd,
        ArrayList<IDiagramElementEditPart> elementstToKeepFixed) {
    /*/*ww  w . j  av a2  s. co m*/
     * Depth-first recursion on containers.
     */
    for (IGraphicalEditPart part : editParts) {
        final Collection<IGraphicalEditPart> children = getChildrenOfInterest(part);
        if (!children.isEmpty()) {
            handlePinnedElements(children, initialBounds, cmd, elementstToKeepFixed);
        }
    }
    /*
     * Base case: handle pinned elements at this particular level.
     */
    final Map<IGraphicalEditPart, Rectangle> initialBoundsForThisLevel = Maps.filterEntries(initialBounds,
            new Predicate<Map.Entry<IGraphicalEditPart, Rectangle>>() {
                public boolean apply(final Entry<IGraphicalEditPart, Rectangle> input) {
                    return editParts.contains(input.getKey());
                }
            });
    final PinnedElementsHandler handler = new PinnedElementsHandler(editParts, initialBoundsForThisLevel,
            elementstToKeepFixed);
    final Map<IGraphicalEditPart, Point> newPositions = handler.computeSolution();
    for (Entry<IGraphicalEditPart, Point> entry : newPositions.entrySet()) {
        final IGraphicalEditPart part = entry.getKey();
        final Point position = entry.getValue();
        final Command cbc = createChangeBoundsCommand(part, position);
        cmd.add(cbc);
    }
}

From source file:org.gradle.api.tasks.scala.ScalaCompile.java

private HashMap<File, File> filterForClasspath(Map<File, File> analysisMap, Iterable<File> classpath) {
    final Set<File> classpathLookup = Sets.newHashSet(classpath);
    return Maps.newHashMap(Maps.filterEntries(analysisMap, new Predicate<Map.Entry<File, File>>() {
        public boolean apply(Map.Entry<File, File> entry) {
            return classpathLookup.contains(entry.getKey());
        }/*ww  w. j  a  va 2  s. com*/
    }));
}

From source file:io.flood.registry.zk.ZookeeperRegistry.java

@Override
public void subscribe(final String name, final String group, final NotifyListener listener) {
    try {//from  ww w .  ja  v  a 2  s . c  om
        String serviceDir = Paths.get(name, group);
        client.getChildren().usingWatcher(new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                switch (watchedEvent.getType()) {
                case NodeChildrenChanged: {

                    try {
                        final List<String> nodes = client.getChildren().forPath(serviceDir);
                        List<Resource> services = Lists.newArrayListWithCapacity(nodes.size());
                        String servicePath = null;
                        for (String node : nodes) {
                            servicePath = Paths.get(name, group, node);
                            byte[] buffer = client.getData().forPath(servicePath);
                            Resource resource = GsonFactory.fromJson(buffer, Resource.class);
                            if (!localService.containsKey(servicePath)) {
                                LOG.info("new serice {},{}", servicePath, resource);
                                listener.notifyResourceCreated(resource);
                                subscribeRealService(resource, listener);
                                localService.put(servicePath, resource);
                            }
                        }

                        Maps.filterEntries(localService, entry -> {
                            if (nodes.contains(entry.getKey())) {
                                return true;
                            }
                            listener.notifyResourceDeleted(entry.getValue());
                            return false;
                        });
                    } catch (Exception e) {
                        LOG.warn("node child changed ,but process error ", e);
                    }

                }
                }
            }
        }).forPath(Paths.get(name, group));
        LOG.info("subscribe {}", Paths.get(name, group));
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.sonar.server.issue.IssueFilterService.java

public String serializeFilterQuery(Map<String, Object> filterQuery) {
    Map<String, Object> filterQueryFiltered = Maps.filterEntries(filterQuery,
            new Predicate<Map.Entry<String, Object>>() {
                @Override/*from   w  w w.  j a  va 2s  . c o  m*/
                public boolean apply(Map.Entry<String, Object> input) {
                    return IssueFilterParameters.ALL_WITHOUT_PAGINATION.contains(input.getKey());
                }
            });
    return serializer.serialize(filterQueryFiltered);
}

From source file:org.sonar.server.issue.filter.IssueFilterService.java

public String serializeFilterQuery(Map<String, Object> filterQuery) {
    Map<String, Object> filterQueryFiltered = Maps.filterEntries(filterQuery,
            MatchIssueFilterParameters.INSTANCE);
    return serializer.serialize(filterQueryFiltered);
}

From source file:com.google.jenkins.flakyTestHandler.plugin.HistoryAggregatedFlakyTestResultAction.java

/**
 * Get filtered tests to display on the project page. Users can decide whether to show all tests
 * or just flaky tests//from  w w  w.  j a  v a 2 s  . co m
 *
 * @return the filtered tests
 */
public Map<String, SingleTestFlakyStats> getFilteredAggregatedFlakyStats() {
    Predicate<Entry<String, SingleTestFlakyStats>> flakyTestsFilter;
    if (onlyShowFlakyTests) {
        flakyTestsFilter = new Predicate<Entry<String, SingleTestFlakyStats>>() {
            @Override
            public boolean apply(Entry<String, SingleTestFlakyStats> singleTestFlakyStatsEntry) {
                return singleTestFlakyStatsEntry.getValue().getFlake() > 0;
            }
        };
    } else {
        flakyTestsFilter = Predicates.alwaysTrue();
    }
    return Maps.filterEntries(aggregatedFlakyStats, flakyTestsFilter);
}

From source file:org.opentestsystem.authoring.testauth.validation.ScoringRuleParameterValidator.java

/**
 * validate dictionary values//from  w  ww. j a  v a  2 s . co m
 */
private <N extends Number> void validateDictionaryValues(
        final ComputationRuleParameter computationRuleParameter,
        final List<ScoringRuleDictionaryElement> dictionaryValues, final Errors errors) {
    final ComputationRuleType fieldType = computationRuleParameter.getComputationRuleType();
    final String paramName = computationRuleParameter.getParameterName();
    if (CollectionUtils.isEmpty(dictionaryValues)) {
        rejectValue(errors, DICTIONARY, getErrorMessageRoot() + DICTIONARY + MSG_REQUIRED, fieldType,
                paramName);
    }

    final Map<String, Collection<ScoringRuleDictionaryElement>> duplicates = Maps.filterEntries(
            Multimaps.index(dictionaryValues, DICTIONARY_ELEMENT_TO_KEY_TRANSFORMER).asMap(),
            KEY_DUPLICATE_FILTER);
    if (!duplicates.isEmpty()) {
        rejectValue(errors, DICTIONARY, getErrorMessageRoot() + DICTIONARY + MSG_DUPLICATES, paramName,
                duplicates.keySet().toString());
    }

    for (int i = 0; i < dictionaryValues.size(); i++) {
        final ScoringRuleDictionaryElement scoringRuleDictionaryElement = dictionaryValues.get(i);
        String key = scoringRuleDictionaryElement.getKey();
        final String value = scoringRuleDictionaryElement.getValue();
        try {
            errors.pushNestedPath(DICTIONARY + "[" + i + "]");

            final DictionaryIndexType dictionaryIndex = computationRuleParameter.getDictionaryIndexType();

            final boolean indexIsInteger = dictionaryIndex == DictionaryIndexType.INTEGER;
            if (!rejectIfEmpty(key, errors, KEY, getErrorMessageRoot() + DICTIONARY_KEY,
                    indexIsInteger ? MAX_PARSEABLE_LENGTH : MAX_STRING_LENGTH, fieldType, paramName, i + 1)
                    && indexIsInteger) {
                if (!StringUtils.isNumeric(key)) {
                    rejectValue(errors, KEY, getErrorMessageRoot() + DICTIONARY_KEY + MSG_INVALID, fieldType,
                            paramName, key, dictionaryIndex);
                }
            }

            key = StringUtils.defaultIfBlank(key, String.valueOf(i + 1));

            final boolean valueIsNumeric = NUMERIC_TYPES.contains(fieldType);
            if (!rejectIfEmpty(value, errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE,
                    valueIsNumeric ? MAX_PARSEABLE_LENGTH : MAX_STRING_LENGTH, fieldType, paramName, key)
                    && valueIsNumeric) {
                final String min = computationRuleParameter.getMinimumValue();
                final String max = computationRuleParameter.getMaximumValue();
                try {
                    if (fieldType == ComputationRuleType.FLOAT) {
                        final Float floatValue = Float.parseFloat(value);
                        final Range<Float> floatRange = buildFloatRange(min, max);
                        if (floatRange != null && !floatRange.contains(floatValue)) {
                            rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_RANGE,
                                    fieldType, paramName, key, min, max);
                        }
                    } else {
                        final Long longValue = Long.parseLong(value);
                        final Range<Long> longRange = buildLongRange(min, max);
                        if (longRange != null && !longRange.contains(longValue)) {
                            rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_RANGE,
                                    fieldType, paramName, key, min, max);
                        }
                    }
                } catch (final NumberFormatException e) {
                    rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_PARSEABLE_NUMBER,
                            fieldType, paramName, key, value);
                }
            } else if (ComputationRuleType.BOOLEAN.equals(fieldType)
                    && !Boolean.FALSE.toString().equals(value.toString())
                    && !Boolean.TRUE.toString().equals(value.toString())) {
                rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_PARSEABLE_BOOLEAN,
                        fieldType, paramName, key, value);
            }
        } finally {
            errors.popNestedPath();
        }
    }
}

From source file:org.opentestsystem.authoring.testauth.validation.ItemSelectionAlgorithmParameterValidator.java

@Override
public void validate(final Object obj, final Errors e) {
    final ItemSelectionAlgorithmParameter parameter = (ItemSelectionAlgorithmParameter) obj;

    if (parameter.getItemSelectionType() != null) {
        final Object[] errorArgs = new String[] { parameter.getItemSelectionType().name(),
                parameter.getParameterName() };

        switch (parameter.getItemSelectionType()) {
        case FLOAT:
        case INTEGER:
            // defaultValue validated via jsr-303
            rejectIfTooLong(e, DEFAULT_FIELD, MAX_PARSEABLE_LENGTH, errorArgs);

            final boolean isFloat = parameter.getItemSelectionType() == ItemSelectionType.FLOAT;
            rejectIfNotFloatOrIntegerParseable(e, DEFAULT_FIELD, isFloat, errorArgs);
            rejectIfNotFloatOrIntegerParseable(e, MINIMUM_FIELD, isFloat, errorArgs);
            rejectIfNotFloatOrIntegerParseable(e, MAXIMUM_FIELD, isFloat, errorArgs);
            if (!e.hasErrors()) {
                boolean compareDefaultToMinMax = true;
                if (StringUtils.isNotBlank(parameter.getMinimumValue())
                        && StringUtils.isNotBlank(parameter.getMaximumValue())) {
                    final BigDecimal minimumBigDecimal = new BigDecimal(parameter.getMinimumValue());
                    final BigDecimal maximumBigDecimal = new BigDecimal(parameter.getMaximumValue());
                    if (minimumBigDecimal.compareTo(maximumBigDecimal) > -1) {
                        rejectValue(e, MINIMUM_FIELD, getErrorMessageRoot() + MINIMUM_FIELD + MSG_LESS_THAN_MAX,
                                errorArgs);
                        compareDefaultToMinMax = false;
                    }// w w w .  j  ava2  s .  co  m
                }
                if (StringUtils.isNotBlank(parameter.getDefaultValue())) {
                    final BigDecimal defaultBigDecimal = new BigDecimal(parameter.getDefaultValue());
                    if (StringUtils.isNotBlank(parameter.getMinimumValue())) {
                        final BigDecimal minimumBigDecimal = new BigDecimal(parameter.getMinimumValue());
                        if (compareDefaultToMinMax && defaultBigDecimal.compareTo(minimumBigDecimal) < 0) {
                            rejectValue(e, DEFAULT_FIELD,
                                    getErrorMessageRoot() + DEFAULT_FIELD + MSG_WITHIN_MIN_MAX, errorArgs);
                        }
                    }
                    if (StringUtils.isNotBlank(parameter.getMaximumValue())) {
                        final BigDecimal maximumBigDecimal = new BigDecimal(parameter.getMaximumValue());
                        if (compareDefaultToMinMax && defaultBigDecimal.compareTo(maximumBigDecimal) > 0) {
                            rejectValue(e, DEFAULT_FIELD,
                                    getErrorMessageRoot() + DEFAULT_FIELD + MSG_WITHIN_MIN_MAX, errorArgs);
                        }
                    }
                }
            }
            rejectIfCollectionNotEmpty(e, ITEM_LIST_FIELD, errorArgs);
            break;
        case BOOLEAN:
            rejectIfNotEmpty(e, MINIMUM_FIELD, errorArgs);
            rejectIfNotEmpty(e, MAXIMUM_FIELD, errorArgs);
            rejectIfNotBooleanParseable(e, DEFAULT_FIELD, errorArgs);
            rejectIfCollectionNotEmpty(e, ITEM_LIST_FIELD, errorArgs);
            break;
        case LIST:
            rejectIfNotEmpty(e, MINIMUM_FIELD, errorArgs);
            rejectIfNotEmpty(e, MAXIMUM_FIELD, errorArgs);
            rejectIfCollectionEmpty(e, ITEM_LIST_FIELD, errorArgs);

            if (parameter.getItemSelectionList() != null) {
                if (Iterables.any(parameter.getItemSelectionList(), ITEM_SELECTION_PARAMETER_ELEMENT_BLANK)) {
                    rejectValue(e, ITEM_LIST_FIELD, getErrorMessageRoot() + ITEM_LIST_NAME_FIELD + MSG_REQUIRED,
                            errorArgs);
                }
                // check if defaultValue is one of values in selection list
                rejectIfNotInCollection(e, DEFAULT_FIELD, Lists.transform(parameter.getItemSelectionList(),
                        ITEM_SELECTION_PARAMETER_ELEMENT_TO_NAME_TRANSFORMER), errorArgs);

                // check if list has duplicate names and duplicate or out-of-range positions
                final Map<String, Collection<ItemSelectionParameterElement>> duplicates = Maps.filterEntries(
                        Multimaps.index(parameter.getItemSelectionList(),
                                ITEM_SELECTION_PARAMETER_ELEMENT_TO_NAME_TRANSFORMER).asMap(),
                        ITEM_SELECTION_PARAMETER_ELEMENT_DUPLICATE_FILTER);
                if (!duplicates.isEmpty()) {
                    rejectValue(e, ITEM_LIST_FIELD,
                            getErrorMessageRoot() + ITEM_LIST_NAME_FIELD + MSG_DUPLICATES,
                            duplicates.keySet().toString());
                }
                final Map<String, Collection<ItemSelectionParameterElement>> duplicatePositions = Maps
                        .filterEntries(
                                Multimaps
                                        .index(parameter.getItemSelectionList(),
                                                ITEM_SELECTION_PARAMETER_ELEMENT_TO_POSITION_TRANSFORMER)
                                        .asMap(),
                                ITEM_SELECTION_PARAMETER_ELEMENT_DUPLICATE_FILTER);
                if (!duplicatePositions.isEmpty()) {
                    rejectValue(e, ITEM_LIST_FIELD,
                            getErrorMessageRoot() + ITEM_LIST_POSITION_FIELD + MSG_DUPLICATES,
                            duplicatePositions.keySet().toString());
                }
                final List<String> outOfRange = Lists.newArrayList(Iterables.transform(
                        Iterables.filter(parameter.getItemSelectionList(),
                                PARAMETER_POSITION_OUT_OF_RANGE_FILTER
                                        .getInstance(parameter.getItemSelectionList().size())),
                        ITEM_SELECTION_PARAMETER_ELEMENT_TO_POSITION_TRANSFORMER));
                if (outOfRange.size() > 0) {
                    rejectValue(e, ITEM_LIST_FIELD,
                            getErrorMessageRoot() + ITEM_LIST_POSITION_FIELD + MSG_INVALID,
                            outOfRange.toString());
                }
            }
            break;
        case STRING:
            rejectIfNotEmpty(e, MINIMUM_FIELD, errorArgs);
            rejectIfNotEmpty(e, MAXIMUM_FIELD, errorArgs);
            rejectIfCollectionNotEmpty(e, ITEM_LIST_FIELD, errorArgs);
            rejectIfTooLong(e, DEFAULT_FIELD, MAXIMUM_DEFAULT_STRING_LENGTH, errorArgs);
            break;
        default:
            rejectValue(e, ITEM_TYPE_FIELD, getErrorMessageRoot() + ITEM_TYPE_FIELD + MSG_INVALID, errorArgs);
            break;
        }
    }
}