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:fr.xebia.cloud.amazon.aws.tools.AmazonAwsUtils.java

public static void deleteCnameIfExist(Iterable<String> cnames, HostedZone hostedZone, AmazonRoute53 route53) {
    // List all//from ww w  .j a v  a  2 s .  com
    ListResourceRecordSetsRequest listResourceRecordSetsRequest = new ListResourceRecordSetsRequest()
            // .withStartRecordType(RRType.CNAME)
            .withHostedZoneId(hostedZone.getId());
    ListResourceRecordSetsResult listResourceRecordSetsResult = route53
            .listResourceRecordSets(listResourceRecordSetsRequest);

    if (listResourceRecordSetsResult.isTruncated()) {
        logger.warn("truncated result");
    }

    Function<ResourceRecordSet, String> cnameExtractor = new Function<ResourceRecordSet, String>() {
        @Override
        public String apply(@Nullable ResourceRecordSet resourceRecordSet) {
            if (resourceRecordSet == null) {
                return null;
            }
            if (!RRType.CNAME.equals(RRType.fromValue(resourceRecordSet.getType()))) {
                return null;
            }
            return resourceRecordSet.getName();
        }
    };

    Iterable<ResourceRecordSet> existingCnamesAsResourceRecordSet = Iterables
            .filter(listResourceRecordSetsResult.getResourceRecordSets(), new Predicate<ResourceRecordSet>() {
                @Override
                public boolean apply(@Nullable ResourceRecordSet resourceRecordSet) {
                    return RRType.CNAME.equals(RRType.fromValue(resourceRecordSet.getType()));
                }
            });

    final ImmutableMap<String, ResourceRecordSet> existingCnames = Maps
            .uniqueIndex(existingCnamesAsResourceRecordSet, cnameExtractor);

    Sets.SetView<String> cnamesToDelete = Sets.intersection(Sets.newHashSet(cnames), existingCnames.keySet());

    Function<String, Change> cnameToDeleteCnameChange = new Function<String, Change>() {
        @Override
        public Change apply(@Nullable String cname) {
            ResourceRecordSet existingResourceRecordSet = existingCnames.get(cname);

            return new Change().withAction(ChangeAction.DELETE)
                    .withResourceRecordSet(new ResourceRecordSet().withType(RRType.CNAME).withName(cname)
                            .withTTL(existingResourceRecordSet.getTTL())
                            .withResourceRecords(existingResourceRecordSet.getResourceRecords()));
        }
    };

    List<Change> changes = Lists.newArrayList(Iterables.transform(cnamesToDelete, cnameToDeleteCnameChange));
    if (changes.isEmpty()) {
        logger.debug("No CNAME to delete");
        return;
    }

    logger.info("Delete CNAME changes {}", changes);
    ChangeResourceRecordSetsRequest changeResourceRecordSetsRequest = new ChangeResourceRecordSetsRequest()
            .withHostedZoneId(hostedZone.getId()).withChangeBatch(new ChangeBatch().withChanges(changes));
    route53.changeResourceRecordSets(changeResourceRecordSetsRequest);
}

From source file:edu.harvard.med.screensaver.db.LibrariesDAOImpl.java

@Override
public void calculatePlateVolumeStatistics(Collection<Plate> plates) {
    // note: we are forced to use native SQL query, as HQL does not perform volume multiplication properly (always results in value of 0)
    String sql = "select p.plate_id, p.well_volume - sum(la.volume_transferred_per_well_from_library_plates)"
            + "from plate p join assay_plate ap using(plate_id) join screening ls on(ls.activity_id = ap.library_screening_id) join lab_activity la using(activity_id) "
            + "where p.plate_id in (:plateIds) and ap.replicate_ordinal = 0 "
            + "group by p.plate_id, p.well_volume";
    javax.persistence.Query query = getEntityManager().createNativeQuery(sql);
    Map<Serializable, Plate> platesById = Maps.uniqueIndex(plates, Plate.ToEntityId);
    query.setParameter("plateIds", platesById.keySet());
    // set statistics for all requested plates, to properly handle plates that have not been screened at all (and which will not have a result in the query, due to lack of left joins)
    for (Plate plate : plates) {
        VolumeStatistics volumeStatistics = new VolumeStatistics();
        plate.setVolumeStatistics(volumeStatistics);
        volumeStatistics.setAverageRemaining(plate.getWellVolume());
    }/*from   w  w w  .j  a  v  a2 s  . co  m*/
    for (Object[] row : (List<Object[]>) query.getResultList()) {
        Plate plate = platesById.get(row[0]);
        BigDecimal avgRemainingVolumeLiters = (BigDecimal) row[1];
        plate.getVolumeStatistics().setAverageRemaining(toPlateVolume(avgRemainingVolumeLiters));
    }
}

From source file:org.restlet.test.ext.apispark.conversion.swagger.v2_0.Swagger2TestCase.java

private void compareRwadefOperations(Resource savedResource, Resource translatedResource) {
    if (assertBothNull(savedResource.getOperations(), translatedResource.getOperations())) {
        return;/*from   www . j  ava 2s .  co m*/
    }

    ImmutableMap<String, Operation> savedOperations = Maps.uniqueIndex(savedResource.getOperations(),
            new Function<Operation, String>() {
                public String apply(Operation operation) {
                    return operation.getName();
                }
            });
    ImmutableMap<String, Operation> translatedOperations = Maps.uniqueIndex(translatedResource.getOperations(),
            new Function<Operation, String>() {
                public String apply(Operation operation) {
                    return operation.getName();
                }
            });

    assertEquals(savedOperations.size(), translatedOperations.size());
    for (String key : savedOperations.keySet()) {
        Operation savedOperation = savedOperations.get(key);
        Operation translatedOperation = translatedOperations.get(key);
        assertNotNull(savedOperation);
        assertNotNull(translatedOperation);

        assertEquals(savedOperation.getDescription(), translatedOperation.getDescription());
        assertEquals(savedOperation.getMethod(), translatedOperation.getMethod());

        compareRwadefHeaders(savedOperation.getHeaders(), translatedOperation.getHeaders());
        compareRwadefQueryParameters(savedOperation, translatedOperation);
        compareRwadefPayloads(savedOperation.getInputPayLoad(), translatedOperation.getInputPayLoad());
        compareRwadefResponses(savedOperation, translatedOperation);

        compareStringLists(savedOperation.getProduces(), translatedOperation.getProduces());
        compareStringLists(savedOperation.getConsumes(), translatedOperation.getConsumes());
    }
}

From source file:org.restlet.test.ext.apispark.conversion.swagger.v2_0.Swagger2TestCase.java

private void compareRwadefResponses(Operation savedOperation, Operation translatedOperation) {
    if (assertBothNull(savedOperation.getResponses(), translatedOperation.getResponses())) {
        return;//from w  w w .j a v  a2 s.c o  m
    }

    ImmutableMap<Integer, Response> savedResponses = Maps.uniqueIndex(savedOperation.getResponses(),
            new Function<Response, Integer>() {
                public Integer apply(Response response) {
                    return response.getCode();
                }
            });
    ImmutableMap<Integer, Response> translatedResponses = Maps.uniqueIndex(translatedOperation.getResponses(),
            new Function<Response, Integer>() {
                public Integer apply(Response response) {
                    return response.getCode();
                }
            });

    assertEquals(savedResponses.size(), translatedResponses.size());
    for (Integer key : savedResponses.keySet()) {
        Response savedResponse = savedResponses.get(key);
        Response translatedResponse = translatedResponses.get(key);
        assertNotNull(savedResponse);
        assertNotNull(translatedResponse);

        assertEquals(savedResponse.getDescription(), translatedResponse.getDescription());

        // both don't exist in Swagger => can't be retrieved
        // assertEquals(savedResponse.getMessage(), translatedResponse.getMessage());
        // assertEquals(savedResponse.getName(), translatedResponse.getName());

        compareRwadefHeaders(savedResponse.getHeaders(), translatedResponse.getHeaders());
        compareRwadefPayloads(savedResponse.getOutputPayLoad(), translatedResponse.getOutputPayLoad());
    }
}

From source file:org.restlet.test.ext.apispark.conversion.swagger.v2_0.Swagger2TestCase.java

private void compareRwadefQueryParameters(Operation savedOperation, Operation translatedOperation) {
    if (assertBothNull(savedOperation.getQueryParameters(), translatedOperation.getQueryParameters())) {
        return;/* w  w w . j  a  v a2  s. co  m*/
    }

    ImmutableMap<String, QueryParameter> savedQueryParameters = Maps
            .uniqueIndex(savedOperation.getQueryParameters(), new Function<QueryParameter, String>() {
                public String apply(QueryParameter header) {
                    return header.getName();
                }
            });
    ImmutableMap<String, QueryParameter> translatedQueryParameters = Maps
            .uniqueIndex(translatedOperation.getQueryParameters(), new Function<QueryParameter, String>() {
                public String apply(QueryParameter header) {
                    return header.getName();
                }
            });

    assertEquals(savedQueryParameters.size(), translatedQueryParameters.size());
    for (String key : savedQueryParameters.keySet()) {
        QueryParameter savedQueryParameter = savedQueryParameters.get(key);
        QueryParameter translatedQueryParameter = translatedQueryParameters.get(key);
        assertNotNull(savedQueryParameter);
        assertNotNull(translatedQueryParameter);

        assertEquals(savedQueryParameter.getDefaultValue(), translatedQueryParameter.getDefaultValue());
        assertEquals(savedQueryParameter.getDescription(), translatedQueryParameter.getDescription());
        assertEquals(savedQueryParameter.getType(), translatedQueryParameter.getType());
        assertEquals(savedQueryParameter.getExample(), translatedQueryParameter.getExample());
        assertEquals(savedQueryParameter.getSeparator(), translatedQueryParameter.getSeparator());
        assertEquals(savedQueryParameter.isRequired(), translatedQueryParameter.isRequired());
        // TODO: not available in Swagger 2.0
        // assertEquals(savedQueryParameter.isAllowMultiple(), translatedQueryParameter.isAllowMultiple());
        compareStringLists(savedQueryParameter.getEnumeration(), translatedQueryParameter.getEnumeration());
    }
}

From source file:com.b2international.snowowl.snomed.api.impl.SnomedClassificationServiceImpl.java

@Override
public ISnomedBrowserConcept getConceptPreview(String branchPath, String classificationId, String conceptId,
        List<ExtendedLocale> locales) {
    final SnomedBrowserConcept conceptDetails = (SnomedBrowserConcept) getBrowserService()
            .getConceptDetails(branchPath, conceptId, locales);

    final List<ISnomedBrowserRelationship> relationships = Lists
            .newArrayList(conceptDetails.getRelationships());
    final RelationshipChanges relationshipChanges = getRelationshipChanges(branchPath, classificationId,
            conceptId, 0, 10000);//from  www.j a va 2 s .  c  o m

    /* 
     * XXX: We don't want to match anything that is part of the inferred set below, so we remove relationships from the existing list, 
     * all in advance. (Revisit should this assumption prove to be incorrect.)
     */
    for (RelationshipChange relationshipChange : relationshipChanges.getItems()) {
        switch (relationshipChange.getChangeNature()) {
        case REDUNDANT:
            relationships.remove(findRelationship(relationships, relationshipChange));
            break;
        default:
            break;
        }
    }

    // Collect all concept representations that will be required for the conversion
    final Set<String> relatedIds = Sets.newHashSet();
    for (RelationshipChange relationshipChange : relationshipChanges.getItems()) {
        switch (relationshipChange.getChangeNature()) {
        case INFERRED:
            relatedIds.add(relationshipChange.getDestinationId());
            relatedIds.add(relationshipChange.getTypeId());
            break;
        default:
            break;
        }
    }

    final SnomedConcepts relatedConcepts = SnomedRequests.prepareSearchConcept().setLimit(relatedIds.size())
            .filterByIds(relatedIds).setLocales(locales).setExpand("fsn()")
            .build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath).execute(getBus()).getSync();

    final Map<String, SnomedConcept> relatedConceptsById = Maps.uniqueIndex(relatedConcepts,
            input -> input.getId());

    final LoadingCache<SnomedConcept, SnomedBrowserRelationshipType> types = CacheBuilder.newBuilder()
            .build(new CacheLoader<SnomedConcept, SnomedBrowserRelationshipType>() {
                @Override
                public SnomedBrowserRelationshipType load(SnomedConcept key) throws Exception {
                    return getBrowserService().convertBrowserRelationshipType(key);
                }
            });

    final LoadingCache<SnomedConcept, SnomedBrowserRelationshipTarget> targets = CacheBuilder.newBuilder()
            .build(new CacheLoader<SnomedConcept, SnomedBrowserRelationshipTarget>() {
                @Override
                public SnomedBrowserRelationshipTarget load(SnomedConcept key) throws Exception {
                    return getBrowserService().convertBrowserRelationshipTarget(key);
                }
            });

    for (RelationshipChange relationshipChange : relationshipChanges.getItems()) {
        switch (relationshipChange.getChangeNature()) {
        case INFERRED:
            final SnomedBrowserRelationship inferred = new SnomedBrowserRelationship();

            // XXX: Default and/or not populated values are shown as commented lines below
            inferred.setActive(true);
            inferred.setCharacteristicType(CharacteristicType.INFERRED_RELATIONSHIP);
            // inferred.setEffectiveTime(null);
            inferred.setGroupId(relationshipChange.getGroup());
            inferred.setModifier(relationshipChange.getModifier());
            // inferred.setModuleId(null);
            // inferred.setRelationshipId(null);
            // inferred.setReleased(false);
            inferred.setSourceId(relationshipChange.getSourceId());

            SnomedConcept destinationConcept = relatedConceptsById.get(relationshipChange.getDestinationId());
            SnomedConcept typeConcept = relatedConceptsById.get(relationshipChange.getTypeId());
            inferred.setTarget(targets.getUnchecked(destinationConcept));
            inferred.setType(types.getUnchecked(typeConcept));

            relationships.add(inferred);
            break;
        default:
            break;
        }
    }

    // Replace immutable relationship list with preview
    conceptDetails.setRelationships(relationships);
    return conceptDetails;
}

From source file:io.prestosql.plugin.hive.HiveMetadata.java

@Override
public void createTable(ConnectorSession session, ConnectorTableMetadata tableMetadata,
        boolean ignoreExisting) {
    SchemaTableName schemaTableName = tableMetadata.getTable();
    String schemaName = schemaTableName.getSchemaName();
    String tableName = schemaTableName.getTableName();
    List<String> partitionedBy = getPartitionedBy(tableMetadata.getProperties());
    Optional<HiveBucketProperty> bucketProperty = getBucketProperty(tableMetadata.getProperties());

    if ((bucketProperty.isPresent() || !partitionedBy.isEmpty())
            && getAvroSchemaUrl(tableMetadata.getProperties()) != null) {
        throw new PrestoException(NOT_SUPPORTED,
                "Bucketing/Partitioning columns not supported when Avro schema url is set");
    }//w  w  w. j  ava2  s . c o m

    List<HiveColumnHandle> columnHandles = getColumnHandles(tableMetadata, ImmutableSet.copyOf(partitionedBy),
            typeTranslator);
    HiveStorageFormat hiveStorageFormat = getHiveStorageFormat(tableMetadata.getProperties());
    Map<String, String> tableProperties = getEmptyTableProperties(tableMetadata, !partitionedBy.isEmpty(),
            new HdfsContext(session, schemaName, tableName));

    hiveStorageFormat.validateColumns(columnHandles);

    Map<String, HiveColumnHandle> columnHandlesByName = Maps.uniqueIndex(columnHandles,
            HiveColumnHandle::getName);
    List<Column> partitionColumns = partitionedBy.stream().map(columnHandlesByName::get)
            .map(column -> new Column(column.getName(), column.getHiveType(), column.getComment()))
            .collect(toList());
    checkPartitionTypesSupported(partitionColumns);

    Path targetPath;
    boolean external;
    String externalLocation = getExternalLocation(tableMetadata.getProperties());
    if (externalLocation != null) {
        if (!createsOfNonManagedTablesEnabled) {
            throw new PrestoException(NOT_SUPPORTED, "Cannot create non-managed Hive table");
        }

        external = true;
        targetPath = getExternalPath(new HdfsContext(session, schemaName, tableName), externalLocation);
    } else {
        external = false;
        LocationHandle locationHandle = locationService.forNewTable(metastore, session, schemaName, tableName);
        targetPath = locationService.getQueryWriteInfo(locationHandle).getTargetPath();
    }

    Table table = buildTableObject(session.getQueryId(), schemaName, tableName, session.getUser(),
            columnHandles, hiveStorageFormat, partitionedBy, bucketProperty, tableProperties, targetPath,
            external, prestoVersion);
    PrincipalPrivileges principalPrivileges = buildInitialPrivilegeSet(table.getOwner());
    HiveBasicStatistics basicStatistics = table.getPartitionColumns().isEmpty() ? createZeroStatistics()
            : createEmptyStatistics();
    metastore.createTable(session, table, principalPrivileges, Optional.empty(), ignoreExisting,
            new PartitionStatistics(basicStatistics, ImmutableMap.of()));
}

From source file:org.restlet.test.ext.apispark.conversion.swagger.v2_0.Swagger2TestCase.java

private void compareRwadefHeaders(List<Header> savedHeadersList, List<Header> translatedHeadersList) {
    if (assertBothNull(savedHeadersList, translatedHeadersList)) {
        return;/*from   w ww.  j  a v a 2s . c om*/
    }

    ImmutableMap<String, Header> savedHeaders = Maps.uniqueIndex(savedHeadersList,
            new Function<Header, String>() {
                public String apply(Header header) {
                    return header.getName();
                }
            });
    ImmutableMap<String, Header> translatedHeaders = Maps.uniqueIndex(translatedHeadersList,
            new Function<Header, String>() {
                public String apply(Header header) {
                    return header.getName();
                }
            });

    assertEquals(savedHeaders.size(), translatedHeaders.size());
    for (String key : savedHeaders.keySet()) {
        Header savedHeader = savedHeaders.get(key);
        Header translatedHeader = translatedHeaders.get(key);
        assertNotNull(savedHeader);
        assertNotNull(translatedHeader);

        assertEquals(savedHeader.getDefaultValue(), translatedHeader.getDefaultValue());
        assertEquals(savedHeader.getDescription(), translatedHeader.getDescription());
        assertEquals(savedHeader.getType(), translatedHeader.getType());
        assertEquals(savedHeader.isRequired(), translatedHeader.isRequired());
        // TODO: does not exist in Swagger 2.0 yet
        // assertEquals(savedHeader.isAllowMultiple(), translatedHeader.isAllowMultiple());

    }
}

From source file:gr.forth.ics.swkm.model2.importer.HybridStore.java

private Map<Interval, PropertyDomainRange> getPropertyDomainsAndRanges(Collection<Interval> propertyIntervals)
        throws SQLException {
    Map<Integer, Interval> intervalsByPost = Maps.uniqueIndex(propertyIntervals,
            new Function<Interval, Integer>() {
                public Integer apply(Interval interval) {
                    return interval.getPost();
                }//from w  w w.ja v a 2 s .c  om
            });

    PreparedStatement domainRangesByPropertyInterval = Jdbc.prepared(
            //post, domainKind, rangeKind
            "SELECT p.att0, p.att4, p.att6 " + "FROM t" + DbConstants.getIdFor(Rdf.PROPERTY) + " p "
                    + "WHERE p.att0 = ANY(?)",
            Jdbc.connection().createArrayOf("int", intervalsByPost.keySet().toArray()));

    Map<Interval, PropertyDomainRange> results = Maps.newHashMap();
    ResultSet rs = domainRangesByPropertyInterval.executeQuery();
    while (rs.next()) {
        final int post = rs.getInt(1);
        final int domainKind = rs.getInt(2);
        final int rangeKind = rs.getInt(3);

        results.put(intervalsByPost.get(post), new PropertyDomainRange(domainKind, rangeKind));
    }
    rs.close();
    domainRangesByPropertyInterval.close();

    return results;
}

From source file:org.restlet.test.ext.apispark.conversion.swagger.v2_0.Swagger2TestCase.java

private void compareRwadefRepresentations(Contract savedContract, Contract translatedContract) {
    if (assertBothNull(savedContract.getRepresentations(), translatedContract.getRepresentations())) {
        return;//from   ww w  . j  a v a 2 s. co  m
    }

    ImmutableMap<String, Representation> savedRepresentations = Maps
            .uniqueIndex(savedContract.getRepresentations(), new Function<Representation, String>() {
                public String apply(Representation representation) {
                    return representation.getName();
                }
            });
    ImmutableMap<String, Representation> translatedRepresentations = Maps
            .uniqueIndex(translatedContract.getRepresentations(), new Function<Representation, String>() {
                public String apply(Representation representation) {
                    return representation.getName();
                }
            });

    assertEquals(savedRepresentations.size(), translatedRepresentations.size());
    for (String key : savedRepresentations.keySet()) {
        Representation savedRepresentation = savedRepresentations.get(key);
        Representation translatedRepresentation = translatedRepresentations.get(key);
        assertNotNull(savedRepresentation);
        assertNotNull(translatedRepresentation);
        assertEquals(savedRepresentation.getDescription(), translatedRepresentation.getDescription());
        assertEquals(savedRepresentation.getExtendedType(), translatedRepresentation.getExtendedType());

        compareStringLists(savedRepresentation.getSections(), translatedRepresentation.getSections());
        compareRwadefProperties(savedRepresentation.getProperties(), translatedRepresentation.getProperties());
    }
}