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:com.b2international.index.mapping.DocumentMapping.java

DocumentMapping(DocumentMapping parent, Class<?> type) {
    this.parent = parent;
    this.type = type;
    final String typeAsString = getType(type);
    this.typeAsString = parent == null ? typeAsString : parent.typeAsString() + DELIMITER + typeAsString;
    this.fieldMap = FluentIterable.from(Reflections.getFields(type)).filter(new Predicate<Field>() {
        @Override//from  ww  w  .  ja va2s  .c  om
        public boolean apply(Field field) {
            return !Modifier.isStatic(field.getModifiers());
        }
    }).uniqueIndex(GET_NAME);

    final Builder<String, Text> textFields = ImmutableSortedMap.naturalOrder();
    final Builder<String, Keyword> keywordFields = ImmutableSortedMap.naturalOrder();

    for (Field field : getFields()) {
        for (Text analyzer : field.getAnnotationsByType(Text.class)) {
            if (Strings.isNullOrEmpty(analyzer.alias())) {
                textFields.put(field.getName(), analyzer);
            } else {
                textFields.put(DELIMITER_JOINER.join(field.getName(), analyzer.alias()), analyzer);
            }
        }
        for (Keyword analyzer : field.getAnnotationsByType(Keyword.class)) {
            if (Strings.isNullOrEmpty(analyzer.alias())) {
                keywordFields.put(field.getName(), analyzer);
            } else {
                keywordFields.put(DELIMITER_JOINER.join(field.getName(), analyzer.alias()), analyzer);
            }
        }
    }

    this.textFields = new TreeMap<>(textFields.build());
    this.keywordFields = new TreeMap<>(keywordFields.build());

    // @RevisionHash should be directly present, not inherited
    final RevisionHash revisionHash = type.getDeclaredAnnotation(RevisionHash.class);
    if (revisionHash != null) {
        this.hashedFields = ImmutableSortedSet.copyOf(revisionHash.value());
    } else {
        this.hashedFields = ImmutableSortedSet.of();
    }

    this.nestedTypes = FluentIterable.from(getFields()).transform(new Function<Field, Class<?>>() {
        @Override
        public Class<?> apply(Field field) {
            if (Reflections.isMapType(field)) {
                return Map.class;
            } else {
                return Reflections.getType(field);
            }
        }
    }).filter(new Predicate<Class<?>>() {
        @Override
        public boolean apply(Class<?> fieldType) {
            return isNestedDoc(fieldType);
        }
    }).toMap(new Function<Class<?>, DocumentMapping>() {
        @Override
        public DocumentMapping apply(Class<?> input) {
            return new DocumentMapping(
                    DocumentMapping.this.parent == null ? DocumentMapping.this : DocumentMapping.this.parent,
                    input);
        }
    });

    this.scripts = Maps.uniqueIndex(getScripts(type), Script::name);
}

From source file:org.sonar.server.measure.ws.ComponentTreeSort.java

private static Ordering<ComponentDto> metricPeriodOrdering(ComponentTreeWsRequest wsRequest,
        List<MetricDto> metrics,
        Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
    if (wsRequest.getMetricSort() == null || wsRequest.getMetricPeriodSort() == null) {
        return componentNameOrdering(wsRequest.getAsc());
    }//w w  w .ja v a 2  s.c o m
    Map<String, MetricDto> metricsByKey = Maps.uniqueIndex(metrics, MetricDto::getKey);
    MetricDto metric = metricsByKey.get(wsRequest.getMetricSort());

    ValueType metricValueType = ValueType.valueOf(metric.getValueType());
    if (NUMERIC_VALUE_TYPES.contains(metricValueType)) {
        return numericalMetricPeriodOrdering(wsRequest, metric, measuresByComponentUuidAndMetric);
    }

    throw BadRequestException
            .create(format("Impossible to sort metric '%s' by measure period.", metric.getKey()));
}

From source file:org.jasig.cas.authentication.LdapAuthenticationHandler.java

/**
 * Sets the mapping of additional principal attributes where the key and value is the LDAP attribute
 * name. Note that the principal ID attribute
 * should not be listed among these attributes.
 *
 * @param attributeList List of LDAP attribute names
 *///from  w ww.  j  av  a  2 s.  com
public void setPrincipalAttributeList(final List<String> attributeList) {
    this.principalAttributeMap = Maps.uniqueIndex(attributeList, Functions.toStringFunction());
}

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

private void setupEffectiveTenantsForRoles(final List<SbacRole> roleList) {
    final Map<String, SbacRole> roleNameMap = Maps.uniqueIndex(
            Iterables.filter(roleList, ROLE_APPLICABLE_TO_COMPONENT_FILTER), ROLE_NAME_MAP_TRANSFORMER);

    for (final Map.Entry<String, SbacRole> roleMapEntry : roleNameMap.entrySet()) {
        SbacRole role = roleMapEntry.getValue();
        final List<Tenant> tenantsComponentRole = getApplicableTenants(Sets.newHashSet(role.getEntities()));

        // may not always be present due to tenancy roles
        if (tenantsComponentRole != null) {
            Collections.sort(tenantsComponentRole, Collections.reverseOrder(new Tenant.TenantTypeComparator()));
            for (Tenant tenant : tenantsComponentRole) {
                if (role.getEffectiveEntity().getEntityType().equals(tenant.getType())
                        && role.getEffectiveEntity().getEntityId().equals(tenant.getName())) {
                    //first check to see if the effective entity (the one the role is assigned at) has a valid tenant)
                    //if so, just use that one
                    roleMapEntry.getValue().setEffectiveTenant(tenant);
                } else if (!TenantType.CLIENT.equals(tenant.getType())) {
                    //otherwise 'walk the tenant tree' to see if there is a non-client tenant that matches the roles hierarchy.
                    for (SbacEntity entity : role.getEntities()) {
                        if (entity.getEntityId() != null && entity.getEntityId().equals(tenant.getName())
                                && entity.getEntityType().equals(tenant.getType())) {
                            //build a new tenant (since one wasn't matched) with the roles effective tenant level,
                            //but with the subscription details from the matched tenant higher in the hierarchy.
                            Tenant newTenant = new Tenant();
                            newTenant.setTenantSubscriptions(tenant.getTenantSubscriptions());
                            newTenant.setId(role.getEffectiveEntity().getEntityId());
                            newTenant.setName(role.getEffectiveEntity().getEntityName());
                            newTenant.setType(role.getEffectiveEntity().getEntityType());
                            roleMapEntry.getValue().setEffectiveTenant(newTenant);
                        }/*from   w w  w.  j a  va  2s. c o m*/
                    }
                }
            }
        }
    }
}

From source file:org.isisaddons.module.security.dom.permission.ApplicationPermissions.java

/**
 * Uses the {@link org.apache.isis.applib.services.queryresultscache.QueryResultsCache} in order to support
 * multiple lookups from <code>org.isisaddons.module.security.app.user.UserPermissionViewModel</code>.
 *///from w  w w . j av  a2s.c  o m
@Programmatic
public ApplicationPermission findByUserAndPermissionValue(final String username,
        final ApplicationPermissionValue permissionValue) {

    // obtain all permissions for this user, map by its value, and
    // put into query cache (so that this method can be safely called in a tight loop)
    final Map<ApplicationPermissionValue, ApplicationPermission> permissions = queryResultsCache
            .execute(new Callable<Map<ApplicationPermissionValue, ApplicationPermission>>() {
                @Override
                public Map<ApplicationPermissionValue, ApplicationPermission> call() throws Exception {
                    final List<ApplicationPermission> applicationPermissions = findByUser(username);
                    return Maps.uniqueIndex(applicationPermissions, ApplicationPermission.Functions.AS_VALUE);
                }
            }, ApplicationPermissions.class, "findByUserAndPermissionValue", username);

    // now simply return the permission from the required value (if it exists)
    return permissions.get(permissionValue);
}

From source file:com.b2international.snowowl.snomed.datastore.taxonomy.SnomedTaxonomyUpdateRunnable.java

@Override
public void run() {

    LOGGER.trace("Processing changes taxonomic information.");

    //here we have to consider changes triggered by repository state revert
    //this point the following might happen:
    //SNOMED CT concept and/or relationship will be contained by both deleted and new collections
    //with same business (SCT ID) but different primary ID (CDO ID) [this is the way how we handle object resurrection]
    //we decided, to order changes by primary keys. as primary IDs are provided in sequence, one could assume
    //that the larger primary ID happens later, and that is the truth

    //but as deletion always happens later than addition, we only have to take care of deletion
    //so if the deletion is about to erase something that has the same SCT ID but more recent (larger) 
    //primary key, we just ignore it when building the taxonomy.

    final Iterable<Concept> newConcepts = commitChangeSet.getNewComponents(Concept.class);
    final Iterable<Concept> dirtyConcepts = commitChangeSet.getDirtyComponents(Concept.class);
    final Iterable<CDOID> deletedConceptStorageKeys = commitChangeSet
            .getDetachedComponents(SnomedPackage.Literals.CONCEPT);
    final Iterable<Relationship> newRelationships = commitChangeSet.getNewComponents(Relationship.class);
    final Iterable<Relationship> dirtyRelationships = commitChangeSet.getDirtyComponents(Relationship.class);
    final Iterable<CDOID> deletedRelationships = commitChangeSet
            .getDetachedComponents(SnomedPackage.Literals.RELATIONSHIP);

    //SCT ID - relationships
    final Map<String, Relationship> _newRelationships = Maps
            .newHashMap(Maps.uniqueIndex(newRelationships, GET_SCT_ID_FUNCTION));

    //SCT ID - concepts
    final Map<String, Concept> _newConcepts = Maps
            .newHashMap(Maps.uniqueIndex(newConcepts, GET_SCT_ID_FUNCTION));

    for (final Relationship newRelationship : newRelationships) {
        taxonomyBuilder.addEdge(createEdge(newRelationship));
    }//from   w ww.  jav a2 s.  c  om

    for (final Relationship dirtyRelationship : dirtyRelationships) {
        taxonomyBuilder.addEdge(createEdge(dirtyRelationship));
    }

    // lookup all deleted relationship documents
    final Iterable<SnomedRelationshipIndexEntry> deletedRelationshipEntries;
    try {
        deletedRelationshipEntries = searcher.get(SnomedRelationshipIndexEntry.class,
                CDOIDUtils.createCdoIdToLong(deletedRelationships));
    } catch (IOException e) {
        throw new SnowowlRuntimeException(e);
    }

    for (final SnomedRelationshipIndexEntry relationship : deletedRelationshipEntries) {
        final String relationshipId = relationship.getId();
        //same relationship as new and detached
        if (_newRelationships.containsKey(relationshipId)) {
            final Relationship newRelationship = _newRelationships.get(relationshipId);
            final String typeId = newRelationship.getType().getId();
            //ignore everything but IS_As
            if (Concepts.IS_A.equals(typeId)) {
                //check source and destination as well
                if (relationship.getSourceId().equals(newRelationship.getSource().getId())
                        && relationship.getDestinationId().equals(newRelationship.getDestination().getId())) {

                    //and if the new relationship has more recent (larger CDO ID), ignore deletion
                    if (CDOIDUtils.asLong(newRelationship.cdoID()) > relationship.getStorageKey()) {
                        continue;
                    }
                }
            }
        }
        taxonomyBuilder.removeEdge(createEdge(relationship));
    }
    for (final Concept newConcept : newConcepts) {
        taxonomyBuilder.addNode(createNode(newConcept));
    }

    try {
        final Iterable<SnomedConceptDocument> deletedConcepts = searcher.get(SnomedConceptDocument.class,
                CDOIDUtils.createCdoIdToLong(deletedConceptStorageKeys));
        for (final SnomedConceptDocument concept : deletedConcepts) {
            //consider the same as for relationship
            //we have to decide if deletion is the 'stronger' modification or not
            final String conceptId = concept.getId();

            //same concept as addition and deletion
            if (_newConcepts.containsKey(conceptId)) {
                final Concept newConcept = _newConcepts.get(conceptId);
                //check whether new concept has more recent (larger CDO ID) or not, ignore deletion
                if (CDOIDUtils.asLong(newConcept.cdoID()) > concept.getStorageKey()) {
                    continue;
                }
            }
            //else delete it
            taxonomyBuilder.removeNode(createDeletedNode(conceptId));
        }
    } catch (IOException e) {
        throw new SnowowlRuntimeException(e);
    }

    for (final Concept dirtyConcept : dirtyConcepts) {
        final CDORevisionDelta revisionDelta = commitChangeSet.getRevisionDeltas().get(dirtyConcept.cdoID());
        if (revisionDelta == null) {
            continue;
        }
        final CDOFeatureDelta changeStatusDelta = revisionDelta
                .getFeatureDelta(SnomedPackage.Literals.COMPONENT__ACTIVE);
        if (changeStatusDelta instanceof CDOSetFeatureDelta) {
            CDOSetFeatureDelta delta = (CDOSetFeatureDelta) changeStatusDelta;
            final Boolean oldValue;
            if (delta.getOldValue() instanceof Boolean) {
                oldValue = (Boolean) delta.getOldValue();
            } else if (CDOSetFeatureDelta.UNSPECIFIED == delta.getOldValue()) {
                oldValue = false;
            } else {
                throw new RuntimeException("Unknown old value type: " + delta.getOldValue());
            }
            final Boolean newValue = (Boolean) delta.getValue();
            if (Boolean.TRUE == oldValue && Boolean.FALSE == newValue) {
                //nothing can be dirty and new at the same time
                //we do not need this concept. either it was deactivated now or sometime earlier.
                taxonomyBuilder.removeNode(createNode(dirtyConcept.getId(), true));
            } else if (Boolean.FALSE == oldValue && Boolean.TRUE == newValue) {
                //consider reverting inactivation
                if (!taxonomyBuilder.containsNode(dirtyConcept.getId())) {
                    taxonomyBuilder.addNode(createNode(dirtyConcept));
                }
            }
        }
    }
    LOGGER.trace("Rebuilding taxonomic information based on the changes.");
    this.status = taxonomyBuilder.build();
}

From source file:be.nbb.demetra.dotstat.DotStatAccessor.java

@VisibleForTesting
static Map<String, Dimension> dimensionById(DataStructure ds) {
    return Maps.uniqueIndex(ds.getDimensions(), new Function<Dimension, String>() {
        @Override/*from  ww w .  ja va2  s .co  m*/
        public String apply(Dimension input) {
            return input.getId();
        }
    });
}

From source file:com.siemens.sw360.commonIO.TypeMappings.java

@NotNull
public static <T, U> Map<U, T> getIdentifierToTypeMapAndWriteMissingToDatabase(
        LicenseService.Iface licenseClient, InputStream in, Class<T> clazz, Class<U> uClass) throws TException {
    Map<U, T> typeMap;/*w ww  .jav  a 2s . com*/
    List<CSVRecord> records = ImportCSV.readAsCSVRecords(in);
    final List<T> recordsToAdd = simpleConvert(records, clazz);
    final List<T> fullList = CommonUtils.nullToEmptyList(getAllFromDB(licenseClient, clazz));
    typeMap = Maps.newHashMap(Maps.uniqueIndex(fullList, getIdentifier(clazz, uClass)));
    final ImmutableList<T> filteredList = getElementsWithIdentifiersNotInMap(getIdentifier(clazz, uClass),
            typeMap, recordsToAdd);
    List<T> added = null;
    if (filteredList.size() > 0) {
        added = addAlltoDB(licenseClient, clazz, filteredList);
    }
    if (added != null)
        typeMap.putAll(Maps.uniqueIndex(added, getIdentifier(clazz, uClass)));
    return typeMap;
}

From source file:org.eclipse.sw360.commonIO.TypeMappings.java

@NotNull
public static <T, U> Map<U, T> getIdentifierToTypeMapAndWriteMissingToDatabase(
        LicenseService.Iface licenseClient, InputStream in, Class<T> clazz, Class<U> uClass, User user)
        throws TException {
    Map<U, T> typeMap;//ww w .  j  av  a2 s.  com
    List<CSVRecord> records = ImportCSV.readAsCSVRecords(in);
    final List<T> recordsToAdd = simpleConvert(records, clazz);
    final List<T> fullList = CommonUtils.nullToEmptyList(getAllFromDB(licenseClient, clazz));
    typeMap = Maps.newHashMap(Maps.uniqueIndex(fullList, getIdentifier(clazz, uClass)));
    final ImmutableList<T> filteredList = getElementsWithIdentifiersNotInMap(getIdentifier(clazz, uClass),
            typeMap, recordsToAdd);
    List<T> added = null;
    if (filteredList.size() > 0) {
        added = addAlltoDB(licenseClient, clazz, filteredList, user);
    }
    if (added != null)
        typeMap.putAll(Maps.uniqueIndex(added, getIdentifier(clazz, uClass)));
    return typeMap;
}

From source file:org.eclipse.sw360.portal.tags.CompareTodos.java

private static Map<String, Todo> getTodosById(List<Todo> currentTodos) {
    return Maps.uniqueIndex(currentTodos, input -> input.getId());
}