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

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

Introduction

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

Prototype

@Override
List<V> get(@Nullable K key);

Source Link

Document

Because the values for a given key may have duplicates and follow the insertion ordering, this method returns a List , instead of the java.util.Collection specified in the Multimap interface.

Usage

From source file:org.eurocarbdb.sugar.CustomBasetype.java

public String getName() {
    if (this.name != null)
        return this.name;

    StringBuilder stem_name = new StringBuilder();
    StringBuilder substits = new StringBuilder();

    for (int i = 0; i < basetypes.length; i++) {
        if (i != 0)
            stem_name.append('-');

        stem_name.append(stereoConfigs[i]);
        stem_name.append('-');
        stem_name.append(basetypes[i].name());
    }/*  w  w  w  . j  av  a 2  s  .c  om*/

    //  substituents        
    Substituent s;
    ListMultimap<Substituent, Integer> map = ArrayListMultimap.create();
    CommonBasetype basetype_with_carbonyl = basetypes[(basetypes.length - 1)];

    for (int i = 0; i < functionalGroups.size(); i++) {
        s = functionalGroups.get(i);

        if (s == OH)
            continue;

        if (s == basetype_with_carbonyl.getFunctionalGroups().get(i))
            continue;

        map.put(s, i + 1);
    }

    List<Integer> positions;
    for (int i = 0; i < functionalGroups.size(); i++) {
        s = functionalGroups.get(i);
        positions = map.get(s);

        if (positions == null || positions.size() == 0)
            continue;

        if (substits.length() > 0)
            substits.append('-');

        substits.append(join(",", positions));
        substits.append('-');
        substits.append(s.getName());

        map.removeAll(s);
    }

    //  superclass, if needed         
    if (substits.length() > 0 || basetypes.length > 1) {
        stem_name.append('-');
        stem_name.append(getSuperclass().getFullName());
    }

    String name = (substits.length() > 0 ? substits.toString() + "-" : "") + stem_name.toString();

    this.name = name;

    return name;
}

From source file:eu.esdihumboldt.cst.functions.groovy.GroovyTransformation.java

@Override
protected Object evaluate(String transformationIdentifier, TransformationEngine engine,
        ListMultimap<String, PropertyValue> variables, String resultName,
        PropertyEntityDefinition resultProperty, Map<String, String> executionParameters, TransformationLog log)
        throws TransformationException, NoResultException {
    // determine if instances should be used in variables or their values
    boolean useInstanceVariables = getOptionalParameter(PARAM_INSTANCE_VARIABLES, Value.of(false))
            .as(Boolean.class);

    // instance builder
    InstanceBuilder builder = createBuilder(resultProperty);

    // create the script binding
    List<? extends Entity> varDefs = null;
    if (getCell().getSource() != null) {
        varDefs = getCell().getSource().get(ENTITY_VARIABLE);
    }/*from  w w  w. j  a  v  a2 s .c  o m*/
    Binding binding = createGroovyBinding(variables.get(ENTITY_VARIABLE), varDefs, getCell(), getTypeCell(),
            builder, useInstanceVariables, log, getExecutionContext(),
            resultProperty.getDefinition().getPropertyType());

    Object result;
    try {
        GroovyService service = getExecutionContext().getService(GroovyService.class);
        Script groovyScript = GroovyUtil.getScript(this, binding, service);

        // evaluate the script
        result = evaluate(groovyScript, builder, resultProperty.getDefinition().getPropertyType(), service,
                log);
    } catch (TransformationException | NoResultException e) {
        throw e;
    } catch (Throwable e) {
        throw new TransformationException("Error evaluating the cell script", e);
    }

    if (result == null) {
        throw new NoResultException();
    }
    return result;
}

From source file:org.onosproject.rest.resources.FlowsWebResource.java

/**
 * Removes a batch of flow rules./*from  w w  w  .j a v a 2  s . c  o m*/
 *
 * @param stream stream for posted JSON
 * @return 204 NO CONTENT
 */
@DELETE
public Response deleteFlows(InputStream stream) {
    ListMultimap<DeviceId, Long> deviceMap = ArrayListMultimap.create();
    List<FlowEntry> rulesToRemove = new ArrayList<>();

    try {
        ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);

        JsonNode jsonFlows = jsonTree.get("flows");

        jsonFlows.forEach(node -> {
            DeviceId deviceId = DeviceId
                    .deviceId(nullIsNotFound(node.get(DEVICE_ID), DEVICE_NOT_FOUND).asText());
            long flowId = nullIsNotFound(node.get(FLOW_ID), FLOW_NOT_FOUND).asLong();
            deviceMap.put(deviceId, flowId);

        });
    } catch (IOException ex) {
        throw new IllegalArgumentException(ex);
    }

    deviceMap.keySet().forEach(deviceId -> {
        List<Long> flowIds = deviceMap.get(deviceId);
        Iterable<FlowEntry> entries = service.getFlowEntries(deviceId);
        flowIds.forEach(flowId -> {
            StreamSupport.stream(entries.spliterator(), false).filter(entry -> flowId == entry.id().value())
                    .forEach(rulesToRemove::add);
        });
    });

    service.removeFlowRules(rulesToRemove.toArray(new FlowEntry[0]));
    return Response.noContent().build();
}

From source file:org.eclipse.xtend.core.jvmmodel.XtendJvmModelInferrer.java

protected void appendSyntheticDispatchMethods(XtendTypeDeclaration source, final JvmGenericType target) {
    ListMultimap<DispatchHelper.DispatchSignature, JvmOperation> methods = dispatchHelper
            .getDeclaredOrEnhancedDispatchMethods(target);
    for (DispatchHelper.DispatchSignature signature : methods.keySet()) {
        List<JvmOperation> operations = methods.get(signature);
        Iterable<JvmOperation> localOperations = Iterables.filter(operations, new Predicate<JvmOperation>() {
            @Override/*  w w  w .ja v a 2 s . c o m*/
            public boolean apply(JvmOperation input) {
                return target == input.eContainer();
            }
        });
        JvmOperation operation = deriveGenericDispatchOperationSignature(localOperations, target);
        if (operation != null) {
            dispatchHelper.markAsDispatcherFunction(operation);
            operation.setSimpleName(signature.getSimpleName());
            operation.setReturnType(jvmTypesBuilder.inferredType());
        }
    }
}

From source file:org.summer.ss.core.jvmmodel.SsJvmModelInferrer.java

protected void appendSyntheticDispatchMethods(XtendClass source, JvmGenericType target) {
    ListMultimap<DispatchHelper.DispatchSignature, JvmOperation> methods = dispatchHelper
            .getDeclaredOrEnhancedDispatchMethods(target);
    for (DispatchHelper.DispatchSignature signature : methods.keySet()) {
        List<JvmOperation> operations = methods.get(signature);
        JvmOperation operation = deriveGenericDispatchOperationSignature(operations, target);
        if (operation != null) {
            operation.setSimpleName(signature.getSimpleName());
            operation.setReturnType(jvmTypesBuilder.inferredType());
        }/*from   w w w . ja  v  a  2 s.co m*/
    }
}

From source file:com.google.gerrit.server.plugins.PluginGuiceEnvironment.java

private void reattachItem(ListMultimap<TypeLiteral<?>, ReloadableRegistrationHandle<?>> oldHandles,
        Map<TypeLiteral<?>, DynamicItem<?>> items, @Nullable Injector src, Plugin newPlugin) {
    if (src == null || items == null || items.isEmpty()) {
        return;/*from w w  w .j av a2 s .co m*/
    }

    for (Map.Entry<TypeLiteral<?>, DynamicItem<?>> e : items.entrySet()) {
        @SuppressWarnings("unchecked")
        TypeLiteral<Object> type = (TypeLiteral<Object>) e.getKey();

        @SuppressWarnings("unchecked")
        DynamicItem<Object> item = (DynamicItem<Object>) e.getValue();

        Iterator<ReloadableRegistrationHandle<?>> oi = oldHandles.get(type).iterator();

        for (Binding<?> binding : bindings(src, type)) {
            @SuppressWarnings("unchecked")
            Binding<Object> b = (Binding<Object>) binding;
            if (oi.hasNext()) {
                @SuppressWarnings("unchecked")
                ReloadableRegistrationHandle<Object> h = (ReloadableRegistrationHandle<Object>) oi.next();
                oi.remove();
                replace(newPlugin, h, b);
            } else {
                newPlugin.add(item.set(b.getKey(), b.getProvider(), newPlugin.getName()));
            }
        }
    }
}

From source file:com.oarfish.keywords.rake.RakeMatrix.java

/**
 * method to initialize the frequency and degree matrix
 *
 * @param candidateKeyword//  w  w w. j  av a 2 s.co  m
 */
private void initMatrix(CandidateKeyword[] candidateKeyword) {
    ListMultimap<String, String> coocurrenceMatrix = ArrayListMultimap.create();
    for (CandidateKeyword candidate : candidateKeyword) {
        //do not include adjoin keywords in the matrix
        if (candidate.isIsAdjoin() == true) {
            continue;
        }

        String[] tokens = candidate.getLabel().split(" ");
        HashSet<String> tokenSet = Sets.newHashSet(tokens);

        for (String token : tokens) {
            int currentFreq = getOrDefault(freqMap, token, 0);

            //update frequency map
            freqMap.put(token, currentFreq + 1);

            //update co-occurence matrix
            for (String neighbor : tokenSet) {
                if (!neighbor.equals(token)) {
                    coocurrenceMatrix.put(token, neighbor);
                }
            }
        }
    }
    for (String token : freqMap.keySet()) {
        //degree is define as: freq(t) + size of co-occurrence_vector(t)
        int degree = freqMap.get(token) + coocurrenceMatrix.get(token).size();
        degreeMap.put(token, degree);
    }
}

From source file:com.rackspacecloud.blueflood.io.AstyanaxReader.java

public Map<Locator, MetricData> getDatapointsForRange(List<Locator> locators, Range range, Granularity gran) {
    ListMultimap<ColumnFamily, Locator> locatorsByCF = ArrayListMultimap.create();
    Map<Locator, MetricData> results = new HashMap<Locator, MetricData>();

    for (Locator locator : locators) {
        try {/*from  ww w  . j  av a2 s .com*/
            RollupType rollupType = RollupType.fromString(
                    (String) metaCache.get(locator, MetricMetadata.ROLLUP_TYPE.name().toLowerCase()));
            DataType dataType = new DataType(
                    (String) metaCache.get(locator, MetricMetadata.TYPE.name().toLowerCase()));
            ColumnFamily cf = CassandraModel.getColumnFamily(rollupType, dataType, gran);
            List<Locator> locs = locatorsByCF.get(cf);
            locs.add(locator);
        } catch (Exception e) {
            // pass for now. need metric to figure this stuff out.
        }
    }

    for (ColumnFamily CF : locatorsByCF.keySet()) {
        List<Locator> locs = locatorsByCF.get(CF);
        Map<Locator, ColumnList<Long>> metrics = getColumnsFromDB(locs, CF, range);
        // transform columns to MetricData
        for (Locator loc : metrics.keySet()) {
            MetricData data = transformColumnsToMetricData(loc, metrics.get(loc), gran);
            if (data != null) {
                results.put(loc, data);
            }
        }
    }

    return results;
}

From source file:org.jpmml.evaluator.rule_set.RuleSetModelEvaluator.java

private Map<FieldName, ? extends Classification> evaluateClassification(ModelEvaluationContext context) {
    RuleSetModel ruleSetModel = getModel();

    RuleSet ruleSet = ruleSetModel.getRuleSet();

    List<RuleSelectionMethod> ruleSelectionMethods = ruleSet.getRuleSelectionMethods();
    if (ruleSelectionMethods.size() < 1) {
        throw new InvalidFeatureException(ruleSet);
    }//from w w  w . java 2  s.  co  m

    // "If more than one method is included, the first method is used as the default method for scoring"
    RuleSelectionMethod ruleSelectionMethod = ruleSelectionMethods.get(0);

    // Both the ordering of keys and values is significant
    ListMultimap<String, SimpleRule> firedRules = LinkedListMultimap.create();

    evaluateRules(ruleSet.getRules(), firedRules, context);

    BiMap<String, SimpleRule> entityRegistry = getEntityRegistry();

    SimpleRuleScoreDistribution result = new SimpleRuleScoreDistribution(entityRegistry);

    // Return the default prediction when no rules in the ruleset fire
    if (firedRules.size() == 0) {
        String score = ruleSet.getDefaultScore();

        result.put(new SimpleRule(score), score, ruleSet.getDefaultConfidence());

        return TargetUtil.evaluateClassification(result, context);
    }

    RuleSelectionMethod.Criterion criterion = ruleSelectionMethod.getCriterion();

    Set<String> keys = firedRules.keySet();
    for (String key : keys) {
        List<SimpleRule> keyRules = firedRules.get(key);

        switch (criterion) {
        case FIRST_HIT: {
            SimpleRule winner = keyRules.get(0);

            // The first value of the first key
            if (result.getEntity() == null) {
                result.setEntity(winner);
            }

            result.put(key, winner.getConfidence());
        }
            break;
        case WEIGHTED_SUM: {
            SimpleRule winner = null;

            double totalWeight = 0;

            for (SimpleRule keyRule : keyRules) {

                if (winner == null || (winner.getWeight() < keyRule.getWeight())) {
                    winner = keyRule;
                }

                totalWeight += keyRule.getWeight();
            }

            result.put(winner, key, totalWeight / firedRules.size());
        }
            break;
        case WEIGHTED_MAX: {
            SimpleRule winner = null;

            for (SimpleRule keyRule : keyRules) {

                if (winner == null || (winner.getWeight() < keyRule.getWeight())) {
                    winner = keyRule;
                }
            }

            result.put(winner, key, winner.getConfidence());
        }
            break;
        default:
            throw new UnsupportedFeatureException(ruleSelectionMethod, criterion);
        }
    }

    return TargetUtil.evaluateClassification(result, context);
}

From source file:org.apache.hadoop.hbase.rsgroup.RSGroupBasedLoadBalancer.java

@Override
public Map<ServerName, List<HRegionInfo>> retainAssignment(Map<HRegionInfo, ServerName> regions,
        List<ServerName> servers) throws HBaseIOException {
    try {/*  w w  w  . j  a v  a2 s  . c  o m*/
        Map<ServerName, List<HRegionInfo>> assignments = new TreeMap<ServerName, List<HRegionInfo>>();
        ListMultimap<String, HRegionInfo> groupToRegion = ArrayListMultimap.create();
        Set<HRegionInfo> misplacedRegions = getMisplacedRegions(regions);
        for (HRegionInfo region : regions.keySet()) {
            if (!misplacedRegions.contains(region)) {
                String groupName = RSGroupInfoManager.getRSGroupOfTable(region.getTable());
                groupToRegion.put(groupName, region);
            }
        }
        // Now the "groupToRegion" map has only the regions which have correct
        // assignments.
        for (String key : groupToRegion.keySet()) {
            Map<HRegionInfo, ServerName> currentAssignmentMap = new TreeMap<HRegionInfo, ServerName>();
            List<HRegionInfo> regionList = groupToRegion.get(key);
            RSGroupInfo info = RSGroupInfoManager.getRSGroup(key);
            List<ServerName> candidateList = filterOfflineServers(info, servers);
            for (HRegionInfo region : regionList) {
                currentAssignmentMap.put(region, regions.get(region));
            }
            if (candidateList.size() > 0) {
                assignments.putAll(this.internalBalancer.retainAssignment(currentAssignmentMap, candidateList));
            }
        }

        for (HRegionInfo region : misplacedRegions) {
            String groupName = RSGroupInfoManager.getRSGroupOfTable(region.getTable());
            RSGroupInfo info = RSGroupInfoManager.getRSGroup(groupName);
            List<ServerName> candidateList = filterOfflineServers(info, servers);
            ServerName server = this.internalBalancer.randomAssignment(region, candidateList);
            if (server != null) {
                if (!assignments.containsKey(server)) {
                    assignments.put(server, new ArrayList<HRegionInfo>());
                }
                assignments.get(server).add(region);
            } else {
                //if not server is available assign to bogus so it ends up in RIT
                if (!assignments.containsKey(LoadBalancer.BOGUS_SERVER_NAME)) {
                    assignments.put(LoadBalancer.BOGUS_SERVER_NAME, new ArrayList<HRegionInfo>());
                }
                assignments.get(LoadBalancer.BOGUS_SERVER_NAME).add(region);
            }
        }
        return assignments;
    } catch (IOException e) {
        throw new HBaseIOException("Failed to do online retain assignment", e);
    }
}