Example usage for com.google.common.collect Multimap values

List of usage examples for com.google.common.collect Multimap values

Introduction

In this page you can find the example usage for com.google.common.collect Multimap values.

Prototype

Collection<V> values();

Source Link

Document

Returns a view collection containing the value from each key-value pair contained in this multimap, without collapsing duplicates (so values().size() == size() ).

Usage

From source file:org.opentestsystem.shared.security.service.AbsractRolesAndPermissionsService.java

protected Multimap<String, SbacRole> extractUserRoles(final String pipeDelimitedTenancyChain,
        final Map<String, RoleToPermissionMapping> roleToPermissionMappings) {
    List<String[]> roleStringsDelimited = new ArrayList<String[]>();
    LOGGER.debug("tenantChain: " + pipeDelimitedTenancyChain);
    if (StringUtils.isNotEmpty(pipeDelimitedTenancyChain)) {
        final String[] attr = pipeDelimitedTenancyChain.split("[|]", -1);
        // split one long string into individual rows for parsing
        final int roleCount = attr.length / ROLE_FIELD_COUNT;
        for (int i = 0; i < roleCount; i++) {
            final Object[] roleStringSet = ArrayUtils.subarray(attr, i * ROLE_FIELD_COUNT,
                    (i + 1) * ROLE_FIELD_COUNT);
            roleStringsDelimited.add((String[]) roleStringSet);
        }/*from   w w w .  j  av a  2s  .c o  m*/
    }
    final Multimap<String, SbacRole> userRoles = buildRolesFromParsedStrings(roleToPermissionMappings,
            roleStringsDelimited);
    setupEffectiveTenantsForRoles(Lists.newArrayList(userRoles.values()));
    return userRoles;
}

From source file:org.gradle.model.internal.manage.binding.DefaultStructBindingsStore.java

private static ModelType<?> determineManagedPropertyType(StructBindingExtractionContext<?> extractionContext,
        String propertyName, Multimap<PropertyAccessorType, StructMethodBinding> accessorBindings) {
    Collection<StructMethodBinding> isGetter = accessorBindings.get(IS_GETTER);
    for (StructMethodBinding isGetterBinding : isGetter) {
        if (!((ManagedPropertyMethodBinding) isGetterBinding).getDeclaredPropertyType()
                .equals(ModelType.of(Boolean.TYPE))) {
            WeaklyTypeReferencingMethod<?, ?> isGetterMethod = isGetterBinding.getViewMethod();
            extractionContext.add(isGetterMethod,
                    String.format("it should either return 'boolean', or its name should be '%s()'",
                            "get" + isGetterMethod.getName().substring(2)));
        }//from   w  w  w . j a va2  s .com
    }
    Set<ModelType<?>> potentialPropertyTypes = Sets.newLinkedHashSet();
    for (StructMethodBinding binding : accessorBindings.values()) {
        if (binding.getAccessorType() == SETTER) {
            continue;
        }
        ManagedPropertyMethodBinding propertyBinding = (ManagedPropertyMethodBinding) binding;
        potentialPropertyTypes.add(propertyBinding.getDeclaredPropertyType());
    }
    Collection<ModelType<?>> convergingPropertyTypes = findConvergingTypes(potentialPropertyTypes);
    if (convergingPropertyTypes.size() != 1) {
        extractionContext.add(propertyName,
                String.format("it must have a consistent type, but it's defined as %s",
                        Joiner.on(", ").join(ModelTypes.getDisplayNames(convergingPropertyTypes))));
        return convergingPropertyTypes.iterator().next();
    }
    ModelType<?> propertyType = Iterables.getOnlyElement(convergingPropertyTypes);

    for (StructMethodBinding setterBinding : accessorBindings.get(SETTER)) {
        ManagedPropertyMethodBinding propertySetterBinding = (ManagedPropertyMethodBinding) setterBinding;
        ModelType<?> declaredSetterType = propertySetterBinding.getDeclaredPropertyType();
        if (!declaredSetterType.equals(propertyType)) {
            extractionContext.add(setterBinding.getViewMethod(),
                    String.format("it should take parameter with type '%s'", propertyType.getDisplayName()));
        }
    }
    return propertyType;
}

From source file:fr.ujm.tse.lt2c.satin.rules.run.RunRHODF7b.java

@Override
protected int process(final TripleStore ts1, final TripleStore ts2, final Collection<Triple> outputTriples) {

    final long domain = AbstractDictionary.domain;
    final long range = AbstractDictionary.range;
    final long type = AbstractDictionary.type;
    final long subClassOf = AbstractDictionary.subClassOf;

    int loops = 0;

    final Multimap<Long, Long> domainMultiMap = ts2.getMultiMapForPredicate(domain);
    final Multimap<Long, Long> rangeMultiMap = ts2.getMultiMapForPredicate(range);
    final Multimap<Long, Long> typeMultiMap = ts2.getMultiMapForPredicate(type);
    if (domainMultiMap != null && !domainMultiMap.isEmpty()) {
        for (final Long o : domainMultiMap.values()) {
            loops++;/*  w  ww .  j a v  a2  s . c o m*/
            final Triple result = new ImmutableTriple(o, subClassOf, o);
            outputTriples.add(result);
        }
    }
    if (rangeMultiMap != null && !rangeMultiMap.isEmpty()) {
        for (final Long o : rangeMultiMap.values()) {
            loops++;
            final Triple result = new ImmutableTriple(o, subClassOf, o);
            outputTriples.add(result);
        }
    }
    if (typeMultiMap != null && !typeMultiMap.isEmpty()) {
        for (final Long o : typeMultiMap.values()) {
            loops++;
            final Triple result = new ImmutableTriple(o, subClassOf, o);
            outputTriples.add(result);
        }
    }

    return loops;

}

From source file:com.facebook.presto.execution.scheduler.SourcePartitionedScheduler.java

@Override
public synchronized ScheduleResult schedule() {
    // Acquire a future for the next state change before doing calculations.
    ///* w  w  w  .  ja v  a  2  s .co  m*/
    // This code may need to return a future when the workers are full, and
    // it is critical that this future is notified of any changes that occur
    // during this calculation (to avoid starvation).
    CompletableFuture<?> taskStateChange = stage.getTaskStateChange();

    // try to get the next batch if necessary
    if (pendingSplits.isEmpty()) {
        if (batchFuture == null) {
            if (splitSource.isFinished()) {
                // no more splits
                splitSource.close();
                return new ScheduleResult(true, ImmutableSet.of(), CompletableFuture.completedFuture(null));
            }

            batchFuture = splitSource.getNextBatch(splitBatchSize);
            long start = System.nanoTime();
            batchFuture.thenRun(() -> stage.recordGetSplitTime(start));
        }

        if (!batchFuture.isDone()) {
            // wrap batch future in unmodifiable future so cancellation is not propagated
            CompletableFuture<List<Split>> blocked = unmodifiableFuture(batchFuture);
            return new ScheduleResult(false, ImmutableSet.of(), blocked);
        }
        pendingSplits = ImmutableSet.copyOf(getFutureValue(batchFuture));
        batchFuture = null;
    }

    // assign the splits
    Multimap<Node, Split> splitAssignment = splitPlacementPolicy.computeAssignments(pendingSplits);
    Set<RemoteTask> newTasks = assignSplits(splitAssignment);

    // remove assigned splits
    pendingSplits = ImmutableSet
            .copyOf(Sets.difference(pendingSplits, ImmutableSet.copyOf(splitAssignment.values())));

    // if not all splits were consumed, return a partial result
    if (!pendingSplits.isEmpty()) {
        newTasks = ImmutableSet.<RemoteTask>builder().addAll(newTasks).addAll(finalizeTaskCreationIfNecessary())
                .build();

        return new ScheduleResult(false, newTasks, taskStateChange);
    }

    // all splits assigned - check if the source is finished
    boolean finished = splitSource.isFinished();
    if (finished) {
        splitSource.close();
    }
    return new ScheduleResult(finished, newTasks, CompletableFuture.completedFuture(null));
}

From source file:org.summer.dsl.model.types.util.FeatureOverridesService.java

protected Iterable<JvmFeature> removeOverridden(
        Multimap<Triple<EClass, String, Integer>, JvmFeature> featureIndex, ITypeArgumentContext ctx) {
    Set<JvmFeature> result = Sets.newLinkedHashSet(featureIndex.values());
    for (Collection<JvmFeature> featuresWithSameName : featureIndex.asMap().values()) {
        if (featuresWithSameName.size() > 1) {
            for (JvmFeature op1 : featuresWithSameName) {
                for (JvmFeature op2 : featuresWithSameName) {
                    if (result.contains(op1) && op1.getDeclaringType() != op2.getDeclaringType()
                            && internalIsOverridden(op1, op2, ctx, true))
                        result.remove(op2);
                }/*  w w w. j a  va 2 s.c o  m*/
            }
        }
    }
    return result;
}

From source file:org.xacml4j.v30.pdp.Policy.java

public Collection<CombinerParameter> getRuleCombinerParams(String ruleId) {
    Multimap<String, CombinerParameter> p = ruleCombiningParameters.get(ruleId);
    return (p == null) ? ImmutableList.<CombinerParameter>of() : p.values();
}

From source file:org.artifactory.ui.rest.service.builds.buildsinfo.tabs.licenses.BuildLicensesService.java

@Override
public void execute(ArtifactoryRestRequest request, RestResponse response) {
    try {/*www .  ja  v a 2s. c  o m*/
        String name = request.getPathParamByKey("name");
        String buildNumber = request.getPathParamByKey("number");
        String buildStarted = DateUtils.formatBuildDate(Long.parseLong(request.getPathParamByKey("date")));
        Boolean authFind = Boolean.valueOf(request.getQueryParamByKey("autoFind"));
        Build build = getBuild(name, buildNumber, buildStarted, response);
        // fetch license
        Multimap<RepoPath, ModuleLicenseModel> repoPathLicenseModuleModel = getRepoPathLicenseModuleModelMultimap(
                build, authFind);
        if (repoPathLicenseModuleModel != null && !repoPathLicenseModuleModel.isEmpty()) {
            Collection<ModuleLicenseModel> values = repoPathLicenseModuleModel.values();
            // fetch published modules
            Set<ModuleLicenseModel> publishedModules = getPublishedModulesFromModelList(values,
                    build.getModules());
            // filter published modules from licenses
            publishedModules.forEach(published -> values.remove(published));
            // fetch build license summary
            Set<String> scopes = getScopeMapping(values);
            BuildLicenseModel buildLicenseModel = new BuildLicenseModel(values, publishedModules, scopes);
            response.iModel(buildLicenseModel);
            // get scopes
        }
    } catch (ParseException e) {
        log.error(e.toString());
        response.error("error with retrieving build licenses");
        return;
    }
}

From source file:org.opentestsystem.shared.security.domain.SbacUser.java

public SbacUser(final Multimap<String, SbacRole> inUserRoles, final Map<String, String> userAttributes) {
    this.sbacRolesMap = inUserRoles == null ? EMPTY_MAP : ImmutableMap.copyOf(inUserRoles.asMap());
    this.authorities = inUserRoles == null ? EMPTY_LIST
            : SbacRole.calculateGrantedAuthority(inUserRoles.values());
    this.authoritesByTenantId = calculateAuthoritiesByTenantId(inUserRoles);
    Map<String, String> userAttribsToUse = userAttributes;
    if (userAttributes == null) {
        userAttribsToUse = BLANK_USER_ATTRIBS;
    }/* w w w. ja  v a  2s.c  om*/
    firstName = userAttribsToUse.get(FIRST_NAME_KEY);
    lastName = userAttribsToUse.get(LAST_NAME_KEY);
    fullName = userAttribsToUse.get(FULL_NAME_KEY);
    email = userAttribsToUse.get(EMAIL_KEY);
    uniqueId = userAttribsToUse.get(USER_UNIQUE_ID_KEY);
    phoneNumber = userAttribsToUse.get(PHONE_KEY);
}

From source file:eu.uqasar.util.UQasarUtil.java

/**
 * Traverse the tree in postorder and update tree values
 * @param node//from   w ww  . j a v  a  2 s.c  o m
 */
private static void postorder(TreeNode node) {

    if (node == null) {
        return;
    }

    logger.debug("------------postorder: " + node.getName() + "---------------");

    // Iterate the node children
    for (Object o : node.getChildren()) {
        TreeNode nodeChild = (TreeNode) o;
        UQasarUtil.postorder(nodeChild);
    }
    logger.debug("Traversing project tree in postorder..." + node.toString());
    // Update the value
    try {
        InitialContext ic = new InitialContext();
        AdapterDataService adapterDataService = new AdapterDataService();
        TreeNodeService treeNodeService = (TreeNodeService) ic.lookup("java:module/TreeNodeService");

        if (node instanceof Metric) {
            Metric metric = (Metric) node;
            logger.debug("Recomputing the value of the Metric " + node);
            Float value = null;
            if (metric.getMetricSource() == MetricSource.Manual) {
                metric.updateQualityStatus();
            } else {
                value = adapterDataService.getMetricValue(metric.getMetricSource(), metric.getMetricType(),
                        metric.getProject());
                metric.setValue(value);
            }
            metric.setLastUpdated(getLatestTreeUpdateDate());
            metric.addHistoricValue();
            // End Metric node treatment 
        } else if (node instanceof QualityIndicator) {
            logger.info("Recomputing the value of the Quality Indicator " + node);
            QualityIndicator qi = (QualityIndicator) node;
            if (qi.getUseFormula()) {
                String formulaToEval = Formula.parseFormula(qi.getViewFormula());
                if (formulaToEval != null && !formulaToEval.isEmpty()) {

                    Float computedValue = Formula.evalFormula(formulaToEval);
                    if (computedValue != null && !computedValue.isNaN()) {
                        qi.setValue(computedValue);
                        qi.setLastUpdated(getLatestTreeUpdateDate());
                        treeNodeService.update(qi);
                    }

                }
            } else {
                float achieved = 0;
                float denominator = 0;
                for (final TreeNode me : qi.getChildren()) {
                    float weight = ((Metric) me).getWeight();
                    if (me.getQualityStatus() == QualityStatus.Green) {
                        achieved += weight;
                    }
                    denominator += weight;
                }
                if (denominator == 0)
                    qi.getChildren().size();
                qi.setValue(achieved * 100 / denominator);
            }
            qi.setLastUpdated(getLatestTreeUpdateDate());
            qi.addHistoricValue();
            // End Q.Indicator node treatment 
        } else if (node instanceof QualityObjective) {
            logger.info("Recomputing the value of the Quality Objective " + node);
            QualityObjective qo = (QualityObjective) node;
            if (qo.getUseFormula()) {
                String formulaToEval = Formula.parseFormula(qo.getViewFormula());
                if (formulaToEval != null && !formulaToEval.isEmpty()) {

                    Float computedValue = Formula.evalFormula(formulaToEval);
                    if (computedValue != null && !computedValue.isNaN()) {
                        qo.setValue(computedValue);
                        qo.setLastUpdated(getLatestTreeUpdateDate());
                    }

                }
            } else {
                float denominator = 0;
                float achieved = 0;
                for (final TreeNode qi : qo.getChildren()) {
                    float weight = ((QualityIndicator) qi).getWeight();
                    if (qi.getQualityStatus() == QualityStatus.Green) {
                        achieved += weight;
                    }
                    denominator += weight;
                }
                qo.setValue(achieved * 100 / denominator);
            }
            qo.setLastUpdated(getLatestTreeUpdateDate());
            qo.addHistoricValue();
            // End Quality Objective node treatment 
        } else if (node instanceof Project) {
            logger.info("Recomputing the value of the Project " + node);
            Project prj = (Project) node;
            double qoValueSum = 0;
            double denominator = 0;
            for (Object o : node.getChildren()) {
                QualityObjective qo = (QualityObjective) o;
                if (qo.getWeight() == 0) {
                    continue;
                }
                qoValueSum += qo.getValue() * (prj.isFormulaAverage() ? qo.getWeight() : 1);
                denominator += prj.isFormulaAverage() ? qo.getWeight() : 1;
            }

            // bad idea to divide something under 0
            if (denominator == 0) {
                denominator = 1;
            }

            Double computedValue = qoValueSum / denominator;

            if (computedValue != null && !computedValue.isNaN() && !computedValue.isInfinite()) {
                prj.setValue(computedValue);
            }

            prj.setLastUpdated(getLatestTreeUpdateDate());
            prj.addHistoricValue();
            logger.debug(" [" + qoValueSum + "] denominator [" + denominator + "] " + computedValue);
            // End Project node treatment 
        }

        // Get a (possible) suggestion for the tree node
        Multimap<?, ?> suggestions = getSuggestionForNode(node);
        //TODO: take all the suggestions into account
        Object[] types = suggestions.keys().toArray();
        Object[] suggestionsValues = suggestions.values().toArray();
        if (types.length > 0) {
            // for now use the first item as suggestion
            SuggestionType stype = (SuggestionType) types[0];
            node.setSuggestionType(stype);
            if (suggestionsValues[0] != null && !suggestionsValues[0].equals("")) {
                node.setSuggestionValue((String) suggestionsValues[0]);
            }
        }

        treeNodeService.update(node);

    } catch (NamingException e) {
        e.printStackTrace();
    }

    return;
}

From source file:org.xacml4j.v30.pdp.PolicySet.java

/**
 * Gets all combiner parameters for a given policy identifier
 *
 * @param policyId a policy identifier/*  ww  w. j  a va  2s .c o  m*/
 * @return a collection of combiner parameters
 */
public Collection<CombinerParameter> getPolicyCombinerParams(String policyId) {
    Multimap<String, CombinerParameter> p = policyCombinerParameters.get(policyId);
    return (p == null) ? ImmutableList.<CombinerParameter>of() : p.values();
}