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.facebook.buck.lua.LuaBinaryDescription.java

private LuaBinaryPackageComponents getPackageComponentsFromDeps(BuildRuleParams baseParams,
        BuildRuleResolver ruleResolver, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder,
        final CxxPlatform cxxPlatform, final PythonPlatform pythonPlatform,
        Optional<BuildTarget> nativeStarterLibrary, String mainModule, LuaConfig.PackageStyle packageStyle,
        Iterable<BuildRule> deps) throws NoSuchBuildTargetException {

    final LuaPackageComponents.Builder builder = LuaPackageComponents.builder();
    final OmnibusRoots.Builder omnibusRoots = OmnibusRoots.builder(cxxPlatform, ImmutableSet.of());

    final Map<BuildTarget, NativeLinkable> nativeLinkableRoots = new LinkedHashMap<>();
    final Map<BuildTarget, CxxLuaExtension> luaExtensions = new LinkedHashMap<>();
    final Map<BuildTarget, CxxPythonExtension> pythonExtensions = new LinkedHashMap<>();

    // Walk the deps to find all Lua packageables and native linkables.
    new AbstractBreadthFirstThrowingTraversal<BuildRule, NoSuchBuildTargetException>(deps) {
        private final ImmutableSet<BuildRule> empty = ImmutableSet.of();

        @Override//from  w ww.j  a  v  a  2  s  .co m
        public ImmutableSet<BuildRule> visit(BuildRule rule) throws NoSuchBuildTargetException {
            ImmutableSet<BuildRule> deps = empty;
            if (rule instanceof LuaPackageable) {
                LuaPackageable packageable = (LuaPackageable) rule;
                LuaPackageComponents components = packageable.getLuaPackageComponents();
                LuaPackageComponents.addComponents(builder, components);
                if (components.hasNativeCode(cxxPlatform)) {
                    for (BuildRule dep : rule.getDeps()) {
                        if (dep instanceof NativeLinkable) {
                            NativeLinkable linkable = (NativeLinkable) dep;
                            nativeLinkableRoots.put(linkable.getBuildTarget(), linkable);
                            omnibusRoots.addExcludedRoot(linkable);
                        }
                    }
                }
                deps = rule.getDeps();
            } else if (rule instanceof CxxPythonExtension) {
                CxxPythonExtension extension = (CxxPythonExtension) rule;
                NativeLinkTarget target = extension.getNativeLinkTarget(pythonPlatform);
                pythonExtensions.put(target.getBuildTarget(), (CxxPythonExtension) rule);
                omnibusRoots.addIncludedRoot(target);
            } else if (rule instanceof PythonPackagable) {
                PythonPackagable packageable = (PythonPackagable) rule;
                PythonPackageComponents components = packageable.getPythonPackageComponents(pythonPlatform,
                        cxxPlatform);
                builder.putAllPythonModules(MoreMaps.transformKeys(components.getModules(), Object::toString));
                builder.putAllNativeLibraries(
                        MoreMaps.transformKeys(components.getNativeLibraries(), Object::toString));
                if (components.hasNativeCode(cxxPlatform)) {
                    for (BuildRule dep : rule.getDeps()) {
                        if (dep instanceof NativeLinkable) {
                            NativeLinkable linkable = (NativeLinkable) dep;
                            nativeLinkableRoots.put(linkable.getBuildTarget(), linkable);
                            omnibusRoots.addExcludedRoot(linkable);
                        }
                    }
                }
                deps = rule.getDeps();
            } else if (rule instanceof CxxLuaExtension) {
                CxxLuaExtension extension = (CxxLuaExtension) rule;
                luaExtensions.put(extension.getBuildTarget(), extension);
                omnibusRoots.addIncludedRoot(extension);
            } else if (rule instanceof NativeLinkable) {
                NativeLinkable linkable = (NativeLinkable) rule;
                nativeLinkableRoots.put(linkable.getBuildTarget(), linkable);
                omnibusRoots.addPotentialRoot(rule);
            }
            return deps;
        }
    }.start();

    // Build the starter.
    Starter starter = createStarter(baseParams, ruleResolver, pathResolver, ruleFinder, cxxPlatform,
            nativeStarterLibrary, mainModule, packageStyle,
            !nativeLinkableRoots.isEmpty() || !omnibusRoots.isEmpty());
    SourcePath starterPath = null;

    if (luaConfig.getNativeLinkStrategy() == NativeLinkStrategy.MERGED) {

        // If we're using a native starter, include it in omnibus linking.
        if (starter instanceof NativeExecutableStarter) {
            NativeExecutableStarter nativeStarter = (NativeExecutableStarter) starter;
            omnibusRoots.addIncludedRoot(nativeStarter);
        }

        // Build the omnibus libraries.
        OmnibusRoots roots = omnibusRoots.build();
        OmnibusLibraries libraries = Omnibus.getSharedLibraries(baseParams, ruleResolver, pathResolver,
                ruleFinder, cxxBuckConfig, cxxPlatform, ImmutableList.of(), roots.getIncludedRoots().values(),
                roots.getExcludedRoots().values());

        // Add all the roots from the omnibus link.  If it's an extension, add it as a module.
        for (Map.Entry<BuildTarget, OmnibusRoot> root : libraries.getRoots().entrySet()) {

            // If it's a Lua extension add it as a module.
            CxxLuaExtension luaExtension = luaExtensions.get(root.getKey());
            if (luaExtension != null) {
                builder.putModules(luaExtension.getModule(cxxPlatform), root.getValue().getPath());
                continue;
            }

            // If it's a Python extension, add it as a python module.
            CxxPythonExtension pythonExtension = pythonExtensions.get(root.getKey());
            if (pythonExtension != null) {
                builder.putPythonModules(pythonExtension.getModule().toString(), root.getValue().getPath());
                continue;
            }

            // A root named after the top-level target is our native starter.
            if (root.getKey().equals(baseParams.getBuildTarget())) {
                starterPath = root.getValue().getPath();
                continue;
            }

            // Otherwise, add it as a native library.
            NativeLinkTarget target = Preconditions.checkNotNull(roots.getIncludedRoots().get(root.getKey()),
                    "%s: linked unexpected omnibus root: %s", baseParams.getBuildTarget(), root.getKey());
            NativeLinkTargetMode mode = target.getNativeLinkTargetMode(cxxPlatform);
            String soname = Preconditions.checkNotNull(mode.getLibraryName().orElse(null),
                    "%s: omnibus library for %s was built without soname", baseParams.getBuildTarget(),
                    root.getKey());
            builder.putNativeLibraries(soname, root.getValue().getPath());
        }

        // Add all remaining libraries as native libraries.
        for (OmnibusLibrary library : libraries.getLibraries()) {
            builder.putNativeLibraries(library.getSoname(), library.getPath());
        }

    } else {

        // For regular linking, add all Lua extensions as modules and their deps as native linkable
        // roots.
        for (Map.Entry<BuildTarget, CxxLuaExtension> entry : luaExtensions.entrySet()) {
            CxxLuaExtension extension = entry.getValue();
            builder.putModules(extension.getModule(cxxPlatform), extension.getExtension(cxxPlatform));
            nativeLinkableRoots.putAll(Maps.uniqueIndex(extension.getNativeLinkTargetDeps(cxxPlatform),
                    HasBuildTarget::getBuildTarget));
        }

        // Add in native executable deps.
        if (starter instanceof NativeExecutableStarter) {
            NativeExecutableStarter executableStarter = (NativeExecutableStarter) starter;
            nativeLinkableRoots.putAll(
                    Maps.uniqueIndex(executableStarter.getNativeStarterDeps(), HasBuildTarget::getBuildTarget));
        }

        // For regular linking, add all extensions via the package components interface and their
        // python-platform specific deps to the native linkables.
        for (Map.Entry<BuildTarget, CxxPythonExtension> entry : pythonExtensions.entrySet()) {
            PythonPackageComponents components = entry.getValue().getPythonPackageComponents(pythonPlatform,
                    cxxPlatform);
            builder.putAllPythonModules(MoreMaps.transformKeys(components.getModules(), Object::toString));
            builder.putAllNativeLibraries(
                    MoreMaps.transformKeys(components.getNativeLibraries(), Object::toString));
            nativeLinkableRoots.putAll(Maps.uniqueIndex(
                    entry.getValue().getNativeLinkTarget(pythonPlatform).getNativeLinkTargetDeps(cxxPlatform),
                    HasBuildTarget::getBuildTarget));
        }

        // Add shared libraries from all native linkables.
        for (NativeLinkable nativeLinkable : NativeLinkables
                .getTransitiveNativeLinkables(cxxPlatform, nativeLinkableRoots.values()).values()) {
            NativeLinkable.Linkage linkage = nativeLinkable.getPreferredLinkage(cxxPlatform);
            if (linkage != NativeLinkable.Linkage.STATIC) {
                builder.putAllNativeLibraries(nativeLinkable.getSharedLibraries(cxxPlatform));
            }
        }

    }

    // If an explicit starter path override hasn't been set (e.g. from omnibus linking), default to
    // building one directly from the starter.
    if (starterPath == null) {
        starterPath = starter.build();
    }

    return LuaBinaryPackageComponents.of(starterPath, builder.build());
}

From source file:com.facebook.presto.hive.HiveMetadata.java

private Table createTable(String schemaName, String tableName, String tableOwner,
        List<HiveColumnHandle> columnHandles, HiveStorageFormat hiveStorageFormat, List<String> partitionedBy,
        Path targetPath) {//  ww w.j a v  a  2  s  . co  m
    Map<String, HiveColumnHandle> columnHandlesByName = Maps.uniqueIndex(columnHandles,
            HiveColumnHandle::getName);
    List<FieldSchema> partitionColumns = partitionedBy.stream().map(columnHandlesByName::get)
            .map(column -> new FieldSchema(column.getName(), column.getHiveType().getHiveTypeName(), null))
            .collect(toList());

    Set<String> partitionColumnNames = ImmutableSet.copyOf(partitionedBy);

    boolean sampled = false;
    ImmutableList.Builder<FieldSchema> columns = ImmutableList.builder();
    for (HiveColumnHandle columnHandle : columnHandles) {
        String name = columnHandle.getName();
        String type = columnHandle.getHiveType().getHiveTypeName();
        if (name.equals(SAMPLE_WEIGHT_COLUMN_NAME)) {
            columns.add(new FieldSchema(name, type, "Presto sample weight column"));
            sampled = true;
        } else if (!partitionColumnNames.contains(name)) {
            verify(!columnHandle.isPartitionKey(),
                    "Column handles are not consistent with partitioned by property");
            columns.add(new FieldSchema(name, type, null));
        } else {
            verify(columnHandle.isPartitionKey(),
                    "Column handles are not consistent with partitioned by property");
        }
    }

    SerDeInfo serdeInfo = new SerDeInfo();
    serdeInfo.setName(tableName);
    serdeInfo.setSerializationLib(hiveStorageFormat.getSerDe());
    serdeInfo.setParameters(ImmutableMap.of());

    StorageDescriptor sd = new StorageDescriptor();
    sd.setLocation(targetPath.toString());
    sd.setCols(columns.build());
    sd.setSerdeInfo(serdeInfo);
    sd.setInputFormat(hiveStorageFormat.getInputFormat());
    sd.setOutputFormat(hiveStorageFormat.getOutputFormat());
    sd.setParameters(ImmutableMap.of());

    Table table = new Table();
    table.setDbName(schemaName);
    table.setTableName(tableName);
    table.setOwner(tableOwner);
    table.setTableType(TableType.MANAGED_TABLE.toString());
    String tableComment = "Created by Presto";
    if (sampled) {
        tableComment = "Sampled table created by Presto. Only query this table from Hive if you understand how Presto implements sampling.";
    }
    table.setParameters(ImmutableMap.of("comment", tableComment));
    table.setPartitionKeys(partitionColumns);
    table.setSd(sd);

    PrivilegeGrantInfo allPrivileges = new PrivilegeGrantInfo("all", 0, tableOwner, PrincipalType.USER, true);
    table.setPrivileges(new PrincipalPrivilegeSet(ImmutableMap.of(tableOwner, ImmutableList.of(allPrivileges)),
            ImmutableMap.of(), ImmutableMap.of()));

    metastore.createTable(table);
    return table;
}

From source file:com.boundlessgeo.geoserver.api.controllers.MapController.java

@RequestMapping(value = "/{wsName}/{name}/layers", method = RequestMethod.PUT)
public @ResponseBody JSONArr mapLayerListPut(@PathVariable String wsName, @PathVariable String name,
        @RequestBody JSONArr layers, HttpServletRequest req) {
    Catalog cat = geoServer.getCatalog();
    LayerGroupInfo m = findMap(wsName, name, cat);

    // original//from w  w w.ja va  2 s .  c  o m
    List<MapLayer> mapLayers = MapLayer.list(m);
    Map<String, MapLayer> lookup = Maps.uniqueIndex(mapLayers, new Function<MapLayer, String>() {
        @Nullable
        public String apply(@Nullable MapLayer input) {
            return input.layer.getName();
        }
    });
    // modified
    List<PublishedInfo> reLayers = new ArrayList<PublishedInfo>();
    Map<String, PublishedInfo> check = Maps.uniqueIndex(reLayers, new Function<PublishedInfo, String>() {
        @Nullable
        public String apply(@Nullable PublishedInfo input) {
            return input.getName();
        }
    });
    List<StyleInfo> reStyles = new ArrayList<StyleInfo>();
    for (JSONObj l : Lists.reverse(Lists.newArrayList(layers.objects()))) {
        String layerName = l.str("name");
        String layerWorkspace = l.str("workspace");
        MapLayer mapLayer = lookup.get(layerName);
        if (mapLayer == null) {
            LayerInfo layer = findLayer(layerWorkspace, layerName, cat);
            if (layer != null) {
                mapLayer = new MapLayer(layer, layer.getDefaultStyle());
            }
        }
        if (mapLayer == null) {
            throw new NotFoundException("No such layer: " + l.toString());
        }
        if (check.containsKey(layerName)) {
            throw new BadRequestException("Duplicate layer: " + l.toString());
        }
        reLayers.add(mapLayer.layer);
        reStyles.add(mapLayer.style);
    }
    m.getLayers().clear();
    m.getLayers().addAll(reLayers);
    m.getStyles().clear();
    m.getStyles().addAll(reStyles);

    WorkspaceInfo ws = m.getWorkspace();

    Date modified = new Date();
    Metadata.modified(m, modified);
    Metadata.modified(ws, modified);

    cat.save(m);
    cat.save(ws);

    recent.add(LayerGroupInfo.class, m);
    recent.add(WorkspaceInfo.class, ws);
    return mapLayerList(m, req);
}

From source file:org.apache.druid.client.cache.MemcachedCache.java

@Override
public Map<NamedKey, byte[]> getBulk(Iterable<NamedKey> keys) {
    try (ResourceHolder<MemcachedClientIF> clientHolder = client.get()) {
        Map<String, NamedKey> keyLookup = Maps.uniqueIndex(keys, new Function<NamedKey, String>() {
            @Override//from www  .  jav a2s .  c  om
            public String apply(@Nullable NamedKey input) {
                return computeKeyHash(memcachedPrefix, input);
            }
        });

        Map<NamedKey, byte[]> results = Maps.newHashMap();

        BulkFuture<Map<String, Object>> future;
        try {
            future = clientHolder.get().asyncGetBulk(keyLookup.keySet());
        } catch (IllegalStateException e) {
            // operation did not get queued in time (queue is full)
            errorCount.incrementAndGet();
            log.warn(e, "Unable to queue cache operation");
            return results;
        }

        try {
            Map<String, Object> some = future.getSome(timeout, TimeUnit.MILLISECONDS);

            if (future.isTimeout()) {
                future.cancel(false);
                timeoutCount.incrementAndGet();
            }
            missCount.addAndGet(keyLookup.size() - some.size());
            hitCount.addAndGet(some.size());

            for (Map.Entry<String, Object> entry : some.entrySet()) {
                final NamedKey key = keyLookup.get(entry.getKey());
                final byte[] value = (byte[]) entry.getValue();
                if (value != null) {
                    results.put(key, deserializeValue(key, value));
                }
            }

            return results;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw Throwables.propagate(e);
        } catch (ExecutionException e) {
            errorCount.incrementAndGet();
            log.warn(e, "Exception pulling item from cache");
            return results;
        }
    }
}

From source file:org.obm.push.mail.EmailManager.java

private Map<Long, Email> getEmailsAsUidTreeMap(Set<Email> emails) {
    return Maps.uniqueIndex(emails, new Function<Email, Long>() {
        @Override/* w  w w.j ava2 s.  c  o  m*/
        public Long apply(Email email) {
            return email.getIndex();
        }
    });
}

From source file:org.apache.aurora.scheduler.thrift.ReadOnlySchedulerImpl.java

private Map<IJobKey, IJobConfiguration> getJobs(Optional<String> ownerRole,
        Multimap<IJobKey, IScheduledTask> tasks) {

    // We need to synthesize the JobConfiguration from the the current tasks because the
    // ImmediateJobManager doesn't store jobs directly and ImmediateJobManager#getJobs always
    // returns an empty Collection.
    Map<IJobKey, IJobConfiguration> jobs = Maps.newHashMap();

    jobs.putAll(Maps.transformEntries(tasks.asMap(), (jobKey, tasks1) -> {

        // Pick the latest transitioned task for each immediate job since the job can be in the
        // middle of an update or some shards have been selectively created.
        TaskConfig mostRecentTaskConfig = Tasks.getLatestActiveTask(tasks1).getAssignedTask().getTask()
                .newBuilder();/*  w w w .  ja  v  a  2  s  .  c  o m*/

        return IJobConfiguration.build(
                new JobConfiguration().setKey(jobKey.newBuilder()).setOwner(mostRecentTaskConfig.getOwner())
                        .setTaskConfig(mostRecentTaskConfig).setInstanceCount(tasks1.size()));
    }));

    // Get cron jobs directly from the manager. Do this after querying the task store so the real
    // template JobConfiguration for a cron job will overwrite the synthesized one that could have
    // been created above.
    Predicate<IJobConfiguration> configFilter = ownerRole.isPresent()
            ? Predicates.compose(Predicates.equalTo(ownerRole.get()), JobKeys::getRole)
            : Predicates.alwaysTrue();
    jobs.putAll(Maps.uniqueIndex(FluentIterable.from(Storage.Util.fetchCronJobs(storage)).filter(configFilter),
            IJobConfiguration::getKey));

    return jobs;
}

From source file:com.facebook.buck.features.lua.LuaBinaryDescription.java

private LuaBinaryPackageComponents getPackageComponentsFromDeps(BuildTarget buildTarget,
        ProjectFilesystem projectFilesystem, BuildRuleParams baseParams, ActionGraphBuilder graphBuilder,
        SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder, LuaPlatform luaPlatform,
        PythonPlatform pythonPlatform, Optional<BuildTarget> nativeStarterLibrary, String mainModule,
        LuaPlatform.PackageStyle packageStyle, Iterable<BuildRule> deps, CellPathResolver cellPathResolver) {

    CxxPlatform cxxPlatform = luaPlatform.getCxxPlatform();

    LuaPackageComponents.Builder builder = LuaPackageComponents.builder();
    OmnibusRoots.Builder omnibusRoots = OmnibusRoots.builder(cxxPlatform, ImmutableSet.of(), graphBuilder);

    Map<BuildTarget, NativeLinkable> nativeLinkableRoots = new LinkedHashMap<>();
    Map<BuildTarget, CxxLuaExtension> luaExtensions = new LinkedHashMap<>();
    Map<BuildTarget, CxxPythonExtension> pythonExtensions = new LinkedHashMap<>();

    // Walk the deps to find all Lua packageables and native linkables.
    new AbstractBreadthFirstTraversal<BuildRule>(deps) {
        private final ImmutableSet<BuildRule> empty = ImmutableSet.of();

        @Override/*from   w  w w.j  av a 2 s  .  com*/
        public Iterable<BuildRule> visit(BuildRule rule) {
            Iterable<BuildRule> deps = empty;
            if (rule instanceof LuaPackageable) {
                LuaPackageable packageable = (LuaPackageable) rule;
                LuaPackageComponents components = packageable.getLuaPackageComponents(pathResolver);
                LuaPackageComponents.addComponents(builder, components);
                deps = packageable.getLuaPackageDeps(cxxPlatform, graphBuilder);
                if (components.hasNativeCode(cxxPlatform)) {
                    for (BuildRule dep : deps) {
                        if (dep instanceof NativeLinkable) {
                            NativeLinkable linkable = (NativeLinkable) dep;
                            nativeLinkableRoots.put(linkable.getBuildTarget(), linkable);
                            omnibusRoots.addExcludedRoot(linkable);
                        }
                    }
                }
            } else if (rule instanceof CxxPythonExtension) {
                CxxPythonExtension extension = (CxxPythonExtension) rule;
                NativeLinkTarget target = extension.getNativeLinkTarget(pythonPlatform);
                pythonExtensions.put(target.getBuildTarget(), (CxxPythonExtension) rule);
                omnibusRoots.addIncludedRoot(target);
            } else if (rule instanceof PythonPackagable) {
                PythonPackagable packageable = (PythonPackagable) rule;
                PythonPackageComponents components = packageable.getPythonPackageComponents(pythonPlatform,
                        cxxPlatform, graphBuilder);
                builder.putAllPythonModules(MoreMaps.transformKeys(components.getModules(), Object::toString));
                builder.putAllNativeLibraries(
                        MoreMaps.transformKeys(components.getNativeLibraries(), Object::toString));
                deps = packageable.getPythonPackageDeps(pythonPlatform, cxxPlatform, graphBuilder);
                if (components.hasNativeCode(cxxPlatform)) {
                    for (BuildRule dep : deps) {
                        if (dep instanceof NativeLinkable) {
                            NativeLinkable linkable = (NativeLinkable) dep;
                            nativeLinkableRoots.put(linkable.getBuildTarget(), linkable);
                            omnibusRoots.addExcludedRoot(linkable);
                        }
                    }
                }
            } else if (rule instanceof CxxLuaExtension) {
                CxxLuaExtension extension = (CxxLuaExtension) rule;
                luaExtensions.put(extension.getBuildTarget(), extension);
                omnibusRoots.addIncludedRoot(extension);
            } else if (rule instanceof NativeLinkable) {
                NativeLinkable linkable = (NativeLinkable) rule;
                nativeLinkableRoots.put(linkable.getBuildTarget(), linkable);
                omnibusRoots.addPotentialRoot(linkable);
            }
            return deps;
        }
    }.start();

    // Build the starter.
    Starter starter = createStarter(cellPathResolver, projectFilesystem, buildTarget, baseParams, graphBuilder,
            pathResolver, ruleFinder, luaPlatform, nativeStarterLibrary, mainModule, packageStyle,
            !nativeLinkableRoots.isEmpty() || !omnibusRoots.isEmpty());
    SourcePath starterPath = null;

    if (luaPlatform.getNativeLinkStrategy() == NativeLinkStrategy.MERGED) {

        // If we're using a native starter, include it in omnibus linking.
        if (starter instanceof NativeExecutableStarter) {
            NativeExecutableStarter nativeStarter = (NativeExecutableStarter) starter;
            omnibusRoots.addIncludedRoot(nativeStarter);
        }

        // Build the omnibus libraries.
        OmnibusRoots roots = omnibusRoots.build();
        OmnibusLibraries libraries = Omnibus.getSharedLibraries(buildTarget, projectFilesystem, baseParams,
                cellPathResolver, graphBuilder, ruleFinder, cxxBuckConfig, cxxPlatform, ImmutableList.of(),
                roots.getIncludedRoots().values(), roots.getExcludedRoots().values());

        // Add all the roots from the omnibus link.  If it's an extension, add it as a module.
        for (Map.Entry<BuildTarget, OmnibusRoot> root : libraries.getRoots().entrySet()) {

            // If it's a Lua extension add it as a module.
            CxxLuaExtension luaExtension = luaExtensions.get(root.getKey());
            if (luaExtension != null) {
                builder.putModules(luaExtension.getModule(cxxPlatform), root.getValue().getPath());
                continue;
            }

            // If it's a Python extension, add it as a python module.
            CxxPythonExtension pythonExtension = pythonExtensions.get(root.getKey());
            if (pythonExtension != null) {
                builder.putPythonModules(pythonExtension.getModule().toString(), root.getValue().getPath());
                continue;
            }

            // A root named after the top-level target is our native starter.
            if (root.getKey().equals(buildTarget)) {
                starterPath = root.getValue().getPath();
                continue;
            }

            // Otherwise, add it as a native library.
            NativeLinkTarget target = Preconditions.checkNotNull(roots.getIncludedRoots().get(root.getKey()),
                    "%s: linked unexpected omnibus root: %s", buildTarget, root.getKey());
            NativeLinkTargetMode mode = target.getNativeLinkTargetMode(cxxPlatform);
            String soname = Preconditions.checkNotNull(mode.getLibraryName().orElse(null),
                    "%s: omnibus library for %s was built without soname", buildTarget, root.getKey());
            builder.putNativeLibraries(soname, root.getValue().getPath());
        }

        // Add all remaining libraries as native libraries.
        for (OmnibusLibrary library : libraries.getLibraries()) {
            builder.putNativeLibraries(library.getSoname(), library.getPath());
        }

    } else {

        // For regular linking, add all Lua extensions as modules and their deps as native linkable
        // roots.
        for (Map.Entry<BuildTarget, CxxLuaExtension> entry : luaExtensions.entrySet()) {
            CxxLuaExtension extension = entry.getValue();
            builder.putModules(extension.getModule(cxxPlatform), extension.getExtension(cxxPlatform));
            nativeLinkableRoots
                    .putAll(Maps.uniqueIndex(extension.getNativeLinkTargetDeps(cxxPlatform, graphBuilder),
                            NativeLinkable::getBuildTarget));
        }

        // Add in native executable deps.
        if (starter instanceof NativeExecutableStarter) {
            NativeExecutableStarter executableStarter = (NativeExecutableStarter) starter;
            nativeLinkableRoots.putAll(
                    Maps.uniqueIndex(executableStarter.getNativeStarterDeps(), NativeLinkable::getBuildTarget));
        }

        // For regular linking, add all extensions via the package components interface and their
        // python-platform specific deps to the native linkables.
        for (Map.Entry<BuildTarget, CxxPythonExtension> entry : pythonExtensions.entrySet()) {
            PythonPackageComponents components = entry.getValue().getPythonPackageComponents(pythonPlatform,
                    cxxPlatform, graphBuilder);
            builder.putAllPythonModules(MoreMaps.transformKeys(components.getModules(), Object::toString));
            builder.putAllNativeLibraries(
                    MoreMaps.transformKeys(components.getNativeLibraries(), Object::toString));
            nativeLinkableRoots.putAll(Maps.uniqueIndex(entry.getValue().getNativeLinkTarget(pythonPlatform)
                    .getNativeLinkTargetDeps(cxxPlatform, graphBuilder), NativeLinkable::getBuildTarget));
        }

        // Add shared libraries from all native linkables.
        for (NativeLinkable nativeLinkable : NativeLinkables
                .getTransitiveNativeLinkables(cxxPlatform, graphBuilder, nativeLinkableRoots.values())
                .values()) {
            NativeLinkable.Linkage linkage = nativeLinkable.getPreferredLinkage(cxxPlatform, graphBuilder);
            if (linkage != NativeLinkable.Linkage.STATIC) {
                builder.putAllNativeLibraries(nativeLinkable.getSharedLibraries(cxxPlatform, graphBuilder));
            }
        }
    }

    // If an explicit starter path override hasn't been set (e.g. from omnibus linking), default to
    // building one directly from the starter.
    if (starterPath == null) {
        starterPath = starter.build();
    }

    return LuaBinaryPackageComponents.of(starterPath, builder.build());
}

From source file:org.immutables.sequence.Sequence.java

/**
 * Returns an immutable map for which the {@link java.util.Map#values} are the elements of this
 * {@code Sequence} in the given order, and each key is the product of invoking a supplied
 * function on its corresponding value.//w w w  .jav a  2  s. c o  m
 * @param <K> the key type
 * @param keyFunction the function used to produce the key for each value
 * @return the immutable map
 * @since 14.0
 */
public final <K> ImmutableMap<K, E> uniqueIndex(Function<? super E, K> keyFunction) {
    return Maps.uniqueIndex(iterable, keyFunction::apply);
}

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

private static final void populateDefaultItemSelectionParameters(final BlueprintElement blueprintElement,
        final String segmentId, final ItemSelectionAlgorithm itemSelectionAlgorithm) {
    if (itemSelectionAlgorithm != null && itemSelectionAlgorithm.getBlueprintParameters() != null) {
        blueprintElement.getBlueprintElementValueMap().get(segmentId)
                .setItemSelectionParameters(Maps.transformValues(
                        Maps.uniqueIndex(itemSelectionAlgorithm.getBlueprintParameters(),
                                ItemSelectionAlgorithmHelper.ISA_PARAMETER_NAME_TRANSFORMER),
                        ItemSelectionAlgorithmHelper.ISA_PARAMETER_DEFAULT_VALUE_TRANSFORMER));
    } else {//from  w  w w.  j  a v  a2s  . c  om
        blueprintElement.getBlueprintElementValueMap().get(segmentId).setItemSelectionParameters(null);
    }
}

From source file:org.opentestsystem.authoring.testauth.publish.BasePublisherHelper.java

protected ItemPool setupItemPoolData(final Assessment assessment, final List<Item> itemList,
        final List<Segment> segmentList, final List<AffinityGroup> affinityGroupList, final String version) {
    final String assessmentId = assessment.getAssessmentId();
    final String assessmentUniqueId = buildIdentifier(assessment.getName(), assessment.getLabel(), version)
            .getUniqueId();/*from w  w w  .j  a v a 2 s .co  m*/
    final ItemPool itemPool = new ItemPool();
    final List<ItemGroup> itemGroupList = this.itemGroupService.getItemGroupsByAssessment(assessmentId);
    final Map<String, ItemGroup> itemGroupMap = Maps.newHashMap();
    if (!CollectionUtils.isEmpty(itemGroupList)) {
        itemGroupMap.putAll(Maps.uniqueIndex(itemGroupList, ITEMGROUP_MAPKEY_TRANSFORMER));
    }
    itemPool.setTestItemList(nullsafeListTransform(itemList,
            ITEM_TESTITEM_TRANSFORMER.getInstance(itemGroupMap,
                    Maps.uniqueIndex(segmentList, SEGMENT_KEYID_TRANSFORMER),
                    Maps.uniqueIndex(affinityGroupList, AFFINITY_GROUP_KEYID_TRANSFORMER), assessmentUniqueId,
                    assessment.getClient())));
    // build up all the passages and use Set to pare down to unique instances
    // itemPool.setPassageList(Lists.newArrayList(Sets.newHashSet(nullsafeListTransform(itemList, ITEM_PASSAGE_TRANSFORMER))));
    // unique by uniqueId
    itemPool.setPassageList(
            buildUniquePassegesByUniqueId(nullsafeListTransform(itemList, ITEM_PASSAGE_TRANSFORMER)));

    final List<Enemy> enemyList = this.enemyService.getEnemiesByAssessmentId(assessmentId);
    if (!CollectionUtils.isEmpty(enemyList)) {
        final List<TestEnemyGroup> testEnemyGroupList = Lists.newArrayList();

        final Map<String, Collection<Enemy>> enemy1MultiMap = Multimaps
                .index(enemyList, ENEMY_TO_ENEMYID1_TRANSFORMER).asMap();
        for (final String enemy1Id : enemy1MultiMap.keySet()) {
            final List<Enemy> enemy1List = this.enemyService.getEnemiesByAssessmentIdAndObjectId1(assessmentId,
                    enemy1Id);
            testEnemyGroupList.add(new TestEnemyGroup(
                    buildTestEnemyGroupIdentifier(enemy1List.get(0).getObject1(), assessment.getItemBank()),
                    nullsafeListTransform(enemy1List,
                            ENEMY1_TRANSFORMER.getInstance(assessment.getItemBank()))));
        }
        final Map<String, Collection<Enemy>> enemy2MultiMap = Multimaps
                .index(enemyList, ENEMY_TO_ENEMYID2_TRANSFORMER).asMap();
        for (final String enemy2Id : enemy2MultiMap.keySet()) {
            final List<Enemy> enemy2List = this.enemyService.getEnemiesByAssessmentIdAndObjectId2(assessmentId,
                    enemy2Id);
            testEnemyGroupList.add(new TestEnemyGroup(
                    buildTestEnemyGroupIdentifier(enemy2List.get(0).getObject2(), assessment.getItemBank()),
                    nullsafeListTransform(enemy2List,
                            ENEMY2_TRANSFORMER.getInstance(assessment.getItemBank()))));
        }

        itemPool.setTestEnemyGroupList(testEnemyGroupList);
    }
    return itemPool;
}