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.siemens.sw360.commonIO.TypeMappings.java

@NotNull
public static Map<Integer, Risk> getIntegerRiskMap(LicenseService.Iface licenseClient,
        Map<Integer, RiskCategory> riskCategoryMap, InputStream in) throws TException {
    List<CSVRecord> riskRecords = ImportCSV.readAsCSVRecords(in);
    final List<Risk> risksToAdd = ConvertRecord.convertRisks(riskRecords, riskCategoryMap);
    final List<Risk> risks = CommonUtils.nullToEmptyList(licenseClient.getRisks());
    Map<Integer, Risk> riskMap = Maps.newHashMap(Maps.uniqueIndex(risks, getRiskIdentifier()));
    final ImmutableList<Risk> filteredList = getElementsWithIdentifiersNotInMap(getRiskIdentifier(), riskMap,
            risksToAdd);//w w  w .  ja  v a  2  s  . c  o m
    List<Risk> addedRisks = null;
    if (filteredList.size() > 0) {
        addedRisks = licenseClient.addRisks(filteredList);
    }
    if (addedRisks != null)
        riskMap.putAll(Maps.uniqueIndex(addedRisks, getRiskIdentifier()));
    return riskMap;
}

From source file:org.artifactory.storage.service.StorageServiceImpl.java

@Override
public StorageSummaryInfo getStorageSummaryInfo() {
    Set<RepoStorageSummary> summaries = fileService.getRepositoriesStorageSummary();
    filterGlobalRepoIfNeeded(summaries);
    List<RepoDescriptor> repos = Lists.newArrayList();
    repos.addAll(repositoryService.getLocalAndCachedRepoDescriptors());
    repos.addAll(repositoryService.getVirtualRepoDescriptors());
    final ImmutableMap<String, RepoDescriptor> reposMap = Maps.uniqueIndex(repos,
            new Function<RepoDescriptor, String>() {
                @Nullable/*from   w  w w  .  j a va2 s. c  om*/
                @Override
                public String apply(@Nullable RepoDescriptor input) {
                    if (input == null) {
                        return null;
                    }
                    return input.getKey();
                }
            });
    Iterable<RepoStorageSummaryInfo> infos = Iterables.transform(summaries,
            new Function<RepoStorageSummary, RepoStorageSummaryInfo>() {
                @Override
                public RepoStorageSummaryInfo apply(RepoStorageSummary r) {
                    RepositoryType repoType = getRepoType(r.getRepoKey(), reposMap);
                    RepoDescriptor repoDescriptor = reposMap.get(r.getRepoKey());
                    String repoTypeName = "UnKnown";
                    if (repoDescriptor != null) {
                        repoTypeName = repoDescriptor.getType().name();
                    }
                    RepoStorageSummaryInfo repoStorageSummaryInfo = new RepoStorageSummaryInfo(r.getRepoKey(),
                            repoType, r.getFoldersCount(), r.getFilesCount(), r.getUsedSpace(), repoTypeName);
                    return repoStorageSummaryInfo;
                }

                private RepositoryType getRepoType(String repoKey,
                        ImmutableMap<String, RepoDescriptor> repoDescriptors) {
                    RepoDescriptor repoDescriptor = repoDescriptors.get(repoKey);
                    if (repoDescriptor == null) {
                        return RepositoryType.BROKEN;
                    } else if (repoDescriptor instanceof RemoteRepoDescriptor) {
                        return RepositoryType.REMOTE;
                    } else if (repoDescriptor instanceof VirtualRepoDescriptor) {
                        return RepositoryType.VIRTUAL;
                    } else if (repoDescriptor instanceof LocalCacheRepoDescriptor) {
                        return RepositoryType.CACHE;
                    } else if (repoDescriptor instanceof LocalRepoDescriptor) {
                        return RepositoryType.LOCAL;
                    } else {
                        return RepositoryType.NA;
                    }
                }
            });

    BinariesInfo binariesInfo = binaryStore.getBinariesInfo();

    return new StorageSummaryInfo(Sets.newHashSet(infos), binariesInfo);
}

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

@NotNull
public static Map<Integer, Risk> getIntegerRiskMap(LicenseService.Iface licenseClient,
        Map<Integer, RiskCategory> riskCategoryMap, InputStream in, User user) throws TException {
    List<CSVRecord> riskRecords = ImportCSV.readAsCSVRecords(in);
    final List<Risk> risksToAdd = ConvertRecord.convertRisks(riskRecords, riskCategoryMap);
    final List<Risk> risks = CommonUtils.nullToEmptyList(licenseClient.getRisks());
    Map<Integer, Risk> riskMap = Maps.newHashMap(Maps.uniqueIndex(risks, getRiskIdentifier()));
    final ImmutableList<Risk> filteredList = getElementsWithIdentifiersNotInMap(getRiskIdentifier(), riskMap,
            risksToAdd);/* w  w  w  . j av  a 2 s.c o m*/
    List<Risk> addedRisks = null;
    if (filteredList.size() > 0) {
        addedRisks = licenseClient.addRisks(filteredList, user);
    }
    if (addedRisks != null)
        riskMap.putAll(Maps.uniqueIndex(addedRisks, getRiskIdentifier()));
    return riskMap;
}

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

/**
 * Handles active/inactive hierarchical validation for each individual <code>BlueprintElement</code>. This includes:
 * <ul>/*from   ww w.  j  a  va2  s.  c  om*/
 * <li>A child standard may not be ACTIVE if it's parent is INACTIVE</li>
 * </ul>
 */
protected static List<ValidationResult<BlueprintElement>> validateInactiveBlueprintHierarchicalRelationships(
        final List<BlueprintElement> blueprintElementList) {
    final List<ValidationResult<BlueprintElement>> errors = Lists.newArrayList();

    if (!CollectionUtils.isEmpty(blueprintElementList)) {
        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) {
                    // validate parent/child inactive rules
                    if (!parentBlueprintElement.isActive()) {
                        for (final BlueprintElement childElement : blueprintElementGroupedMap
                                .get(blueprintElementEntry.getKey())) {
                            if (childElement.isActive()) {
                                errors.add(buildValidationResult(childElement, MASTER_KEY, ACTIVE_FIELD,
                                        INACTIVE_MESSAGE));
                            }
                        }
                    }
                }
            }
        }
    }

    return errors;
}

From source file:org.apache.jackrabbit.oak.plugins.blob.MarkSweepGarbageCollector.java

/**
 * Returns the stats related to GC for all repos
 * //w  w  w  .  j  a  v a  2 s.  c  om
 * @return a list of GarbageCollectionRepoStats objects
 * @throws Exception
 */
@Override
public List<GarbageCollectionRepoStats> getStats() throws Exception {
    List<GarbageCollectionRepoStats> stats = newArrayList();
    if (SharedDataStoreUtils.isShared(blobStore)) {
        // Get all the references available
        List<DataRecord> refFiles = ((SharedDataStore) blobStore)
                .getAllMetadataRecords(SharedStoreRecordType.REFERENCES.getType());
        Map<String, DataRecord> references = Maps.uniqueIndex(refFiles, new Function<DataRecord, String>() {
            @Override
            public String apply(DataRecord input) {
                return SharedStoreRecordType.REFERENCES.getIdFromName(input.getIdentifier().toString());
            }
        });

        // Get all the markers available
        List<DataRecord> markerFiles = ((SharedDataStore) blobStore)
                .getAllMetadataRecords(SharedStoreRecordType.MARKED_START_MARKER.getType());
        Map<String, DataRecord> markers = Maps.uniqueIndex(markerFiles, new Function<DataRecord, String>() {
            @Override
            public String apply(DataRecord input) {
                return SharedStoreRecordType.MARKED_START_MARKER
                        .getIdFromName(input.getIdentifier().toString());
            }
        });

        // Get all the repositories registered
        List<DataRecord> repoFiles = ((SharedDataStore) blobStore)
                .getAllMetadataRecords(SharedStoreRecordType.REPOSITORY.getType());

        for (DataRecord repoRec : repoFiles) {
            String id = SharedStoreRecordType.REFERENCES.getIdFromName(repoRec.getIdentifier().toString());
            GarbageCollectionRepoStats stat = new GarbageCollectionRepoStats();
            stat.setRepositoryId(id);
            if (id != null && id.equals(repoId)) {
                stat.setLocal(true);
            }

            if (references.containsKey(id)) {
                DataRecord refRec = references.get(id);
                stat.setEndTime(refRec.getLastModified());
                stat.setLength(refRec.getLength());

                if (markers.containsKey(id)) {
                    stat.setStartTime(markers.get(id).getLastModified());
                }

                LineNumberReader reader = null;
                try {
                    reader = new LineNumberReader(new InputStreamReader(refRec.getStream()));
                    while (reader.readLine() != null) {
                    }
                    stat.setNumLines(reader.getLineNumber());
                } finally {
                    Closeables.close(reader, true);
                }
            }
            stats.add(stat);
        }
    }
    return stats;
}

From source file:org.jclouds.cloudstack.compute.config.CloudStackComputeServiceContextModule.java

@Provides
@Singleton/*from  w  ww .  jav a  2  s.c  om*/
@Memoized
public Supplier<Map<String, OSType>> listOSTypes(AtomicReference<AuthorizationException> authException,
        @Named(PROPERTY_SESSION_INTERVAL) long seconds, final CloudStackClient client) {
    return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException,
            new Supplier<Map<String, OSType>>() {
                @Override
                public Map<String, OSType> get() {
                    GuestOSClient guestOSClient = client.getGuestOSClient();
                    return Maps.uniqueIndex(guestOSClient.listOSTypes(), new Function<OSType, String>() {

                        @Override
                        public String apply(OSType arg0) {
                            return arg0.getId();
                        }
                    });
                }

                @Override
                public String toString() {
                    return Objects.toStringHelper(client.getGuestOSClient()).add("method", "listOSTypes")
                            .toString();
                }
            }, seconds, TimeUnit.SECONDS);
}

From source file:de.metas.ui.web.picking.pickingslot.PickingSlotRow.java

/**
 * Picking slot row constructor.// w w w. ja  v a2s. c om
 *
 * @param pickingSlotId
 * @param pickingSlotName
 * @param pickingSlotWarehouse
 * @param pickingSlotBPartner
 * @param pickingSlotBPLocation
 * @param includedHURows
 */
@Builder(builderMethodName = "fromPickingSlotBuilder", builderClassName = "FromPickingSlotBuilder")
private PickingSlotRow(final PickingSlotId pickingSlotId,
        //
        final String pickingSlotName, final LookupValue pickingSlotWarehouse,
        final LocatorId pickingSlotLocatorId, final LookupValue pickingSlotBPartner,
        final LookupValue pickingSlotBPLocation,
        //
        final List<PickingSlotRow> includedHURows, final ViewId includedViewId) {
    pickingSlotRowId = PickingSlotRowId.ofPickingSlotId(pickingSlotId);

    type = PickingSlotRowType.forPickingSlotRow();
    processed = false;
    documentPath = DocumentPath.rootDocumentPath(PickingConstants.WINDOWID_PickingSlotView, pickingSlotId);

    // HU
    huCode = null;
    huProduct = null;
    huPackingInfo = null;
    huQtyCU = null;
    huTopLevel = false;

    // Picking slot info
    this.pickingSlotWarehouse = pickingSlotWarehouse;
    this.pickingSlotLocatorId = pickingSlotLocatorId;
    this.pickingSlotBPartner = pickingSlotBPartner;
    this.pickingSlotBPLocation = pickingSlotBPLocation;

    pickingSlotCaption = buildPickingSlotCaption(pickingSlotName, pickingSlotBPartner, pickingSlotBPLocation);

    // Included rows
    this.includedHURows = includedHURows == null ? ImmutableMap.of()
            : Maps.uniqueIndex(includedHURows, PickingSlotRow::getPickingSlotRowId);

    this.includedViewId = includedViewId;
}

From source file:de.metas.ui.web.view.SqlViewFactory.java

private static ImmutableMap<WindowId, SqlDocumentFilterConverterDecorator> makeDecoratorsMapAndHandleDuplicates(
        @NonNull final Collection<SqlDocumentFilterConverterDecorator> providers) {
    try {/*from   www.  j ava2 s .  co  m*/
        return Maps.uniqueIndex(providers, SqlDocumentFilterConverterDecorator::getWindowId);
    } catch (IllegalArgumentException e) {
        final String message = "The given collection of SqlDocumentFilterConverterDecoratorProvider implementors contains more than one element with the same window-id";
        throw new AdempiereException(message, e)
                .setParameter("sqlDocumentFilterConverterDecoratorProviders", providers)
                .appendParametersToMessage();
    }
}

From source file:org.opendaylight.netconf.messagebus.eventsources.netconf.NetconfEventSource.java

private Map<String, Stream> getAvailableStreams() {
    Map<String, Stream> streamMap = new HashMap<>();
    final List<Stream> availableStreams;
    try {//from  ww  w  . j ava 2s.  c o  m
        availableStreams = mount.getAvailableStreams();
        streamMap = Maps.uniqueIndex(availableStreams, new Function<Stream, String>() {
            @Nullable
            @Override
            public String apply(@Nullable Stream input) {
                return input.getName().getValue();
            }
        });
    } catch (ReadFailedException e) {
        LOG.warn("Can not read streams for node {}", mount.getNodeId());
    }
    return streamMap;
}

From source file:org.sosy_lab.cpachecker.core.algorithm.termination.lasso_analysis.construction.LassoBuilder.java

public Collection<Lasso> buildLasso(CounterexampleInfo pCounterexampleInfo,
        Set<CVariableDeclaration> pRelevantVariables)
        throws CPATransferException, InterruptedException, TermException, SolverException {
    StemAndLoop stemAndLoop = createStemAndLoop(pCounterexampleInfo);
    shutdownNotifier.shutdownIfNecessary();

    Map<String, CVariableDeclaration> relevantVariables = Maps.uniqueIndex(pRelevantVariables,
            AVariableDeclaration::getQualifiedName);
    return createLassos(stemAndLoop, relevantVariables);
}