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:org.locationtech.geogig.repository.impl.WorkingTreeImpl.java

@Override
public ObjectId insert(Iterator<FeatureInfo> featureInfos, ProgressListener progress) {
    checkArgument(featureInfos != null);
    checkArgument(progress != null);/* w  w w.  jav a2s  .  c o m*/

    final RevTree currentWorkHead = getTree();
    final Map<String, NodeRef> currentTrees = Maps
            .newHashMap(Maps.uniqueIndex(getFeatureTypeTrees(), (nr) -> nr.path()));

    Map<String, CanonicalTreeBuilder> parentBuilders = new HashMap<>();

    progress.setProgress(0);
    final AtomicLong p = new AtomicLong();
    Function<FeatureInfo, RevFeature> treeBuildingTransformer = (fi) -> {
        final String parentPath = NodeRef.parentPath(fi.getPath());
        final String fid = NodeRef.nodeFromPath(fi.getPath());
        @Nullable
        ObjectId metadataId = fi.getFeatureTypeId();
        CanonicalTreeBuilder parentBuilder = getTreeBuilder(currentTrees, parentBuilders, parentPath,
                metadataId);

        if (fi.isDelete()) {
            if (parentBuilder != null) {
                parentBuilder.remove(fid);
            }
            return null;
        }

        Preconditions.checkState(parentBuilder != null);
        RevFeature feature = fi.getFeature();
        NodeRef parentRef = currentTrees.get(parentPath);
        Preconditions.checkNotNull(parentRef);
        if (fi.getFeatureTypeId().equals(parentRef.getMetadataId())) {
            metadataId = ObjectId.NULL;// use the parent's default
        }

        ObjectId oid = feature.getId();
        Envelope bounds = SpatialOps.boundsOf(feature);
        Node featureNode = Node.create(fid, oid, metadataId, TYPE.FEATURE, bounds);

        parentBuilder.put(featureNode);

        progress.setProgress(p.incrementAndGet());
        return feature;
    };

    Iterator<RevFeature> features = Iterators.transform(featureInfos, treeBuildingTransformer);
    features = Iterators.filter(features, Predicates.notNull());
    features = Iterators.filter(features, (f) -> !progress.isCanceled());

    Stopwatch insertTime = Stopwatch.createStarted();
    indexDatabase.putAll(features);
    insertTime.stop();
    if (progress.isCanceled()) {
        return currentWorkHead.getId();
    }

    progress.setDescription(String.format("%,d features inserted in %s", p.get(), insertTime));

    UpdateTree updateTree = context.command(UpdateTree.class).setRoot(currentWorkHead);
    parentBuilders.forEach((path, builder) -> {

        final NodeRef oldTreeRef = currentTrees.get(path);
        progress.setDescription(String.format("Building final tree %s...", oldTreeRef.name()));
        Stopwatch treeTime = Stopwatch.createStarted();
        final RevTree newFeatureTree = builder.build();
        treeTime.stop();
        progress.setDescription(
                String.format("%,d features tree built in %s", newFeatureTree.size(), treeTime));
        final NodeRef newTreeRef = oldTreeRef.update(newFeatureTree.getId(),
                SpatialOps.boundsOf(newFeatureTree));
        updateTree.setChild(newTreeRef);
    });

    final RevTree newWorkHead = updateTree.call();
    return updateWorkHead(newWorkHead.getId());
}

From source file:de.metas.ui.web.pickingV2.productsToPick.ProductsToPickRowsDataFactory.java

private Map<HuId, I_M_HU> retrieveHUs(final Collection<HuId> huIds) {
    return Maps.uniqueIndex(handlingUnitsDAO.getByIds(huIds), hu -> HuId.ofRepoId(hu.getM_HU_ID()));
}

From source file:com.facebook.presto.raptor.RaptorMetadata.java

@Override
public ConnectorOutputTableHandle beginCreateTable(ConnectorSession session,
        ConnectorTableMetadata tableMetadata) {
    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++;//from   w w  w . ja  va 2s.c  o  m
    }
    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);

    RaptorColumnHandle sampleWeightColumnHandle = null;
    if (tableMetadata.isSampled()) {
        sampleWeightColumnHandle = new RaptorColumnHandle(connectorId, SAMPLE_WEIGHT_COLUMN_NAME, columnId,
                BIGINT);
        columnHandles.add(sampleWeightColumnHandle);
        columnTypes.add(BIGINT);
    }

    long transactionId = shardManager.beginTransaction();

    return new RaptorOutputTableHandle(connectorId, transactionId, tableMetadata.getTable().getSchemaName(),
            tableMetadata.getTable().getTableName(), columnHandles.build(), columnTypes.build(),
            Optional.ofNullable(sampleWeightColumnHandle), sortColumnHandles,
            nCopies(sortColumnHandles.size(), ASC_NULLS_FIRST), temporalColumnHandle);
}

From source file:de.metas.ui.web.order.sales.purchasePlanning.view.PurchaseRow.java

private void setIncludedRows(@NonNull final ImmutableList<PurchaseRow> includedRows) {
    _includedRowsById = Maps.uniqueIndex(includedRows, PurchaseRow::getRowId);
}

From source file:com.vmware.appfactory.config.ConfigRegistry.java

/**
 * Load all config settings from the DB.
 *
 * @return a map of config settings <param_key,ConfigSetting>
 *///from   w  ww .j ava  2  s  .  c  o m
private Map<String, ConfigSetting> loadFromDB() {
    final List<ConfigSetting> settingsInDBList = _configDao.findAll();
    return Maps.uniqueIndex(settingsInDBList, new Function<ConfigSetting, String>() {
        /** Key function **/
        @Override
        public String apply(ConfigSetting setting) {
            return setting.getKey();
        }
    });
}

From source file:org.sonar.server.batch.ProjectRepositoryLoader.java

private Map<RuleKey, Rule> ruleByRuleKey(Iterator<Rule> rules) {
    return Maps.uniqueIndex(rules, new Function<Rule, RuleKey>() {
        @Override/*from  www .  jav a  2 s  .c  o  m*/
        public RuleKey apply(@Nullable Rule input) {
            return input != null ? input.key() : null;
        }
    });
}

From source file:com.siemens.sw360.importer.ComponentImportUtils.java

public static RequestSummary writeToDatabase(Iterable<ComponentCSVRecord> compCSVRecords,
        ComponentService.Iface componentClient, VendorService.Iface vendorClient,
        AttachmentService.Iface attachmentClient, User user) throws TException {

    Map<String, String> vendorNameToVendorId = getVendorNameToId(compCSVRecords, vendorClient);
    log.debug(format("Read vendors: (%d) %s ", vendorNameToVendorId.size(), vendorNameToVendorId));

    final RequestSummary componentRequestSummary = updateComponents(compCSVRecords, componentClient, user);

    Map<String, String> componentNameToId = new HashMap<>();
    final ArrayList<Release> releases = new ArrayList<>();
    for (Component component : componentClient.getComponentDetailedSummaryForExport()) {
        componentNameToId.put(component.getName(), component.getId());
        final List<Release> componentReleases = component.getReleases();
        if (componentReleases != null && componentReleases.size() > 0)
            releases.addAll(componentReleases);
    }/*from www . j ava  2s. c o  m*/
    Set<String> knownReleaseIdentifiers = Sets.newHashSet(getReleaseIdentifiers(releases));

    List<ComponentCSVRecord> relevantCSVRecords = new ArrayList<>();
    final HashMap<String, List<String>> releaseIdentifierToDownloadURL = new HashMap<>();

    List<AttachmentContent> attachmentContentsToUpdate = new ArrayList<>();

    filterRelevantCSVRecordsAndGetAttachmentContents(compCSVRecords, componentNameToId, knownReleaseIdentifiers,
            relevantCSVRecords, releaseIdentifierToDownloadURL, attachmentContentsToUpdate);

    attachmentContentsToUpdate = attachmentClient.makeAttachmentContents(attachmentContentsToUpdate);
    final ImmutableMap<String, AttachmentContent> URLtoAttachment = Maps.uniqueIndex(attachmentContentsToUpdate,
            new Function<AttachmentContent, String>() {
                @Override
                public String apply(AttachmentContent input) {
                    return input.getRemoteUrl();
                }
            });

    Set<Release> releasesToUpdate = new HashSet<>();

    //I do not need so many checks here because I only iterate over the relevant CSV records
    for (ComponentCSVRecord componentCSVRecord : relevantCSVRecords) {
        String releaseIdentifier = componentCSVRecord.getReleaseIdentifier();
        String vendorName = componentCSVRecord.getVendorName();
        String vendorId = vendorNameToVendorId.get(vendorName);

        String componentId = componentNameToId.get(componentCSVRecord.getComponentName());
        List<AttachmentContent> attachmentContents = getAttachmentContents(releaseIdentifierToDownloadURL,
                URLtoAttachment, releaseIdentifier);

        Release releaseToAdd = componentCSVRecord.getRelease(vendorId, componentId, attachmentContents);
        knownReleaseIdentifiers.add(releaseIdentifier);
        if (releaseToAdd != null) {
            releasesToUpdate.add(releaseToAdd);
        }

    }

    final RequestSummary releaseRequestSummary = componentClient.updateReleases(releasesToUpdate, user);

    return CommonUtils.addRequestSummaries(componentRequestSummary, "component", releaseRequestSummary,
            "release");
}

From source file:org.apache.aurora.common.args.ArgScanner.java

/**
 * Applies argument values to fields based on their annotations.
 *
 * @param parserOracle ParserOracle available to parse raw args with.
 * @param verifiers Verifiers available to verify argument constraints with.
 * @param argsInfo Fields to apply argument values to.
 * @param args Unparsed argument values.
 * @param positionalArgs The unparsed positional arguments.
 * @return {@code true} if the given {@code args} were successfully applied to their
 *     corresponding {@link Arg} fields.
 *///from ww w.  j a v a2s  . com
private boolean process(final ParserOracle parserOracle, Verifiers verifiers, ArgsInfo argsInfo,
        Map<String, String> args, List<String> positionalArgs) {

    if (!Sets.intersection(args.keySet(), ArgumentInfo.HELP_ARGS).isEmpty()) {
        printHelp(verifiers, argsInfo);
        return false;
    }

    Iterable<? extends OptionInfo<?>> optionInfos = argsInfo.getOptionInfos();

    final Set<String> argsFailedToParse = Sets.newHashSet();
    final Set<String> argsConstraintsFailed = Sets.newHashSet();

    Set<String> argAllShortNamesNoCollisions = getNoCollisions(optionInfos);

    final Map<String, OptionInfo<?>> argsByName = ImmutableMap.<String, OptionInfo<?>>builder()
            // Map by short arg name -> arg def.
            .putAll(Maps.uniqueIndex(Iterables.filter(optionInfos,
                    Predicates.compose(Predicates.in(argAllShortNamesNoCollisions), GET_OPTION_INFO_NAME)),
                    GET_OPTION_INFO_NAME))
            // Map by negated short arg name (for booleans)
            .putAll(Maps
                    .uniqueIndex(
                            Iterables.filter(Iterables.filter(optionInfos, IS_BOOLEAN),
                                    Predicates.compose(Predicates.in(argAllShortNamesNoCollisions),
                                            GET_OPTION_INFO_NEGATED_NAME)),
                            GET_OPTION_INFO_NEGATED_NAME))
            .build();

    // TODO(William Farner): Make sure to disallow duplicate arg specification by short and
    // canonical names.

    // TODO(William Farner): Support non-atomic argument constraints.  @OnlyIfSet, @OnlyIfNotSet,
    //    @ExclusiveOf to define inter-argument constraints.

    Set<String> recognizedArgs = Sets.intersection(argsByName.keySet(), args.keySet());

    for (String argName : recognizedArgs) {
        String argValue = args.get(argName);
        OptionInfo<?> optionInfo = argsByName.get(argName);

        try {
            optionInfo.load(parserOracle, argName, argValue);
        } catch (IllegalArgumentException e) {
            argsFailedToParse.add(argName + " - " + e.getMessage());
        }
    }

    Set<String> commandLineArgumentInfos = Sets.newTreeSet();

    Iterable<? extends ArgumentInfo<?>> allArguments = argsInfo.getOptionInfos();

    for (ArgumentInfo<?> anArgumentInfo : allArguments) {
        Arg<?> arg = anArgumentInfo.getArg();

        commandLineArgumentInfos.add(String.format("%s: %s", anArgumentInfo.getName(), arg.uncheckedGet()));

        try {
            anArgumentInfo.verify(verifiers);
        } catch (IllegalArgumentException e) {
            argsConstraintsFailed.add(anArgumentInfo.getName() + " - " + e.getMessage());
        }
    }

    ImmutableMultimap<String, String> warningMessages = ImmutableMultimap.<String, String>builder()
            .putAll("Unrecognized arguments", Sets.difference(args.keySet(), argsByName.keySet()))
            .putAll("Failed to parse", argsFailedToParse)
            .putAll("Value did not meet constraints", argsConstraintsFailed).build();

    if (!warningMessages.isEmpty()) {
        printHelp(verifiers, argsInfo);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Collection<String>> warnings : warningMessages.asMap().entrySet()) {
            sb.append(warnings.getKey()).append(":\n\t").append(Joiner.on("\n\t").join(warnings.getValue()))
                    .append("\n");
        }
        throw new IllegalArgumentException(sb.toString());
    }

    LOG.info("-------------------------------------------------------------------------");
    LOG.info("Command line argument values");
    for (String commandLineArgumentInfo : commandLineArgumentInfos) {
        LOG.info(commandLineArgumentInfo);
    }
    LOG.info("-------------------------------------------------------------------------");
    return true;
}

From source file:cpw.mods.fml.common.Loader.java

/**
 * The primary loading code/*from   ww w  .  java 2  s  .  c o  m*/
 *
 *
 * The found resources are first loaded into the {@link #modClassLoader}
 * (always) then scanned for class resources matching the specification
 * above.
 *
 * If they provide the {@link Mod} annotation, they will be loaded as
 * "FML mods"
 *
 * Finally, if they are successfully loaded as classes, they are then added
 * to the available mod list.
 */
private ModDiscoverer identifyMods() {
    FMLLog.fine("Building injected Mod Containers %s", injectedContainers);
    // Add in the MCP mod container
    mods.add(new InjectedModContainer(mcp, new File("minecraft.jar")));
    for (String cont : injectedContainers) {
        ModContainer mc;
        try {
            mc = (ModContainer) Class.forName(cont, true, modClassLoader).newInstance();
        } catch (Exception e) {
            FMLLog.log(Level.ERROR, e, "A problem occured instantiating the injected mod container %s", cont);
            throw new LoaderException(e);
        }
        mods.add(new InjectedModContainer(mc, mc.getSource()));
    }
    ModDiscoverer discoverer = new ModDiscoverer();
    FMLLog.fine("Attempting to load mods contained in the minecraft jar file and associated classes");
    discoverer.findClasspathMods(modClassLoader);
    FMLLog.fine("Minecraft jar mods loaded successfully");

    FMLLog.info("Searching %s for mods", canonicalModsDir.getAbsolutePath());
    discoverer.findModDirMods(canonicalModsDir);
    File versionSpecificModsDir = new File(canonicalModsDir, mccversion);
    if (versionSpecificModsDir.isDirectory()) {
        FMLLog.info("Also searching %s for mods", versionSpecificModsDir);
        discoverer.findModDirMods(versionSpecificModsDir);
    }

    mods.addAll(discoverer.identifyMods());
    identifyDuplicates(mods);
    namedMods = Maps.uniqueIndex(mods, new ModIdFunction());
    FMLLog.info("Forge Mod Loader has identified %d mod%s to load", mods.size(), mods.size() != 1 ? "s" : "");
    return discoverer;
}

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

private List<BlueprintElement> buildListOfDifferences(final String blueprintId,
        final List<BlueprintElement> coreStandardsElementList,
        final List<BlueprintElement> blueprintElementList, final Map<String, Segment> segmentMap,
        final String[] assessmentGrades) {
    List<BlueprintElement> blueprintElementListToSave = Lists.newArrayList();
    final Map<String, BlueprintElement> blueprintElementMap = Maps.uniqueIndex(blueprintElementList,
            BLUEPRINT_ELEMENT_UNIQUE_KEY_FUNCTION);
    final Map<String, BlueprintElement> coreStandardsElementMap = Maps.uniqueIndex(coreStandardsElementList,
            BLUEPRINT_ELEMENT_UNIQUE_KEY_FUNCTION);

    final Map<String, ValueDifference<BlueprintElement>> entriesDiffering = Maps
            .difference(blueprintElementMap, coreStandardsElementMap, BLUEPRINT_ELEMENT_EQUIVALENCE)
            .entriesDiffering();/*from  w w w.  j  av a 2s. co  m*/
    final Map<String, BlueprintElement> entriesOnlyOnLeft = Maps
            .difference(blueprintElementMap, coreStandardsElementMap).entriesOnlyOnLeft();
    final Map<String, BlueprintElement> entriesOnlyOnRight = Maps
            .difference(blueprintElementMap, coreStandardsElementMap).entriesOnlyOnRight();

    blueprintElementListToSave = Lists
            .newArrayList(Iterables.transform(entriesDiffering.values(), BLUEPRINT_ELEMENT_VALUE_DIFF_TRANS));

    // subsequent time around, default active booleans for the additions from core standards only to correspond to the grades already in use
    Iterables.addAll(blueprintElementListToSave,
            Iterables.transform(entriesOnlyOnRight.values(),
                    BLUEPRINT_ELEMENT_INJECT_DEFAULT_VALUES_TRANSFORMER.getInstance(blueprintId,
                            convertExistingBpElementGradesIntoDistinctGradeArray(blueprintElementList,
                                    assessmentGrades),
                            segmentMap)));

    Iterables.addAll(blueprintElementListToSave,
            Iterables.transform(entriesOnlyOnLeft.values(), BLUEPRINT_ELEMENT_REMOVE_TRANSFORMER));
    return blueprintElementListToSave;
}