Example usage for com.google.common.collect Multimaps index

List of usage examples for com.google.common.collect Multimaps index

Introduction

In this page you can find the example usage for com.google.common.collect Multimaps index.

Prototype

public static <K, V> ImmutableListMultimap<K, V> index(Iterator<V> values, Function<? super V, K> keyFunction) 

Source Link

Document

Creates an index ImmutableListMultimap that contains the results of applying a specified function to each item in an Iterator of values.

Usage

From source file:org.restlet.ext.apispark.internal.agent.module.FirewallModule.java

private Map<Integer, java.util.Collection<FirewallRateLimit>> sortRateLimitsByPeriod(
        List<FirewallRateLimit> rateLimits) {

    ListMultimap<Integer, FirewallRateLimit> rateLimitsByPeriod = Multimaps.index(rateLimits,
            new Function<FirewallRateLimit, Integer>() {
                @Override//  w  w  w  .  ja  v a  2 s . c  om
                public Integer apply(FirewallRateLimit firewallRateLimit) {
                    return firewallRateLimit.getPeriod();
                }
            });
    return rateLimitsByPeriod.asMap();
}

From source file:io.github.jonestimd.swing.table.model.BeanListMultimapTableModel.java

public void setBeans(Collection<T> beans) {
    setBeans(Multimaps.index(beans, groupingFunction::apply));
}

From source file:org.sonarsource.sonarlint.core.container.standalone.rule.StandaloneActiveRulesProvider.java

private static Map<String, Collection<RulesProfile>> profilesByName(List<RulesProfile> profiles) {
    return Multimaps.index(profiles, profile -> profile != null ? profile.getName() : null).asMap();
}

From source file:io.github.guaidaodl.pomodorotimer.ui.statistics.StatisticsPresenter.java

private void loadStatistics() {
    final Pair<Long, Long> todayTimePair = DateUtils.getTodayTime();
    Subscription daySubscription = mTomatoRepository
            .getTomatoWithStartTimeBetween(todayTimePair.first, todayTimePair.second)
            .observeOn(mSchedulerProvider.ui()).subscribe(new Action1<List<Tomato>>() {
                @Override/*from  w w w  .  j  a  v a2 s.  c o  m*/
                public void call(List<Tomato> tomatos) {
                    mStatisticsView.showTodayTomatoCount(tomatos.size());
                }
            });
    mSubscriptions.add(daySubscription);

    Pair<Long, Long> weekTime = DateUtils.getCurrentWeekTime();
    Subscription weekSubscription = mTomatoRepository
            .getTomatoWithStartTimeBetween(weekTime.first, weekTime.second).observeOn(mSchedulerProvider.ui())
            .subscribe(new Action1<List<Tomato>>() {
                @Override
                public void call(List<Tomato> tomatos) {
                    mStatisticsView.showWeekTomatoCount(tomatos.size());
                }
            });
    mSubscriptions.add(weekSubscription);

    Pair<Long, Long> monthTime = DateUtils.getCurrentMonthTime();
    Subscription monthSubscription = mTomatoRepository
            .getTomatoWithStartTimeBetween(monthTime.first, monthTime.second).observeOn(mSchedulerProvider.ui())
            .subscribe(new Action1<List<Tomato>>() {
                @Override
                public void call(List<Tomato> tomatos) {
                    mStatisticsView.showMonthTomatoCount(tomatos.size());
                }
            });
    mSubscriptions.add(monthSubscription);

    final Pair<Long, Long> lastSevenDaysTime = DateUtils.getLastSevenDaysTime();
    Subscription lastSevenDaySubscription = mTomatoRepository
            .getTomatoWithStartTimeBetween(lastSevenDaysTime.first, lastSevenDaysTime.second)
            .subscribe(new Action1<List<Tomato>>() {
                @Override
                public void call(List<Tomato> tomatos) {
                    ImmutableListMultimap<Long, Tomato> index = Multimaps.index(tomatos,
                            new Function<Tomato, Long>() {
                                @Nullable
                                @Override
                                public Long apply(Tomato tomato) {
                                    return DateUtils.getStartOfDay(tomato.getStartTime()).getTimeInMillis();
                                }
                            });

                    mStatisticsView.showLastSevenDaysTomatoStatistics(index);
                }
            });
    mSubscriptions.add(lastSevenDaySubscription);
}

From source file:com.google.api.server.spi.config.jsonwriter.JsonConfigWriter.java

@Override
public Map<ApiKey, String> writeConfig(Iterable<? extends ApiConfig> configs) throws ApiConfigException {
    Multimap<ApiKey, ? extends ApiConfig> apisByKey = Multimaps.index(configs,
            new Function<ApiConfig, ApiKey>() {
                @Override//w w w .ja  v a  2s. c om
                public ApiKey apply(ApiConfig config) {
                    return config.getApiKey();
                }
            });

    // This *must* retain the order of apisByKey so the lily_java_api BUILD rule has predictable
    // output order.
    Map<ApiKey, String> results = Maps.newLinkedHashMap();
    for (ApiKey apiKey : apisByKey.keySet()) {
        Collection<? extends ApiConfig> apiConfigs = apisByKey.get(apiKey);
        validator.validate(apiConfigs);
        results.put(apiKey, generateForApi(apiConfigs));
    }
    return results;
}

From source file:org.apache.james.rrt.memory.MemoryRecipientRewriteTable.java

@Override
protected Map<String, Mappings> getAllMappingsInternal() throws RecipientRewriteTableException {
    if (mappingEntries.isEmpty()) {
        return null;
    }/* w  ww .j  ava2 s . com*/
    Map<String, Collection<Mappings>> userMappingsMap = Multimaps
            .transformEntries(Multimaps.index(mappingEntries, new Function<InMemoryMappingEntry, String>() {
                public String apply(InMemoryMappingEntry mappingEntry) {
                    return mappingEntry.asKey();
                }
            }), new Maps.EntryTransformer<String, InMemoryMappingEntry, Mappings>() {
                public Mappings transformEntry(String s, InMemoryMappingEntry mappingEntry) {
                    return MappingsImpl.fromRawString(mappingEntry.getMapping());
                }
            }).asMap();
    return Maps.transformEntries(userMappingsMap,
            new Maps.EntryTransformer<String, Collection<Mappings>, Mappings>() {
                public Mappings transformEntry(String s, Collection<Mappings> mappingsList) {
                    Mappings result = MappingsImpl.empty();
                    for (Mappings mappings : mappingsList) {
                        result = result.union(mappings);
                    }
                    return result;
                }
            });
}

From source file:eu.itesla_project.online.tools.RunSecurityRulesOnStateTool.java

@Override
public void run(CommandLine line) throws Exception {
    String workflowId = line.getOptionValue("workflow");
    Integer stateId = Integer.valueOf(line.getOptionValue("state"));
    System.out.println("loading state " + stateId + " of workflow " + workflowId + " from the online db ...");
    OnlineConfig config = OnlineConfig.load();
    OnlineDb onlinedb = config.getOnlineDbFactoryClass().newInstance().create();
    // load the network
    Network network = onlinedb.getState(workflowId, stateId);
    if (network != null) {
        OnlineWorkflowParameters parameters = onlinedb.getWorkflowParameters(workflowId);
        String offlineWorkflowId = parameters.getOfflineWorkflowId();
        if (line.hasOption("offline-workflow"))
            offlineWorkflowId = line.getOptionValue("offline-workflow");
        System.out.println("checking state " + stateId + " of workflow " + workflowId
                + " against rules of offline workflow " + offlineWorkflowId + " ...");
        RulesDbClient rulesDb = config.getRulesDbClientFactoryClass().newInstance().create("rulesdb");
        RuleAttributeSet attributeSet = RuleAttributeSet.MONTE_CARLO;
        if (line.hasOption("wca"))
            attributeSet = RuleAttributeSet.WORST_CASE;
        double purityThreshold = parameters.getRulesPurityThreshold();
        // get rules from db
        Collection<RuleId> ruleIds = rulesDb.listRules(offlineWorkflowId, attributeSet);
        // TODO filter rules that does not apply to the network
        // .../* ww w .  j a v  a2s.c  o  m*/
        // sort rules per contingency
        Multimap<String, RuleId> ruleIdsPerContingency = Multimaps.index(ruleIds,
                new Function<RuleId, String>() {
                    @Override
                    public String apply(RuleId ruleId) {
                        return ruleId.getSecurityIndexId().getContingencyId();
                    }
                });
        Map<HistoDbAttributeId, Object> values = IIDM2DB
                .extractCimValues(network, new IIDM2DB.Config(null, false)).getSingleValueMap();
        SecurityIndexType[] securityIndexTypes = parameters.getSecurityIndexes() == null
                ? SecurityIndexType.values()
                : parameters.getSecurityIndexes()
                        .toArray(new SecurityIndexType[parameters.getSecurityIndexes().size()]);
        Table table = new Table(1 + securityIndexTypes.length, BorderStyle.CLASSIC_WIDE);
        table.addCell("Contingency");
        for (SecurityIndexType securityIndexType : securityIndexTypes) {
            table.addCell(securityIndexType.toString());
        }
        // check rules
        for (Map.Entry<String, Collection<RuleId>> entry : ruleIdsPerContingency.asMap().entrySet()) {
            String contingencyId = entry.getKey();
            table.addCell(contingencyId);
            Map<SecurityIndexType, CheckStatus> checkStatus = new EnumMap<>(SecurityIndexType.class);
            for (SecurityIndexType securityIndexType : securityIndexTypes) {
                checkStatus.put(securityIndexType, CheckStatus.NA);
            }
            for (RuleId ruleId : entry.getValue()) {
                List<SecurityRule> rules = rulesDb.getRules(offlineWorkflowId, attributeSet, contingencyId,
                        ruleId.getSecurityIndexId().getSecurityIndexType());
                if (rules.size() > 0) {
                    SecurityRule rule = rules.get(0);
                    SecurityRuleExpression securityRuleExpression = rule.toExpression(purityThreshold);
                    boolean ok = securityRuleExpression.check(values).isSafe();
                    checkStatus.put(rule.getId().getSecurityIndexId().getSecurityIndexType(),
                            ok ? CheckStatus.OK : CheckStatus.NOK);
                }
            }
            for (SecurityIndexType securityIndexType : securityIndexTypes) {
                table.addCell(checkStatus.get(securityIndexType).name());
            }
        }
        System.out.println(table.render());
    } else {
        System.out.println("no state " + stateId + " of workflow " + workflowId + " stored in the online db");
    }
    onlinedb.close();
}

From source file:com.todoroo.astrid.service.StartupService.java

private void removeDuplicateTags() {
    ListMultimap<String, TagData> tagsByUuid = Multimaps.index(tagService.getTagList(), TagData::getUuid);
    for (String uuid : tagsByUuid.keySet()) {
        removeDuplicateTagData(tagsByUuid.get(uuid));
        removeDuplicateTagMetadata(uuid);
    }//from w  ww.j  a  va2 s  . co  m
    broadcaster.refresh();
}

From source file:org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer.java

public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing,
        final BaseSchema baseSchema) {
    this.counter = new MessageCounter();
    this.schemaContext = schemaContext;
    parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER,
            schemaContext, strictParsing);
    mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
    mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
    this.baseSchema = baseSchema;
}

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

@Override
public void validate(final Object obj, final Errors errors) {
    // execute JSR-303 validations (annotations)
    this.jsrValidator.validate(obj, errors);

    final ComputationRule computationRule = (ComputationRule) obj;
    if (!CollectionUtils.isEmpty(computationRule.getParameters())) {
        // custom validation for each computationRuleParameter
        for (int i = 0; i < computationRule.getParameters().size(); i++) {
            final ComputationRuleParameter nextParameter = computationRule.getParameters().get(i);
            try {
                errors.pushNestedPath(PARAMETERS + "[" + i + "]");
                ValidationUtils.invokeValidator(this.computationRuleParameterValidator, nextParameter, errors);

                if (nextParameter.getPosition() > computationRule.getParameters().size()) {
                    rejectValue(errors, "position", getErrorMessageRoot() + PARAMETERS_POSITION + MSG_INVALID,
                            nextParameter.getPosition());
                }//from   w  ww.  j a va  2s. co  m
            } finally {
                errors.popNestedPath();
            }
        }

        // check for duplicate parameter names
        final Map<String, Collection<ComputationRuleParameter>> duplicates = Maps.filterEntries(
                Multimaps.index(computationRule.getParameters(), PARAMETER_TO_NAME_TRANSFORMER).asMap(),
                PARAMETER_DUPLICATE_FILTER);
        if (!duplicates.isEmpty()) {
            rejectValue(errors, PARAMETERS, getErrorMessageRoot() + PARAMETERS_NAME + MSG_DUPLICATES,
                    duplicates.keySet().toString());
        }

        // check for duplicate parameter position
        final Map<String, Collection<ComputationRuleParameter>> duplicatePositions = Maps.filterEntries(
                Multimaps.index(computationRule.getParameters(), PARAMETER_TO_POSITION_TRANSFORMER).asMap(),
                PARAMETER_DUPLICATE_FILTER);
        if (!duplicatePositions.isEmpty()) {
            rejectValue(errors, PARAMETERS, getErrorMessageRoot() + PARAMETERS_POSITION + MSG_DUPLICATES,
                    duplicatePositions.keySet().toString());
        } else if (!errors.hasErrors()) {
            computationRule.setParameters(
                    Lists.newArrayList(Ordering.natural().onResultOf(PARAMETER_TO_POSITION_TRANSFORMER)
                            .sortedCopy(computationRule.getParameters())));
        }
    }
    if (StringUtils.trimToNull(computationRule.getVersion()) != null) {
        final String[] parts = computationRule.getVersion().split("\\.");
        if (parts.length != 2) { // not the right number version parts
            // should be 2 parts like "1.0"
            rejectValue(errors, "version", "version.format", new Object() {
            });
            return;
        }
        if (NumberUtils.toInt(parts[0], -1) < 1 || parts[1].length() > 1
                || (NumberUtils.toInt(parts[1], -1) < 0 || NumberUtils.toInt(parts[1], -1) > 9)) { //major is a negative number or some other character
            rejectValue(errors, "version", "version.majorminor.format", new Object() {
            });
        }
    }
}