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

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

Introduction

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

Prototype

public static <K, V> ImmutableMap<K, V> uniqueIndex(Iterator<V> values, Function<? super V, K> keyFunction) 

Source Link

Document

Returns a map with the given values , indexed by keys derived from those values.

Usage

From source file:org.opentestsystem.authoring.testauth.service.impl.BlueprintValidationHelper.java

/**
 * Handles hierarchical validation for each individual <code>BlueprintElement</code>. This includes:
 * <ul>/*from  ww  w.ja  v a 2  s.c  o  m*/
 * <li>The sum of the child min values must be less than or equal to the parent max</li>
 * <li>The sum of the child max values must be greater than or equal to the parent min</li>
 * </ul>
 */
protected static List<ValidationResult<BlueprintElement>> validateBlueprintHierarchicalRelationships(
        final List<BlueprintElement> blueprintElementList) {
    final List<ValidationResult<BlueprintElement>> errors = Lists.newArrayList();

    if (!CollectionUtils.isEmpty(blueprintElementList)) {
        final List<String> valueMapKeys = Lists
                .newArrayList(blueprintElementList.get(0).getBlueprintElementValueMap().keySet());
        final Map<String, BlueprintElement> blueprintElementMap = Maps.uniqueIndex(blueprintElementList,
                BLUEPRINT_ELEMENT_UNIQUE_KEY_FUNCTION);

        final List<BlueprintElement> filteredChildrenBlueprintElementList = Lists
                .newArrayList(Iterables.filter(blueprintElementList, BLUEPRINT_ELEMENT_CHILD_FILTER));
        final Map<String, Collection<BlueprintElement>> blueprintElementGroupedMap = Multimaps
                .index(filteredChildrenBlueprintElementList, BLUEPRINT_ELEMENT_PARENT_KEY_FUNCTION).asMap();

        for (final Entry<String, Collection<BlueprintElement>> blueprintElementEntry : blueprintElementGroupedMap
                .entrySet()) {
            if (StringUtils.isNotBlank(blueprintElementEntry.getKey())) {
                final BlueprintElement parentBlueprintElement = blueprintElementMap
                        .get(blueprintElementEntry.getKey());
                if (parentBlueprintElement != null) {
                    for (final String valueMapKey : valueMapKeys) {
                        final List<BlueprintElementValue> bpValueList = Lists.transform(
                                Lists.newArrayList(blueprintElementEntry.getValue()),
                                BPE_BPEV_TRANSFORMER.getInstance(valueMapKey));
                        final BlueprintElementValue parentValue = parentBlueprintElement
                                .getBlueprintElementValueMap().get(valueMapKey);
                        final BlueprintElementValue childSummedValue = getActualListSum(bpValueList);

                        if (childSummedValue.getOperationalItemMinValue() > parentValue
                                .getOperationalItemMaxValue()) {
                            errors.add(buildValidationResult(parentBlueprintElement, valueMapKey, OP_MAX_FIELD,
                                    String.format(PARENT_MESSAGE, "OP Max",
                                            parentValue.getOperationalItemMaxValue(), "less", "OP Min",
                                            childSummedValue.getOperationalItemMinValue())));
                        }

                        if (childSummedValue.getOperationalItemMaxValue() < parentValue
                                .getOperationalItemMinValue()) {
                            errors.add(buildValidationResult(parentBlueprintElement, valueMapKey, OP_MIN_FIELD,
                                    String.format(PARENT_MESSAGE, "OP Min",
                                            parentValue.getOperationalItemMinValue(), "greater", "OP Max",
                                            childSummedValue.getOperationalItemMaxValue())));
                        }

                        if (childSummedValue.getFieldTestItemMinValue() > parentValue
                                .getFieldTestItemMaxValue()) {
                            errors.add(buildValidationResult(parentBlueprintElement, valueMapKey, FT_MAX_FIELD,
                                    String.format(PARENT_MESSAGE, "FT Max",
                                            parentValue.getFieldTestItemMaxValue(), "less", "FT Min",
                                            childSummedValue.getFieldTestItemMinValue())));
                        }

                        if (childSummedValue.getFieldTestItemMaxValue() < parentValue
                                .getFieldTestItemMinValue()) {
                            errors.add(buildValidationResult(parentBlueprintElement, valueMapKey, FT_MIN_FIELD,
                                    String.format(PARENT_MESSAGE, "FT Min",
                                            parentValue.getFieldTestItemMinValue(), "greater", "FT Max",
                                            childSummedValue.getFieldTestItemMaxValue())));
                        }
                    }
                }
            }
        }
    }

    return errors;
}

From source file:org.caleydo.view.domino.internal.Bands.java

@Override
public void update() {
    Map<ABandIdentifier, ABand> bak = Maps.uniqueIndex(bands, new Function<ABand, ABandIdentifier>() {
        @Override//from  www  . j ava  2  s  .co  m
        public ABandIdentifier apply(ABand input) {
            return input.getId();
        }
    });
    bands.clear();
    Domino domino = findParent(Domino.class);
    EToolState tool = domino.getTool();
    List<Block> blocks;

    for (Block block : domino.getBlocks()) {
        block.resetHasBands();
    }

    if (tool != EToolState.BANDS)
        blocks = domino.getBlocks();
    else {
        blocks = ImmutableList.copyOf(domino.getSelections().getBlockSelection(SelectionType.SELECTION));
    }

    final int length = blocks.size();

    if (length <= 1)
        return;

    // create bands
    List<Rectangle2D> bounds = new ArrayList<>();
    for (int i = 0; i < length; ++i) {
        final Block block = blocks.get(i);
        block.createBandsTo(blocks.subList(i + 1, length), bands);
        for (LinearBlock b : block.getLinearBlocks())
            b.addBounds(bounds);
    }
    for (int i = 0; i < bounds.size(); ++i) {
        bounds.set(i, shrink(bounds.get(i)));
    }

    // collected the bounds check what we have to stubify
    if (tool != EToolState.BANDS) {
        outer: for (Iterator<ABand> it = bands.iterator(); it.hasNext();) {
            ABand band = it.next();
            for (Rectangle2D bound : bounds) {
                if (band.intersects(bound)) {
                    // if (!band.stubify())
                    it.remove();
                    continue outer;
                }
            }
        }

        // remove rulers and separators
        removeExtraObstacles(domino.getOutlerBlocks());
    }

    for (ABand band : bands) {
        if (bak.containsKey(band.getId())) {
            band.initFrom(bak.get(band.getId()));
        }
        BandIdentifier id = (BandIdentifier) band.getId();
        id.updateBandInfo();
    }

    pickingBandPool.ensure(0, bands.size());
    pickingBandDetailPool.ensure(0, bands.size());

}

From source file:com.romeikat.datamessie.core.base.dao.impl.AbstractEntityWithIdDao.java

@Override
public Map<Long, E> getIdsWithEntities(final SharedSessionContract ssc, final Collection<Long> ids) {
    final List<E> objects = getEntities(ssc, ids);
    final Map<Long, E> result = Maps.uniqueIndex(objects, s -> s.getId());
    return result;
}

From source file:de.metas.ui.web.document.filter.json.JSONDocumentFilter.java

private static DocumentFilter unwrapUsingDescriptor(final JSONDocumentFilter jsonFilter,
        final DocumentFilterDescriptor filterDescriptor) {
    final DocumentFilter.Builder filter = DocumentFilter.builder().setFilterId(jsonFilter.getFilterId());

    final Map<String, JSONDocumentFilterParam> jsonParams = Maps.uniqueIndex(jsonFilter.getParameters(),
            JSONDocumentFilterParam::getParameterName);

    for (final DocumentFilterParamDescriptor paramDescriptor : filterDescriptor.getParameters()) {
        final String parameterName = paramDescriptor.getParameterName();
        final JSONDocumentFilterParam jsonParam = jsonParams.get(parameterName);

        // If parameter is missing: skip it if no required, else throw exception
        if (jsonParam == null) {
            if (paramDescriptor.isMandatory()) {
                throw new IllegalArgumentException("Parameter '" + parameterName + "' was not provided");
            }// w w w . ja  va  2  s. co m
            continue;
        }

        final Object value = paramDescriptor.convertValueFromJson(jsonParam.getValue());
        final Object valueTo = paramDescriptor.convertValueFromJson(jsonParam.getValueTo());

        // If there was no value/valueTo provided: skip it if no required, else throw exception
        if (value == null && valueTo == null) {
            if (paramDescriptor.isMandatory()) {
                throw new IllegalArgumentException("Parameter '" + parameterName + "' has no value");
            }
            continue;
        }

        filter.addParameter(DocumentFilterParam.builder().setFieldName(paramDescriptor.getFieldName())
                .setOperator(paramDescriptor.getOperator()).setValue(value).setValueTo(valueTo).build());
    }

    for (final DocumentFilterParam internalParam : filterDescriptor.getInternalParameters()) {
        filter.addInternalParameter(internalParam);
    }

    return filter.build();
}

From source file:alluxio.master.BackupManager.java

/**
 * Restores master state from the specified backup.
 *
 * @param is an input stream to read from the backup
 *///from  w ww  .  java 2 s.c o  m
public void initFromBackup(InputStream is) throws IOException {
    int count = 0;
    try (GzipCompressorInputStream gzIn = new GzipCompressorInputStream(is);
            JournalEntryStreamReader reader = new JournalEntryStreamReader(gzIn)) {
        List<Master> masters = mRegistry.getServers();
        JournalEntry entry;
        Map<String, Master> mastersByName = Maps.uniqueIndex(masters, Master::getName);
        while ((entry = reader.readEntry()) != null) {
            String masterName = JournalEntryAssociation.getMasterForEntry(entry);
            Master master = mastersByName.get(masterName);
            master.processJournalEntry(entry);
            try (JournalContext jc = master.createJournalContext()) {
                jc.append(entry);
                count++;
            }
        }
    }
    LOG.info("Restored {} entries from backup", count);
}

From source file:com.thinkbiganalytics.discovery.model.AbstractSchema.java

@JsonIgnore
public Map<String, Field> getFieldsAsMap() {
    Map<String, Field> map = new HashMap<>();
    if (fields != null) {
        map = Maps.uniqueIndex(fields, new Function<Field, String>() {
            @Nullable/*from w w  w  .ja  v  a  2 s.  c om*/
            @Override
            public String apply(@Nullable Field field) {
                return field.getName();
            }
        });
    }
    return map;
}

From source file:groovyx.gpars.benchmark.caliper.chart.ChartBuilder.java

@Override
public void handleResults(final Run run) {
    this.run = run;
    final Map<String, VM> vms = Maps.uniqueIndex(run.vms, VM_LOCAL_NAME_FUNCTION);
    this.scenarioLocalVars = HashBasedTable.create();
    for (final Scenario scenario : run.scenarios) {
        final ScenarioName scenarioName = new ScenarioName(scenario.localName);
        scenarioLocalVars.put(scenarioName, new AxisName("benchmark"),
                new AxisValue(scenario.benchmarkMethodName));
        scenarioLocalVars.put(scenarioName, new AxisName("vm"),
                new AxisValue(vms.get(scenario.vmLocalName).vmName));
        for (final Entry<String, String> entry : scenario.userParameters.entrySet()) {
            scenarioLocalVars.put(scenarioName, new AxisName(entry.getKey()), new AxisValue(entry.getValue()));
        }/*w ww  .j  a  v a  2s .  c om*/
        for (final Entry<String, String> entry : scenario.vmArguments.entrySet()) {
            scenarioLocalVars.put(scenarioName, new AxisName(entry.getKey()), new AxisValue(entry.getValue()));
        }
    }

    for (final Instrument instrument : run.instruments) {
        displayResults(instrument);
    }
}

From source file:de.metas.ui.web.window.datatypes.json.filters.JSONDocumentFilter.java

private static DocumentFilter unwrapUsingDescriptor(final JSONDocumentFilter jsonFilter,
        final DocumentFilterDescriptor filterDescriptor) {
    final DocumentFilter.Builder filter = DocumentFilter.builder().setFilterId(jsonFilter.getFilterId());

    final Map<String, JSONDocumentFilterParam> jsonParams = Maps.uniqueIndex(jsonFilter.getParameters(),
            jsonParam -> jsonParam.getParameterName());

    for (final DocumentFilterParamDescriptor paramDescriptor : filterDescriptor.getParameters()) {
        final String parameterName = paramDescriptor.getParameterName();
        final JSONDocumentFilterParam jsonParam = jsonParams.get(parameterName);

        // If parameter is missing: skip it if no required, else throw exception
        if (jsonParam == null) {
            if (paramDescriptor.isMandatory()) {
                throw new IllegalArgumentException("Parameter '" + parameterName + "' was not provided");
            }// www. j  a v  a2 s .  c o m
            continue;
        }

        final Object value = paramDescriptor.convertValueFromJson(jsonParam.getValue());
        final Object valueTo = paramDescriptor.convertValueFromJson(jsonParam.getValueTo());

        // If there was no value/valueTo provided: skip it if no required, else throw exception
        if (value == null && valueTo == null) {
            if (paramDescriptor.isMandatory()) {
                throw new IllegalArgumentException("Parameter '" + parameterName + "' has no value");
            }
            continue;
        }

        filter.addParameter(DocumentFilterParam.builder().setFieldName(paramDescriptor.getFieldName())
                .setOperator(paramDescriptor.getOperator()).setValue(value).setValueTo(valueTo).build());
    }

    for (final DocumentFilterParam internalParam : filterDescriptor.getInternalParameters()) {
        filter.addParameter(internalParam);
    }

    return filter.build();
}

From source file:com.netflix.paas.cassandra.tasks.ClusterDiscoveryTask.java

@Override
public void execte(TaskContext context) throws Exception {
    // Get complete set of existing clusters from the discovery service
    Collection<String> clusters = Sets.newHashSet(discoveryService.getClusterNames());
    LOG.info(clusters.toString());/*www  .j  av a  2  s.  com*/

    // Load entire list of previously known clusters to a map of <ClusterName> => <ClusterEntity>
    Map<String, CassandraClusterEntity> existingClusters = Maps.uniqueIndex(this.clusterDao.list(),
            new Function<CassandraClusterEntity, String>() {
                @Override
                public String apply(CassandraClusterEntity cluster) {
                    LOG.info("Found existing cluster : " + cluster.getClusterName());
                    return cluster.getClusterName();
                }
            });

    // Iterate through new list of clusters and look for changes
    for (String clusterName : clusters) {
        CassandraClusterEntity entity = existingClusters.get(clusterName);

        // This is a new cluster
        if (entity == null) {
            LOG.info("Found new cluster : " + clusterName);

            entity = CassandraClusterEntity.builder().withName(clusterName).withIsEnabled(true)
                    .withDiscoveryType(discoveryService.getName()).build();

            try {
                clusterDao.write(entity);
            } catch (Exception e) {
                LOG.warn("Failed to persist cluster info for '{}'", new Object[] { clusterName, e });
            }

            updateCluster(entity);
        }

        // We knew about it before and it is disabled
        else if (!entity.isEnabled()) {
            LOG.info("Cluster '{}' is disabled and will not be refreshed", new Object[] { clusterName });
        }

        // Refresh the info for an existing cluster
        else {
            LOG.info("Cluster '{}' is being refreshed", new Object[] { clusterName });
            if (entity.getDiscoveryType() == null) {
                entity.setDiscoveryType(discoveryService.getName());
                try {
                    clusterDao.write(entity);
                } catch (Exception e) {
                    LOG.warn("Failed to persist cluster info for '{}'", new Object[] { clusterName, e });
                }
            }

            updateCluster(entity);
        }
    }
}

From source file:com.facebook.presto.util.IterableTransformer.java

public <K> MapTransformer<K, E> uniqueIndex(Function<? super E, K> keyFunction) {
    return new MapTransformer<>(Maps.uniqueIndex(iterable, keyFunction));
}