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:com.android.tools.idea.gradle.editor.ui.ReferencedValuesGradleEditorComponent.java

public void bind(@NotNull Project project, @NotNull List<GradleEditorSourceBinding> sourceBindings) {
    myProjectRef = new WeakReference<Project>(project);
    ImmutableListMultimap<VirtualFile, GradleEditorSourceBinding> byFile = Multimaps.index(sourceBindings,
            GROUPER);/*w  ww.ja  v a 2  s. co m*/
    List<VirtualFile> orderedFiles = Lists.newArrayList(byFile.keySet());
    ContainerUtil.sort(orderedFiles, FILES_COMPARATOR);
    for (VirtualFile file : orderedFiles) {
        ImmutableList<GradleEditorSourceBinding> list = byFile.get(file);
        List<RangeMarker> rangeMarkers = Lists.newArrayList();
        for (GradleEditorSourceBinding descriptor : list) {
            rangeMarkers.add(descriptor.getRangeMarker());
        }
        if (!rangeMarkers.isEmpty()) {
            ContainerUtil.sort(rangeMarkers, RANGE_COMPARATOR);
            String name = getRepresentativeName(project, file);
            mySourceBindings.put(name, rangeMarkers);
            myFilesByName.put(name, file);
        }
    }
}

From source file:org.sentilo.platform.server.handler.impl.CatalogAlertHandler.java

/**
 * Group alerts list by type (INTERNAL or EXTERNAL)
 * //from   w  ww .  j a  va2 s.c  o  m
 * @param alerts
 * @return
 */
protected Multimap<String, CatalogAlert> groupAlertsByType(final List<CatalogAlert> alerts) {
    final Function<CatalogAlert, String> internalFunction = new Function<CatalogAlert, String>() {

        @Override
        public String apply(final CatalogAlert alert) {
            // alert type could be null if it is wrong, so return empty string if it is null
            return (alert.getType() != null ? alert.getType() : "");
        }
    };
    return Multimaps.index(alerts, internalFunction);
}

From source file:com.ngdata.hbaseindexer.indexer.Indexer.java

/**
 * groups a list of ids by shard//from  ww  w .  j ava 2s  .co m
 * (consider moving this to a BaseSharder class)
 */
private Map<Integer, Collection<String>> shardByValue(List<String> idsToDelete) {
    Multimap<Integer, String> map = Multimaps.index(idsToDelete, new Function<String, Integer>() {
        @Override
        public Integer apply(@Nullable String id) {
            try {
                return sharder.getShard(id);
            } catch (SharderException e) {
                throw new RuntimeException("error calculating hash", e);
            }
        }
    });
    return map.asMap();
}

From source file:org.sleuthkit.autopsy.report.TableReportGenerator.java

/**
 * Generate the tables for the selected blackboard artifacts
 *//*from w w w.ja va 2 s  .  c om*/
private void makeBlackboardArtifactTables() {
    // Make a comment string describing the tag names filter in effect. 
    String comment = "";
    if (!tagNamesFilter.isEmpty()) {
        comment += NbBundle.getMessage(this.getClass(), "ReportGenerator.artifactTable.taggedResults.text");
        comment += makeCommaSeparatedList(tagNamesFilter);
    }

    // Add a table to the report for every enabled blackboard artifact type.
    for (BlackboardArtifact.Type type : artifactTypes) {
        // Check for cancellaton.

        if (progressPanel.getStatus() == ReportProgressPanel.ReportStatus.CANCELED) {
            return;
        }

        progressPanel.updateStatusLabel(NbBundle.getMessage(this.getClass(),
                "ReportGenerator.progress.processing", type.getDisplayName()));

        // Keyword hits and hashset hit artifacts get special handling.
        if (type.getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_KEYWORD_HIT.getTypeID()) {
            writeKeywordHits(tableReport, comment, tagNamesFilter);
            continue;
        } else if (type.getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_HASHSET_HIT.getTypeID()) {
            writeHashsetHits(tableReport, comment, tagNamesFilter);
            continue;
        }

        List<ArtifactData> artifactList = getFilteredArtifacts(type, tagNamesFilter);

        if (artifactList.isEmpty()) {
            continue;
        }

        /* TSK_ACCOUNT artifacts get grouped by their TSK_ACCOUNT_TYPE
         * attribute, and then handed off to the standard method for writing
         * tables. */
        if (type.getTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_ACCOUNT.getTypeID()) {
            //Group account artifacts by their account type
            ListMultimap<String, ArtifactData> groupedArtifacts = Multimaps.index(artifactList,
                    artifactData -> {
                        try {
                            return artifactData.getArtifact()
                                    .getAttribute(new BlackboardAttribute.Type(
                                            BlackboardAttribute.ATTRIBUTE_TYPE.TSK_ACCOUNT_TYPE))
                                    .getValueString();
                        } catch (TskCoreException ex) {
                            logger.log(Level.SEVERE,
                                    "Unable to get value of TSK_ACCOUNT_TYPE attribute. Defaulting to \"unknown\"",
                                    ex);
                            return "unknown";
                        }
                    });
            for (String accountType : groupedArtifacts.keySet()) {
                /* If the report is a ReportHTML, the data type name
                 * eventualy makes it to useDataTypeIcon which expects but
                 * does not require a artifact name, so we make a synthetic
                 * compund name by appending a ":" and the account type.
                 */
                final String compundDataTypeName = BlackboardArtifact.ARTIFACT_TYPE.TSK_ACCOUNT.getDisplayName()
                        + ": " + accountType;
                writeTableForDataType(new ArrayList<>(groupedArtifacts.get(accountType)), type,
                        compundDataTypeName, comment);
            }
        } else {
            //all other artifact types are sent to writeTableForDataType directly
            writeTableForDataType(artifactList, type, type.getDisplayName(), comment);
        }
    }
}

From source file:de.faustedition.genesis.lines.VerseManager.java

public ImmutableListMultimap<MaterialUnit, GraphVerseInterval> indexByMaterialUnit(
        Iterable<GraphVerseInterval> verseIntervals) {

    Function materialUnitOfVerseInterval = new Function<GraphVerseInterval, MaterialUnit>() {
        @Override//from   www  . j a  v  a 2s.com
        public MaterialUnit apply(@Nullable GraphVerseInterval input) {
            return transcriptManager.materialUnitForTranscript(input.getTranscript(textRepository));
        }
    };

    return Multimaps.index(verseIntervals, materialUnitOfVerseInterval);
}

From source file:org.impressivecode.depress.mg.po.PeopleOrganizationMetricProcessor.java

private ImmutableListMultimap<String, String> groupByOrganization(final ChangeData change) {
    ImmutableListMultimap<String, String> indexed = Multimaps.index(change.getInvolvedEngineers(),
            new Function<String, String>() {
                @Override/*from ww w.ja  va2  s . c  om*/
                public String apply(final String name) {
                    return engineersData.get(name).getOrganizationPath();
                }
            });
    return indexed;
}

From source file:brooklyn.entity.network.bind.BindDnsServerImpl.java

public void update() {
    Lifecycle serverState = getAttribute(Attributes.SERVICE_STATE_ACTUAL);
    if (Lifecycle.STOPPED.equals(serverState) || Lifecycle.STOPPING.equals(serverState)
            || Lifecycle.DESTROYED.equals(serverState) || !getAttribute(Attributes.SERVICE_UP)) {
        LOG.debug("Skipped update of {} when service state is {} and running is {}",
                new Object[] { this, getAttribute(Attributes.SERVICE_STATE_ACTUAL), getAttribute(SERVICE_UP) });
        return;//from w  w  w  .  j  a  v a  2 s .c  om
    }
    synchronized (this) {
        Iterable<Entity> availableEntities = FluentIterable.from(getEntities().getMembers())
                .filter(new HasHostnameAndValidLifecycle());
        LOG.debug("{} updating with entities: {}", this, Iterables.toString(availableEntities));
        ImmutableListMultimap<String, Entity> hostnameToEntity = Multimaps.index(availableEntities,
                new HostnameTransformer());

        Map<String, String> octetToName = Maps.newHashMap();
        BiMap<String, String> ipToARecord = HashBiMap.create();
        Multimap<String, String> aRecordToCnames = MultimapBuilder.hashKeys().hashSetValues().build();
        Multimap<String, String> ipToAllNames = MultimapBuilder.hashKeys().hashSetValues().build();

        for (Map.Entry<String, Entity> e : hostnameToEntity.entries()) {
            String domainName = e.getKey();
            Maybe<SshMachineLocation> location = Machines
                    .findUniqueSshMachineLocation(e.getValue().getLocations());
            if (!location.isPresent()) {
                LOG.debug("Member {} of {} does not have an SSH location so will not be configured",
                        e.getValue(), this);
                continue;
            } else if (ipToARecord.inverse().containsKey(domainName)) {
                continue;
            }

            String address = location.get().getAddress().getHostAddress();
            ipToAllNames.put(address, domainName);
            if (!ipToARecord.containsKey(address)) {
                ipToARecord.put(address, domainName);
                if (getReverseLookupNetwork().contains(new Cidr(address + "/32"))) {
                    String octet = Iterables.get(Splitter.on('.').split(address), 3);
                    if (!octetToName.containsKey(octet))
                        octetToName.put(octet, domainName);
                }
            } else {
                aRecordToCnames.put(ipToARecord.get(address), domainName);
            }
        }
        setAttribute(A_RECORDS, ImmutableMap.copyOf(ipToARecord.inverse()));
        setAttribute(PTR_RECORDS, ImmutableMap.copyOf(octetToName));
        setAttribute(CNAME_RECORDS, Multimaps.unmodifiableMultimap(aRecordToCnames));
        setAttribute(ADDRESS_MAPPINGS, Multimaps.unmodifiableMultimap(ipToAllNames));

        // Update Bind configuration files and restart the service
        getDriver().updateBindConfiguration();
    }
}

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

/**
 * validate dictionary values//ww w  . j  a v a 2 s  . c om
 */
private <N extends Number> void validateDictionaryValues(
        final ComputationRuleParameter computationRuleParameter,
        final List<ScoringRuleDictionaryElement> dictionaryValues, final Errors errors) {
    final ComputationRuleType fieldType = computationRuleParameter.getComputationRuleType();
    final String paramName = computationRuleParameter.getParameterName();
    if (CollectionUtils.isEmpty(dictionaryValues)) {
        rejectValue(errors, DICTIONARY, getErrorMessageRoot() + DICTIONARY + MSG_REQUIRED, fieldType,
                paramName);
    }

    final Map<String, Collection<ScoringRuleDictionaryElement>> duplicates = Maps.filterEntries(
            Multimaps.index(dictionaryValues, DICTIONARY_ELEMENT_TO_KEY_TRANSFORMER).asMap(),
            KEY_DUPLICATE_FILTER);
    if (!duplicates.isEmpty()) {
        rejectValue(errors, DICTIONARY, getErrorMessageRoot() + DICTIONARY + MSG_DUPLICATES, paramName,
                duplicates.keySet().toString());
    }

    for (int i = 0; i < dictionaryValues.size(); i++) {
        final ScoringRuleDictionaryElement scoringRuleDictionaryElement = dictionaryValues.get(i);
        String key = scoringRuleDictionaryElement.getKey();
        final String value = scoringRuleDictionaryElement.getValue();
        try {
            errors.pushNestedPath(DICTIONARY + "[" + i + "]");

            final DictionaryIndexType dictionaryIndex = computationRuleParameter.getDictionaryIndexType();

            final boolean indexIsInteger = dictionaryIndex == DictionaryIndexType.INTEGER;
            if (!rejectIfEmpty(key, errors, KEY, getErrorMessageRoot() + DICTIONARY_KEY,
                    indexIsInteger ? MAX_PARSEABLE_LENGTH : MAX_STRING_LENGTH, fieldType, paramName, i + 1)
                    && indexIsInteger) {
                if (!StringUtils.isNumeric(key)) {
                    rejectValue(errors, KEY, getErrorMessageRoot() + DICTIONARY_KEY + MSG_INVALID, fieldType,
                            paramName, key, dictionaryIndex);
                }
            }

            key = StringUtils.defaultIfBlank(key, String.valueOf(i + 1));

            final boolean valueIsNumeric = NUMERIC_TYPES.contains(fieldType);
            if (!rejectIfEmpty(value, errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE,
                    valueIsNumeric ? MAX_PARSEABLE_LENGTH : MAX_STRING_LENGTH, fieldType, paramName, key)
                    && valueIsNumeric) {
                final String min = computationRuleParameter.getMinimumValue();
                final String max = computationRuleParameter.getMaximumValue();
                try {
                    if (fieldType == ComputationRuleType.FLOAT) {
                        final Float floatValue = Float.parseFloat(value);
                        final Range<Float> floatRange = buildFloatRange(min, max);
                        if (floatRange != null && !floatRange.contains(floatValue)) {
                            rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_RANGE,
                                    fieldType, paramName, key, min, max);
                        }
                    } else {
                        final Long longValue = Long.parseLong(value);
                        final Range<Long> longRange = buildLongRange(min, max);
                        if (longRange != null && !longRange.contains(longValue)) {
                            rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_RANGE,
                                    fieldType, paramName, key, min, max);
                        }
                    }
                } catch (final NumberFormatException e) {
                    rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_PARSEABLE_NUMBER,
                            fieldType, paramName, key, value);
                }
            } else if (ComputationRuleType.BOOLEAN.equals(fieldType)
                    && !Boolean.FALSE.toString().equals(value.toString())
                    && !Boolean.TRUE.toString().equals(value.toString())) {
                rejectValue(errors, VALUE, getErrorMessageRoot() + DICTIONARY_VALUE + MSG_PARSEABLE_BOOLEAN,
                        fieldType, paramName, key, value);
            }
        } finally {
            errors.popNestedPath();
        }
    }
}

From source file:dagger.internal.codegen.ContributionBinding.java

/**
 * Indexes map-multibindings by map key (the result of calling
 * {@link AnnotationValue#getValue()} on a single member or the whole {@link AnnotationMirror}
 * itself, depending on {@link MapKey#unwrapValue()}).
 *///from www  .  j a va 2 s  .co  m
static ImmutableSetMultimap<Object, ContributionBinding> indexMapBindingsByMapKey(
        Set<ContributionBinding> mapBindings) {
    return ImmutableSetMultimap.copyOf(Multimaps.index(mapBindings, mapBinding -> {
        AnnotationMirror mapKey = mapBinding.mapKey().get();
        return unwrapValue(mapKey).map(AnnotationValue::getValue).orElse(mapKey);
    }));
}

From source file:edu.harvard.med.screensaver.model.screens.LibraryScreening.java

@Transient
public SortedSet<LibraryPlate> getLibraryPlatesScreened() {
    Multimap<Integer, AssayPlate> index = Multimaps.index(getAssayPlatesScreened(),
            new Function<AssayPlate, Integer>() {
                @Override/*from   w  w w.  j  ava 2  s  .  c  o  m*/
                public Integer apply(AssayPlate p) {
                    return p.getPlateNumber();
                }
            });
    SortedSet<LibraryPlate> libraryPlates = Sets.newTreeSet();
    for (Integer plateNumber : index.keySet()) {
        Set<AssayPlate> assayPlates = Sets.newHashSet(index.get(plateNumber));
        libraryPlates.add(new LibraryPlate(plateNumber,
                assayPlates.iterator().next().getPlateScreened().getCopy().getLibrary(), assayPlates));
    }
    return libraryPlates;
}