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:it.anyplace.sync.bep.BlockExchangeConnectionHandler.java

private void startMessageListenerService() {
    inExecutorService.submit(new Runnable() {

        @Override/*  w w  w  . j  a v  a2 s.c  o m*/
        public void run() {
            try {
                while (!Thread.interrupted()) {
                    final Pair<BlockExchageProtos.MessageType, GeneratedMessage> message = receiveMessage();
                    logger.debug("received message type = {} {}", message.getLeft(),
                            getIdForMessage(message.getRight()));
                    logger.trace("received message = {}", message.getRight());
                    messageProcessingService.submit(new Runnable() {
                        @Override
                        public void run() {
                            logger.debug("processing message type = {} {}", message.getLeft(),
                                    getIdForMessage(message.getRight()));
                            try {
                                switch (message.getLeft()) {
                                case INDEX:
                                    eventBus.post(new IndexMessageReceivedEvent((Index) message.getValue()));
                                    break;
                                case INDEX_UPDATE:
                                    eventBus.post(new IndexUpdateMessageReceivedEvent(
                                            (IndexUpdate) message.getValue()));
                                    break;
                                case REQUEST:
                                    eventBus.post(
                                            new RequestMessageReceivedEvent((Request) message.getValue()));
                                    break;
                                case RESPONSE:
                                    eventBus.post(
                                            new ResponseMessageReceivedEvent((Response) message.getValue()));
                                    break;
                                case PING:
                                    logger.debug("ping message received");
                                    break;
                                case CLOSE:
                                    logger.info("received close message = {}", message.getValue());
                                    closeBg();
                                    break;
                                case CLUSTER_CONFIG: {
                                    checkArgument(clusterConfigInfo == null,
                                            "received cluster config message twice!");
                                    clusterConfigInfo = new ClusterConfigInfo();
                                    ClusterConfig clusterConfig = (ClusterConfig) message.getValue();
                                    for (Folder folder : firstNonNull(clusterConfig.getFoldersList(),
                                            Collections.<Folder>emptyList())) {
                                        ClusterConfigFolderInfo.Builder builder = ClusterConfigFolderInfo
                                                .newBuilder().setFolder(folder.getId())
                                                .setLabel(folder.getLabel());
                                        Map<String, Device> devicesById = Maps.uniqueIndex(
                                                firstNonNull(folder.getDevicesList(),
                                                        Collections.<Device>emptyList()),
                                                new Function<Device, String>() {
                                                    @Override
                                                    public String apply(Device input) {
                                                        return hashDataToDeviceIdString(
                                                                input.getId().toByteArray());
                                                    }
                                                });
                                        Device otherDevice = devicesById.get(address.getDeviceId()),
                                                ourDevice = devicesById.get(configuration.getDeviceId());
                                        if (otherDevice != null) {
                                            builder.setAnnounced(true);
                                        }
                                        final ClusterConfigFolderInfo folderInfo;
                                        if (ourDevice != null) {
                                            folderInfo = builder.setShared(true).build();
                                            logger.info("folder shared from device = {} folder = {}",
                                                    address.getDeviceId(), folderInfo);
                                            if (!configuration.getFolderNames()
                                                    .contains(folderInfo.getFolder())) {
                                                configuration.edit().addFolders(new FolderInfo(
                                                        folderInfo.getFolder(), folderInfo.getLabel()));
                                                logger.info("new folder shared = {}", folderInfo);
                                                eventBus.post(new NewFolderSharedEvent() {
                                                    @Override
                                                    public String getFolder() {
                                                        return folderInfo.getFolder();
                                                    }

                                                });
                                            }
                                        } else {
                                            folderInfo = builder.build();
                                            logger.info("folder not shared from device = {} folder = {}",
                                                    address.getDeviceId(), folderInfo);
                                        }
                                        clusterConfigInfo.putFolderInfo(folderInfo);
                                        configuration.edit()
                                                .addPeers(
                                                        Iterables
                                                                .filter(Iterables.transform(
                                                                        firstNonNull(folder.getDevicesList(),
                                                                                Collections
                                                                                        .<Device>emptyList()),
                                                                        new Function<Device, DeviceInfo>() {
                                                                            @Override
                                                                            public DeviceInfo apply(
                                                                                    Device device) {
                                                                                String deviceId = hashDataToDeviceIdString(
                                                                                        device.getId()
                                                                                                .toByteArray()),
                                                                                        name = device.hasName()
                                                                                                ? device.getName()
                                                                                                : null;
                                                                                return new DeviceInfo(deviceId,
                                                                                        name);
                                                                            }
                                                                        }), new Predicate<DeviceInfo>() {
                                                                            @Override
                                                                            public boolean apply(DeviceInfo s) {
                                                                                return !equal(s.getDeviceId(),
                                                                                        configuration
                                                                                                .getDeviceId());
                                                                            }
                                                                        }));
                                    }
                                    configuration.edit().persistLater();
                                    eventBus.post(new ClusterConfigMessageProcessedEvent(clusterConfig));
                                }
                                    break;
                                }
                            } catch (Exception ex) {
                                if (messageProcessingService.isShutdown()) {
                                    return;
                                }
                                logger.error("error processing message", ex);
                                closeBg();
                                throw ex;
                            }
                        }
                    });
                }
            } catch (Exception ex) {
                if (inExecutorService.isShutdown()) {
                    return;
                }
                logger.error("error receiving message", ex);
                closeBg();
            }
        }
    });
}

From source file:com.b2international.snowowl.core.CoreTerminologyBroker.java

private Map<String, ICoreTerminologyComponentInformation> internalGetRegisteredComponents() {

    if (null == registeredTerminologyComponents) {

        synchronized (CoreTerminologyBroker.class) {

            if (null == registeredTerminologyComponents) {

                final IConfigurationElement[] terminologyComponents = Platform.getExtensionRegistry()
                        .getConfigurationElementsFor(TERMINOLOGY_COMPONENT_EXTENSION_POINT_ID);
                final List<ICoreTerminologyComponentInformation> terminologyComponentInfos = configurationElementsToComponentInfo(
                        Lists.newArrayList(terminologyComponents));
                registeredTerminologyComponents = Maps.uniqueIndex(terminologyComponentInfos,
                        new Function<ICoreTerminologyComponentInformation, String>() {
                            @Override
                            public String apply(final ICoreTerminologyComponentInformation info) {
                                return info.getId();
                            }//w  w  w . j av  a  2 s . com
                        });
            }

        }

    }

    return registeredTerminologyComponents;
}

From source file:com.b2international.snowowl.snomed.datastore.converter.SnomedConceptConverter.java

private void expandAncestors(List<SnomedConcept> results, Set<String> conceptIds, String key, boolean stated) {
    if (!expand().containsKey(key)) {
        return;//from  w  w w  .  j  av  a  2  s  .com
    }

    final Options expandOptions = expand().get(key, Options.class);
    final boolean direct = checkDirect(expandOptions);

    final Multimap<String, String> ancestorsByDescendant = TreeMultimap.create();

    final LongToStringFunction toString = new LongToStringFunction();
    for (SnomedConcept concept : results) {
        final long[] parentIds = stated ? concept.getStatedParentIds() : concept.getParentIds();
        if (parentIds != null) {
            for (long parent : parentIds) {
                if (IComponent.ROOT_IDL != parent) {
                    ancestorsByDescendant.put(concept.getId(), toString.apply(parent));
                }
            }
        }
        if (!direct) {
            final long[] ancestorIds = stated ? concept.getStatedAncestorIds() : concept.getAncestorIds();
            if (ancestorIds != null) {
                for (long ancestor : ancestorIds) {
                    if (IComponent.ROOT_IDL != ancestor) {
                        ancestorsByDescendant.put(concept.getId(), toString.apply(ancestor));
                    }
                }
            }
        }
    }

    final int limit = getLimit(expandOptions);

    final Collection<String> componentIds = newHashSet(ancestorsByDescendant.values());

    if (limit > 0 && !componentIds.isEmpty()) {
        final SnomedConcepts ancestors = SnomedRequests.prepareSearchConcept().all().filterByActive(true)
                .filterByIds(componentIds).setLocales(locales())
                .setExpand(expandOptions.get("expand", Options.class)).build().execute(context());

        final Map<String, SnomedConcept> ancestorsById = newHashMap();
        ancestorsById.putAll(Maps.uniqueIndex(ancestors, ID_FUNCTION));
        for (SnomedConcept concept : results) {
            final Collection<String> ancestorIds = ancestorsByDescendant.get(concept.getId());
            final List<SnomedConcept> conceptAncestors = FluentIterable.from(ancestorIds).limit(limit)
                    .transform(Functions.forMap(ancestorsById)).toList();
            final SnomedConcepts ancestorConcepts = new SnomedConcepts(conceptAncestors, null, null, limit,
                    ancestorIds.size());
            if (stated) {
                concept.setStatedAncestors(ancestorConcepts);
            } else {
                concept.setAncestors(ancestorConcepts);
            }
        }
    } else {
        for (SnomedConcept concept : results) {
            final Collection<String> ancestorIds = ancestorsByDescendant.get(concept.getId());
            final SnomedConcepts ancestors = new SnomedConcepts(limit, ancestorIds.size());
            if (stated) {
                concept.setStatedAncestors(ancestors);
            } else {
                concept.setAncestors(ancestors);
            }
        }
    }
}

From source file:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java

static Map<String, FileMetadata> metadataToFileMetadataMap(final Metadata metadata) {
    return Maps.uniqueIndex(metadata.getFilesMetadata(), new Function<FileMetadata, String>() {
        @Override/* w  ww  .ja v a 2 s. c  o m*/
        public String apply(FileMetadata fileMetadata) {
            return Files.getNameWithoutExtension(fileMetadata.getFile()) + "."
                    + Files.getFileExtension(fileMetadata.getFile());
        }
    });
}

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

private void compareRwadefResources(Contract savedContract, Contract translatedContract) {
    if (assertBothNull(savedContract.getResources(), translatedContract.getResources())) {
        return;/*www. java2s .c om*/
    }

    ImmutableMap<String, Resource> savedResources = Maps.uniqueIndex(savedContract.getResources(),
            new Function<Resource, String>() {
                public String apply(Resource resource) {
                    return resource.getResourcePath();
                }
            });
    ImmutableMap<String, Resource> translatedResources = Maps.uniqueIndex(translatedContract.getResources(),
            new Function<Resource, String>() {
                public String apply(Resource resource) {
                    return resource.getResourcePath();
                }
            });

    assertEquals(savedResources.size(), translatedResources.size());
    for (String key : savedResources.keySet()) {
        Resource savedResource = savedResources.get(key);
        Resource translatedResource = translatedResources.get(key);
        assertNotNull(savedResource);
        assertNotNull(translatedResource);

        assertEquals(savedResource.getDescription(), translatedResource.getDescription());
        assertEquals(savedResource.getAuthenticationProtocol(), translatedResource.getAuthenticationProtocol());
        assertEquals(savedResource.getName(), translatedResource.getName());
        compareStringLists(savedResource.getSections(), translatedResource.getSections());

        compareRwadefPathVariables(savedResource, translatedResource);
        compareRwadefOperations(savedResource, translatedResource);
    }
}

From source file:com.brq.wallet.coinapult.CoinapultAccount.java

private List<com.coinapult.api.httpclient.Transaction.Json> getHistoryWithExtras() {
    if (accountHistory == null) {
        return Lists.newArrayList();
    }//from  www .j ava 2  s  .  co  m
    Function<com.coinapult.api.httpclient.Transaction.Json, String> txMapping = new Function<com.coinapult.api.httpclient.Transaction.Json, String>() {
        @Nullable
        @Override
        public String apply(@Nullable com.coinapult.api.httpclient.Transaction.Json input) {
            return input.tid;
        }
    };
    ImmutableMap<String, Transaction.Json> localHistoryMap = Maps.uniqueIndex(extraHistory, txMapping);
    final HashMap<String, Transaction.Json> historyMap = new HashMap<String, Transaction.Json>();
    for (Transaction.Json historyEntry : accountHistory) {
        // sometimes the entry contains the same tx twice - timing problem in combination with paging-request
        if (!historyMap.containsKey(historyEntry.tid)) {
            historyMap.put(historyEntry.tid, historyEntry);
        }
    }
    HashMap<String, Transaction.Json> merged = Maps.newHashMap();
    merged.putAll(localHistoryMap);
    merged.putAll(historyMap); //accountHistory overwrites local results
    Collection<Transaction.Json> unfiltered = merged.values();
    Iterable<com.coinapult.api.httpclient.Transaction.Json> withoutConversion = Iterables.filter(unfiltered,
            TX_NOT_CONVERSION);
    ImmutableList<Transaction.Json> ret = Ordering.natural()
            .onResultOf(new Function<com.coinapult.api.httpclient.Transaction.Json, Comparable>() {
                @Nullable
                @Override
                public Comparable apply(@Nullable com.coinapult.api.httpclient.Transaction.Json input) {
                    Long completeTime = input.completeTime;
                    if (completeTime.equals(0L)) {
                        return input.timestamp;
                    }
                    return completeTime;
                }
            }).reverse().immutableSortedCopy(withoutConversion);
    return ret;
}

From source file:io.prestosql.plugin.raptor.legacy.RaptorMetadata.java

@Override
public ConnectorOutputTableHandle beginCreateTable(ConnectorSession session,
        ConnectorTableMetadata tableMetadata, Optional<ConnectorNewTableLayout> layout) {
    if (viewExists(session, tableMetadata.getTable())) {
        throw new PrestoException(ALREADY_EXISTS, "View already exists: " + tableMetadata.getTable());
    }//from w ww  .jav a2s.c o  m

    Optional<RaptorPartitioningHandle> partitioning = layout.map(ConnectorNewTableLayout::getPartitioning)
            .map(RaptorPartitioningHandle.class::cast);

    ImmutableList.Builder<RaptorColumnHandle> columnHandles = ImmutableList.builder();
    ImmutableList.Builder<Type> columnTypes = ImmutableList.builder();

    long columnId = 1;
    for (ColumnMetadata column : tableMetadata.getColumns()) {
        columnHandles.add(new RaptorColumnHandle(connectorId, column.getName(), columnId, column.getType()));
        columnTypes.add(column.getType());
        columnId++;
    }
    Map<String, RaptorColumnHandle> columnHandleMap = Maps.uniqueIndex(columnHandles.build(),
            RaptorColumnHandle::getColumnName);

    List<RaptorColumnHandle> sortColumnHandles = getSortColumnHandles(
            getSortColumns(tableMetadata.getProperties()), columnHandleMap);
    Optional<RaptorColumnHandle> temporalColumnHandle = getTemporalColumnHandle(
            getTemporalColumn(tableMetadata.getProperties()), columnHandleMap);

    if (temporalColumnHandle.isPresent()) {
        RaptorColumnHandle column = temporalColumnHandle.get();
        if (!column.getColumnType().equals(TIMESTAMP) && !column.getColumnType().equals(DATE)) {
            throw new PrestoException(NOT_SUPPORTED,
                    "Temporal column must be of type timestamp or date: " + column.getColumnName());
        }
    }

    boolean organized = isOrganized(tableMetadata.getProperties());
    if (organized) {
        if (temporalColumnHandle.isPresent()) {
            throw new PrestoException(NOT_SUPPORTED, "Table with temporal columns cannot be organized");
        }
        if (sortColumnHandles.isEmpty()) {
            throw new PrestoException(NOT_SUPPORTED, "Table organization requires an ordering");
        }
    }

    long transactionId = shardManager.beginTransaction();

    setTransactionId(transactionId);

    Optional<DistributionInfo> distribution = partitioning
            .map(handle -> getDistributionInfo(handle.getDistributionId(), columnHandleMap,
                    tableMetadata.getProperties()));

    return new RaptorOutputTableHandle(connectorId, transactionId, tableMetadata.getTable().getSchemaName(),
            tableMetadata.getTable().getTableName(), columnHandles.build(), columnTypes.build(),
            sortColumnHandles, nCopies(sortColumnHandles.size(), ASC_NULLS_FIRST), temporalColumnHandle,
            distribution.map(info -> OptionalLong.of(info.getDistributionId())).orElse(OptionalLong.empty()),
            distribution.map(info -> OptionalInt.of(info.getBucketCount())).orElse(OptionalInt.empty()),
            organized, distribution.map(DistributionInfo::getBucketColumns).orElse(ImmutableList.of()));
}

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

@Override
public void calculateCopyVolumeStatistics(Collection<Copy> copies) {
    if (copies.isEmpty()) {
        return;/* w  w w. ja  v  a 2  s . c o  m*/
    }
    // 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 prv.copy_id, avg(prv.plate_remaining_volume), min(prv.plate_remaining_volume), max(prv.plate_remaining_volume) from "
            + "(select p.copy_id, p.well_volume - sum(la.volume_transferred_per_well_from_library_plates) as plate_remaining_volume "
            + "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.copy_id in (:copyIds) and ap.replicate_ordinal = 0 "
            + "group by p.copy_id, p.plate_id, p.well_volume) as prv " + "group by prv.copy_id";
    javax.persistence.Query query = getEntityManager().createNativeQuery(sql);
    Map<Serializable, Copy> copiesById = Maps.uniqueIndex(copies, Copy.ToEntityId);
    query.setParameter("copyIds", copiesById.keySet());
    for (Object[] row : (List<Object[]>) query.getResultList()) {
        Copy copy = copiesById.get(row[0]);
        VolumeStatistics volumeStatistics = new VolumeStatistics();
        copy.setVolumeStatistics(volumeStatistics);
        volumeStatistics.setAverageRemaining(toPlateVolume((BigDecimal) row[1]));
        volumeStatistics.setMinRemaining(toPlateVolume((BigDecimal) row[2]));
        volumeStatistics.setMaxRemaining(toPlateVolume((BigDecimal) row[3]));
    }
}

From source file:org.glowroot.central.storage.ConfigRepositoryImpl.java

private PluginConfig buildPluginConfig(PluginConfig existingPluginConfig, List<PluginProperty> properties) {
    Map<String, PluginProperty> props = Maps.newHashMap(Maps.uniqueIndex(properties, PluginProperty::getName));
    PluginConfig.Builder builder = PluginConfig.newBuilder().setId(existingPluginConfig.getId())
            .setName(existingPluginConfig.getName());
    for (PluginProperty existingProperty : existingPluginConfig.getPropertyList()) {
        PluginProperty prop = props.remove(existingProperty.getName());
        if (prop == null) {
            throw new IllegalStateException("Missing plugin property name: " + existingProperty.getName());
        }//from w w w.j  a v a 2  s . c  o  m
        if (!isSameType(prop.getValue(), existingProperty.getValue())) {
            throw new IllegalStateException("Plugin property " + prop.getName() + " has incorrect type: "
                    + prop.getValue().getValCase());
        }
        builder.addProperty(PluginProperty.newBuilder(existingProperty).setValue(prop.getValue()));
    }
    if (!props.isEmpty()) {
        throw new IllegalStateException("Unexpected property name(s): " + Joiner.on(", ").join(props.keySet()));
    }
    return builder.build();
}

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

private void compareRwadefPathVariables(Resource savedResource, Resource translatedResource) {
    if (assertBothNull(savedResource.getPathVariables(), translatedResource.getPathVariables())) {
        return;/*from   w  w w .j  av  a  2  s.c  o m*/
    }

    ImmutableMap<String, PathVariable> savedPathVariables = Maps.uniqueIndex(savedResource.getPathVariables(),
            new Function<PathVariable, String>() {
                public String apply(PathVariable pathVariable) {
                    return pathVariable.getName();
                }
            });
    ImmutableMap<String, PathVariable> translatedPathVariables = Maps
            .uniqueIndex(translatedResource.getPathVariables(), new Function<PathVariable, String>() {
                public String apply(PathVariable pathVariable) {
                    return pathVariable.getName();
                }
            });

    assertEquals(savedPathVariables.size(), translatedPathVariables.size());
    for (String key1 : savedPathVariables.keySet()) {
        PathVariable savedPathVariable = savedPathVariables.get(key1);
        PathVariable translatedPathVariable = translatedPathVariables.get(key1);
        assertNotNull(savedPathVariable);
        assertNotNull(translatedPathVariable);

        assertEquals(savedPathVariable.getDescription(), translatedPathVariable.getDescription());
        assertEquals(savedPathVariable.getExample(), translatedPathVariable.getExample());
        assertEquals(savedPathVariable.getType(), translatedPathVariable.getType());
        assertEquals(savedPathVariable.isRequired(), translatedPathVariable.isRequired());
    }
}