Example usage for com.google.common.collect ListMultimap asMap

List of usage examples for com.google.common.collect ListMultimap asMap

Introduction

In this page you can find the example usage for com.google.common.collect ListMultimap asMap.

Prototype

@Override
Map<K, Collection<V>> asMap();

Source Link

Document

Note: The returned map's values are guaranteed to be of type List .

Usage

From source file:com.cloudera.flume.master.ZooKeeperConfigStore.java

/**
 * Converts a nodemap into an Avro-serialized byte array
 *//*from   w w w.  j  a v  a 2  s .c om*/
static protected byte[] serializeNodeMap(ListMultimap<String, String> nodeMap) throws IOException {
    DatumWriter<AvroFlumeNodeMap> datumWriter = new SpecificDatumWriter<AvroFlumeNodeMap>();
    AvroFlumeNodeMap avromap = new AvroFlumeNodeMap();

    Map<CharSequence, List<CharSequence>> map = new HashMap<CharSequence, List<CharSequence>>();
    for (Entry<String, Collection<String>> e : nodeMap.asMap().entrySet()) {
        String name = e.getKey();
        GenericArray<CharSequence> out = new GenericData.Array<CharSequence>(e.getValue().size(),
                Schema.createArray(Schema.create(Type.STRING)));

        for (String s : e.getValue()) {
            out.add(new String(s));
        }

        map.put(name, out);
    }

    avromap.nodemap = map;

    datumWriter.setSchema(avromap.getSchema());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataFileWriter<AvroFlumeNodeMap> fileWriter = new DataFileWriter<AvroFlumeNodeMap>(datumWriter);
    fileWriter.create(avromap.getSchema(), baos);
    fileWriter.append(avromap);
    fileWriter.close();

    return baos.toByteArray();
}

From source file:de.bund.bfr.knime.pmmlite.core.CombineUtils.java

public static List<TertiaryModel> combine(List<SecondaryModel> dataModels) throws UnitException {
    // 1. find secondary models and data for each primary model
    Map<String, PrimaryModel> primModelMap = new LinkedHashMap<>();
    Map<String, Map<String, Double>> paramMeanMap = new LinkedHashMap<>();
    ListMultimap<String, SecondaryModel> secModelMap = ArrayListMultimap.create();
    ListMultimap<String, TimeSeries> dataMap = ArrayListMultimap.create();

    for (SecondaryModel dataModel : dataModels) {
        PrimaryModel primModel = dataModel.getData().get(0);
        String id = primModel.getFormula().getId();

        if (!primModelMap.containsKey(id)) {
            primModelMap.put(id, primModel);

            ListMultimap<String, Double> paramValues = ArrayListMultimap.create();

            for (PrimaryModel primData : dataModel.getData()) {
                dataMap.put(id, primData.getData());

                for (Parameter param : primModel.getFormula().getParams()) {
                    ParameterValue value = primData.getParamValues().get(param.getName());

                    if (value != null && value.getValue() != null) {
                        paramValues.put(param.getName(), value.getValue());
                    }/*from   w  ww  .ja v  a 2  s . c o m*/
                }
            }

            Map<String, Double> paramMeans = new LinkedHashMap<>();

            for (Map.Entry<String, Collection<Double>> entry : paramValues.asMap().entrySet()) {
                paramMeans.put(entry.getKey(), DoubleMath.mean(Doubles.toArray(entry.getValue())));
            }

            paramMeanMap.put(id, paramMeans);
        }

        secModelMap.put(id, dataModel);
        paramMeanMap.get(id)
                .remove(dataModel.getAssignments().get(dataModel.getFormula().getDepVar().getName()));
    }

    // 2. if secondary does not exist for a parameter create constant model
    // 3. call combine for each primary models with its secondary models
    List<TertiaryModel> tertiaryModels = new ArrayList<>();

    for (Map.Entry<String, PrimaryModel> entry : primModelMap.entrySet()) {
        String id = entry.getKey();
        PrimaryModel primModel = entry.getValue();
        List<SecondaryModel> secModels = secModelMap.get(id);
        List<Model> allModels = new ArrayList<>();

        allModels.add(primModel);
        allModels.addAll(secModels);

        TertiaryModel tertModel = ModelsFactory.eINSTANCE.createTertiaryModel();

        tertModel.setId(Joiner.on("").join(PmmUtils.getIds(allModels)));
        tertModel.setName(Joiner.on("_").join(PmmUtils.getNames(secModels)));

        for (Map.Entry<String, VariableRange> range : primModel.getVariableRanges().entrySet()) {
            tertModel.getVariableRanges().put(range.getKey(), EcoreUtil.copy(range.getValue()));
        }

        for (Map.Entry<String, ParameterValue> value : primModel.getParamValues().entrySet()) {
            tertModel.getParamValues().put(value.getKey(), EcoreUtil.copy(value.getValue()));
        }

        for (SecondaryModel secModel : secModels) {
            String depVarAssignment = secModel.getAssignments()
                    .get(secModel.getFormula().getDepVar().getName());

            tertModel.getParamValues().remove(depVarAssignment);
        }

        List<SecondaryModelFormula> secFormulas = new ArrayList<>();
        Map<String, String> assignments = new LinkedHashMap<>();
        Map<String, Renamings> secondaryRenamings = new LinkedHashMap<>();

        for (SecondaryModel secModel : secModels) {
            SecondaryModelFormula secFormula = secModel.getFormula();
            String depVarAssignment = secModel.getAssignments().get(secFormula.getDepVar().getName());
            Renamings renamings = ModelsFactory.eINSTANCE.createRenamings();

            for (Map.Entry<String, String> assignment : secModel.getAssignments().entrySet()) {
                if (!assignment.getKey().equals(secFormula.getDepVar().getName())) {
                    renamings.getMap().put(assignment.getKey(), assignment.getValue());
                    tertModel.getAssignments().put(assignment.getValue(), assignment.getValue());
                }
            }

            secFormulas.add(secFormula);
            assignments.put(depVarAssignment, secFormula.getId());
            secondaryRenamings.put(depVarAssignment, renamings);

            for (Variable var : secFormula.getIndepVars()) {
                VariableRange range = secModel.getVariableRanges()
                        .get(secModel.getAssignments().get(var.getName()));

                addIndep(tertModel, renamings.getMap().get(var.getName()), EcoreUtil.copy(range));
            }

            for (Map.Entry<String, ParameterValue> value : secModel.getParamValues().entrySet()) {
                addParam(tertModel, value.getKey(), EcoreUtil.copy(value.getValue()));
            }
        }

        for (Parameter param : primModel.getFormula().getParams()) {
            if (!assignments.containsKey(param.getName())) {
                ParameterValue value = ModelsFactory.eINSTANCE.createParameterValue();

                value.setValue(paramMeanMap.get(primModel.getFormula().getId()).get(param.getName()));
                tertModel.getParamValues().put(param.getName(), value);
            }
        }

        for (ParameterValue value : tertModel.getParamValues().values()) {
            value.setError(null);
            value.setP(null);
            value.setT(null);
            value.getCorrelations().clear();
        }

        tertModel.setFormula(combine(primModel.getFormula(), secFormulas, assignments, secondaryRenamings));
        tertModel.getAssignments().putAll(primModel.getAssignments());
        tertModel.getData().addAll(dataMap.get(id));
        tertiaryModels.add(tertModel);
    }

    return tertiaryModels;
}

From source file:exm.stc.ic.opt.WaitCoalescer.java

/**
 * Find the variable which appears the most times in a value of the
 * map/*  w w  w.  j a va  2 s .  c  om*/
 * @param waitMap
 * @return
 */
public static Var mostSharedVar(ListMultimap<Var, WaitStatement> waitMap) {
    Var winner = null;
    int winCount = 0;
    for (Entry<Var, Collection<WaitStatement>> e : waitMap.asMap().entrySet()) {
        Collection<WaitStatement> waits = e.getValue();
        if (waits.size() > 1) {
            if (winner == null || waits.size() > winCount) {
                winner = e.getKey();
                winCount = waits.size();
            }
        }
    }
    return winner;
}

From source file:eu.numberfour.n4js.tests.GrammarLinter.java

private void printKeywordsOnlyInDatatypeRules() {
    Grammar grammar = grammarAccess.getGrammar();
    ListMultimap<String, Keyword> allKeywords = getAllKeywords(grammar);
    System.out.println("Keywords which do not occur in production rules: ");
    outer: for (Collection<Keyword> chunk : allKeywords.asMap().values()) {
        for (Keyword keyword : chunk) {
            AbstractRule rule = EcoreUtil2.getContainerOfType(keyword, AbstractRule.class);
            if (!GrammarUtil.isDatatypeRule(rule)) {
                continue outer;
            }/*from   w  w  w.j a va2s.  co  m*/
        }
        System.out.println("  " + ((List<Keyword>) chunk).get(0).getValue());
    }
    System.out.println();
}

From source file:org.jpmml.evaluator.general_regression.GeneralRegressionModelEvaluator.java

@SuppressWarnings(value = { "rawtypes", "unchecked" })
static private <C extends ParameterCell> Map<String, List<C>> asMap(ListMultimap<String, C> multimap) {
    return (Map) multimap.asMap();
}

From source file:org.sonar.server.qualityprofile.DefinedQProfileRepositoryImpl.java

private void validateAndClean(ListMultimap<String, RulesProfile> byLang) {
    byLang.asMap().entrySet().removeIf(entry -> {
        String language = entry.getKey();
        if (languages.get(language) == null) {
            LOGGER.info("Language {} is not installed, related Quality profiles are ignored", language);
            return true;
        }//from   w ww . ja v  a  2s .  c  o m
        Collection<RulesProfile> profiles = entry.getValue();
        if (profiles.isEmpty()) {
            LOGGER.warn("No Quality profiles defined for language: {}", language);
            return true;
        }
        return false;
    });
}

From source file:org.sonar.server.qualityprofile.QProfileReset.java

/**
 * Reset built-in profiles for the given language. Missing profiles are created and
 * existing ones are updated./* w  w  w . j  a va 2 s  .com*/
 */
public void resetLanguage(String language) {
    DbSession dbSession = db.openSession(false);
    try {
        ListMultimap<QProfileName, RulesProfile> profilesByName = loadDefinitionsGroupedByName(language);
        for (Map.Entry<QProfileName, Collection<RulesProfile>> entry : profilesByName.asMap().entrySet()) {
            QProfileName profileName = entry.getKey();
            QualityProfileDto profile = factory.getOrCreate(dbSession, profileName);
            List<RuleActivation> activations = Lists.newArrayList();
            for (RulesProfile def : entry.getValue()) {
                for (ActiveRule activeRule : def.getActiveRules()) {
                    RuleActivation activation = new RuleActivation(
                            RuleKey.of(activeRule.getRepositoryKey(), activeRule.getRuleKey()));
                    activation.setSeverity(activeRule.getSeverity().name());
                    if (!activeRule.getActiveRuleParams().isEmpty()) {
                        for (ActiveRuleParam param : activeRule.getActiveRuleParams()) {
                            activation.setParameter(param.getParamKey(), param.getValue());
                        }
                    } else {
                        for (RuleParamDto param : db.ruleDao().selectRuleParamsByRuleKey(dbSession,
                                activeRule.getRule().ruleKey())) {
                            activation.setParameter(param.getName(), param.getDefaultValue());
                        }
                    }
                    activations.add(activation);
                }
            }
            doReset(dbSession, profile, activations);
        }
    } finally {
        dbSession.close();
    }
}

From source file:org.glowroot.agent.embedded.util.Schemas.java

@VisibleForTesting
static ImmutableSet<Index> getIndexes(String tableName, Connection connection) throws SQLException {
    ListMultimap</*@Untainted*/ String, /*@Untainted*/ String> indexColumns = ArrayListMultimap.create();
    ResultSet resultSet = getMetaDataIndexInfo(connection, tableName);
    ResultSetCloser closer = new ResultSetCloser(resultSet);
    try {//from  ww  w .j  av  a 2s  .  c  o  m
        while (resultSet.next()) {
            String indexName = checkNotNull(resultSet.getString("INDEX_NAME"));
            String columnName = checkNotNull(resultSet.getString("COLUMN_NAME"));
            // hack-ish to skip over primary key constraints which seem to be always
            // prefixed in H2 by PRIMARY_KEY_
            if (!indexName.startsWith("PRIMARY_KEY_")) {
                indexColumns.put(castUntainted(indexName), castUntainted(columnName));
            }
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
    ImmutableSet.Builder<Index> indexes = ImmutableSet.builder();
    for (Map.Entry</*@Untainted*/ String, Collection</*@Untainted*/ String>> entry : indexColumns.asMap()
            .entrySet()) {
        String name = entry.getKey().toLowerCase(Locale.ENGLISH);
        List<String> columns = Lists.newArrayList();
        for (String column : entry.getValue()) {
            columns.add(column.toLowerCase(Locale.ENGLISH));
        }
        indexes.add(ImmutableIndex.of(name, columns));
    }
    return indexes.build();
}

From source file:org.glowroot.agent.fat.storage.util.Schemas.java

@VisibleForTesting
static ImmutableSet<Index> getIndexes(String tableName, Connection connection) throws SQLException {
    ListMultimap</*@Untainted*/ String, /*@Untainted*/ String> indexColumns = ArrayListMultimap.create();
    ResultSet resultSet = getMetaDataIndexInfo(connection, tableName);
    ResultSetCloser closer = new ResultSetCloser(resultSet);
    try {/*w  w  w .ja  v a2 s .c o m*/
        while (resultSet.next()) {
            String indexName = checkNotNull(resultSet.getString("INDEX_NAME"));
            String columnName = checkNotNull(resultSet.getString("COLUMN_NAME"));
            // hack-ish to skip over primary key constraints which seem to be always
            // prefixed in H2 by PRIMARY_KEY_
            if (!indexName.startsWith("PRIMARY_KEY_")) {
                indexColumns.put(castUntainted(indexName), castUntainted(columnName));
            }
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
    ImmutableSet.Builder<Index> indexes = ImmutableSet.builder();
    for (Entry</*@Untainted*/ String, Collection</*@Untainted*/ String>> entry : indexColumns.asMap()
            .entrySet()) {
        String name = entry.getKey().toLowerCase(Locale.ENGLISH);
        List<String> columns = Lists.newArrayList();
        for (String column : entry.getValue()) {
            columns.add(column.toLowerCase(Locale.ENGLISH));
        }
        indexes.add(ImmutableIndex.of(name, columns));
    }
    return indexes.build();
}

From source file:org.gradle.configuration.TaskDetailPrinter.java

private void printlnCommandlineOptions(StyledTextOutput output, List<Task> tasks) {
    List<OptionDescriptor> allOptions = new ArrayList<OptionDescriptor>();
    for (Task task : tasks) {
        allOptions.addAll(optionReader.getOptions(task));
    }//  w  ww . j  ava2s. c  om
    if (!allOptions.isEmpty()) {
        output.println();
        output.text("Options").println();
    }
    final ListMultimap<String, OptionDescriptor> optionsByName = groupDescriptorsByName(allOptions);
    Iterator<String> optionNames = sort(optionsByName.asMap().keySet()).iterator();
    while (optionNames.hasNext()) {
        final String currentOption = optionNames.next();
        final List<OptionDescriptor> descriptorsForCurrentName = optionsByName.get(currentOption);

        final String optionString = String.format("--%s", currentOption);
        output.text(INDENT).withStyle(UserInput).text(optionString);

        List<List<String>> availableValuesByDescriptor = collect(descriptorsForCurrentName,
                new Transformer<List<String>, OptionDescriptor>() {
                    public List<String> transform(OptionDescriptor original) {
                        return original.getAvailableValues();
                    }
                });

        List<String> commonAvailableValues = intersection(availableValuesByDescriptor);
        Set<String> availableValues = new TreeSet<String>(commonAvailableValues);
        //description does not differ between task objects, grab first one
        output.text(INDENT).text(descriptorsForCurrentName.iterator().next().getDescription());
        if (!availableValues.isEmpty()) {
            final int optionDescriptionOffset = 2 * INDENT.length() + optionString.length();
            final LinePrefixingStyledTextOutput prefixedOutput = createIndentedOutput(output,
                    optionDescriptionOffset);
            prefixedOutput.println();
            prefixedOutput.println("Available values are:");
            for (String value : availableValues) {
                prefixedOutput.text(INDENT);
                prefixedOutput.withStyle(UserInput).println(value);
            }
        } else {
            output.println();
        }
        if (optionNames.hasNext()) {
            output.println();
        }
    }
}