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.apache.aurora.scheduler.thrift.ReadOnlySchedulerImpl.java

@Override
public Response getConfigSummary(JobKey job) throws TException {
    IJobKey jobKey = JobKeys.assertValid(IJobKey.build(job));

    Iterable<IAssignedTask> assignedTasks = Iterables.transform(
            Storage.Util.fetchTasks(storage, Query.jobScoped(jobKey).active()),
            IScheduledTask::getAssignedTask);
    Map<Integer, ITaskConfig> tasksByInstance = Maps.transformValues(
            Maps.uniqueIndex(assignedTasks, IAssignedTask::getInstanceId), IAssignedTask::getTask);
    Set<ConfigGroup> groups = instancesToConfigGroups(tasksByInstance);

    return ok(Result.configSummaryResult(new ConfigSummaryResult().setSummary(new ConfigSummary(job, groups))));
}

From source file:net.minecraftforge.fml.common.Loader.java

/**
 * Sort the mods into a sorted list, using dependency information from the
 * containers. The sorting is performed using a {@link TopologicalSort}
 * based on the pre- and post- dependency information provided by the mods.
 *///from  w ww .  j  a v a2s.com
private void sortModList() {
    FMLLog.finer("Verifying mod requirements are satisfied");
    try {
        BiMap<String, ArtifactVersion> modVersions = HashBiMap.create();
        for (ModContainer mod : Iterables.concat(getActiveModList(), ModAPIManager.INSTANCE.getAPIList())) {
            modVersions.put(mod.getModId(), mod.getProcessedVersion());
        }

        ArrayListMultimap<String, String> reqList = ArrayListMultimap.create();
        for (ModContainer mod : getActiveModList()) {
            if (!mod.acceptableMinecraftVersionRange().containsVersion(minecraft.getProcessedVersion())) {
                FMLLog.severe(
                        "The mod %s does not wish to run in Minecraft version %s. You will have to remove it to play.",
                        mod.getModId(), getMCVersionString());
                throw new WrongMinecraftVersionException(mod);
            }
            Map<String, ArtifactVersion> names = Maps.uniqueIndex(mod.getRequirements(),
                    new ArtifactVersionNameFunction());
            Set<ArtifactVersion> versionMissingMods = Sets.newHashSet();

            Set<String> missingMods = Sets.difference(names.keySet(), modVersions.keySet());
            if (!missingMods.isEmpty()) {
                FMLLog.severe("The mod %s (%s) requires mods %s to be available", mod.getModId(), mod.getName(),
                        missingMods);
                for (String modid : missingMods) {
                    versionMissingMods.add(names.get(modid));
                }
                throw new MissingModsException(versionMissingMods, mod.getModId(), mod.getName());
            }
            reqList.putAll(mod.getModId(), names.keySet());
            ImmutableList<ArtifactVersion> allDeps = ImmutableList.<ArtifactVersion>builder()
                    .addAll(mod.getDependants()).addAll(mod.getDependencies()).build();
            for (ArtifactVersion v : allDeps) {
                if (modVersions.containsKey(v.getLabel())) {
                    if (!v.containsVersion(modVersions.get(v.getLabel()))) {
                        versionMissingMods.add(v);
                    }
                }
            }
            if (!versionMissingMods.isEmpty()) {
                FMLLog.severe("The mod %s (%s) requires mod versions %s to be available", mod.getModId(),
                        mod.getName(), versionMissingMods);
                throw new MissingModsException(versionMissingMods, mod.getModId(), mod.getName());
            }
        }

        FMLLog.finer("All mod requirements are satisfied");

        reverseDependencies = Multimaps.invertFrom(reqList, ArrayListMultimap.<String, String>create());
        ModSorter sorter = new ModSorter(getActiveModList(), namedMods);

        try {
            FMLLog.finer("Sorting mods into an ordered list");
            List<ModContainer> sortedMods = sorter.sort();
            // Reset active list to the sorted list
            modController.getActiveModList().clear();
            modController.getActiveModList().addAll(sortedMods);
            // And inject the sorted list into the overall list
            mods.removeAll(sortedMods);
            sortedMods.addAll(mods);
            mods = sortedMods;
            FMLLog.finer("Mod sorting completed successfully");
        } catch (ModSortingException sortException) {
            FMLLog.severe(
                    "A dependency cycle was detected in the input mod set so an ordering cannot be determined");
            SortingExceptionData<ModContainer> exceptionData = sortException.getExceptionData();
            FMLLog.severe("The first mod in the cycle is %s", exceptionData.getFirstBadNode());
            FMLLog.severe("The mod cycle involves");
            for (ModContainer mc : exceptionData.getVisitedNodes()) {
                FMLLog.severe("%s : before: %s, after: %s", mc.toString(), mc.getDependants(),
                        mc.getDependencies());
            }
            FMLLog.log(Level.ERROR, sortException, "The full error");
            throw sortException;
        }
    } finally {
        FMLLog.fine("Mod sorting data");
        int unprintedMods = mods.size();
        for (ModContainer mod : getActiveModList()) {
            if (!mod.isImmutable()) {
                FMLLog.fine("\t%s(%s:%s): %s (%s)", mod.getModId(), mod.getName(), mod.getVersion(),
                        mod.getSource().getName(), mod.getSortingRules());
                unprintedMods--;
            }
        }
        if (unprintedMods == mods.size()) {
            FMLLog.fine("No user mods found to sort");
        }
    }

}

From source file:org.geogig.geoserver.web.repository.RepositoryEditFormPanel.java

private void onSave(RepositoryInfo repoInfo, AjaxRequestTarget target) {
    RepositoryManager manager = RepositoryManager.get();
    // update remotes
    Repository geogig;/*from   ww w . ja v  a2  s. co m*/
    try {
        repoInfo = manager.save(repoInfo);
        geogig = manager.getRepository(repoInfo.getId());
    } catch (Exception e) {
        form.error("Unable to connect to repository " + repoInfo.getLocation() + "\n" + e.getMessage());
        target.add(form);
        return;
    }

    Function<RemoteInfo, Integer> keyFunction = new Function<RemoteInfo, Integer>() {
        @Override
        public Integer apply(RemoteInfo r) {
            return r.getId();
        }
    };

    Map<Integer, RemoteInfo> currentRemotes = new HashMap<>(
            Maps.uniqueIndex(loadRemoteInfos(repoInfo), keyFunction));

    Set<RemoteInfo> newRemotes = Sets.newHashSet(remotes.getRemotes());
    if (!currentRemotes.isEmpty() || !newRemotes.isEmpty()) {
        GeogigTransaction tx = geogig.command(TransactionBegin.class).call();
        try {
            updateRemotes(tx, currentRemotes, newRemotes);
            tx.commit();
        } catch (Exception e) {
            try {
                tx.abort();
            } finally {
                form.error(e.getMessage());
                target.add(form);
            }
            return;
        }
    }
    Map<String, String> currentLocalConfig = loadConfig(repoInfo, false);
    updateConfig(geogig.context(), currentLocalConfig, Lists.newArrayList(localConfig.getConfigs()), false);
    Map<String, String> currentGlobalConfig = loadConfig(repoInfo, true);
    updateConfig(geogig.context(), currentGlobalConfig, Lists.newArrayList(globalConfig.getConfigs()), true);
    saved(repoInfo, target);
}

From source file:org.gradle.caching.internal.tasks.TarTaskOutputPacker.java

private void unpack(TaskOutputsInternal taskOutputs, TarInputStream tarInput,
        TaskOutputOriginReader readOriginAction) throws IOException {
    Map<String, TaskOutputFilePropertySpec> propertySpecs = Maps.uniqueIndex(taskOutputs.getFileProperties(),
            new Function<TaskFilePropertySpec, String>() {
                @Override// ww w  .  java  2  s  .c om
                public String apply(TaskFilePropertySpec propertySpec) {
                    return propertySpec.getPropertyName();
                }
            });
    boolean originSeen = false;
    TarEntry entry;
    while ((entry = tarInput.getNextEntry()) != null) {
        String name = entry.getName();

        if (name.equals(METADATA_PATH)) {
            // handle origin metadata
            originSeen = true;
            readOriginAction.execute(new CloseShieldInputStream(tarInput));
        } else {
            // handle output property
            Matcher matcher = PROPERTY_PATH.matcher(name);
            if (!matcher.matches()) {
                throw new IllegalStateException("Cached result format error, invalid contents: " + name);
            }
            String propertyName = matcher.group(1);
            CacheableTaskOutputFilePropertySpec propertySpec = (CacheableTaskOutputFilePropertySpec) propertySpecs
                    .get(propertyName);
            if (propertySpec == null) {
                throw new IllegalStateException(
                        String.format("No output property '%s' registered", propertyName));
            }

            File specRoot = propertySpec.getOutputFile();
            String path = matcher.group(2);
            File outputFile;
            if (Strings.isNullOrEmpty(path)) {
                outputFile = specRoot;
            } else {
                outputFile = new File(specRoot, path);
            }
            if (entry.isDirectory()) {
                if (propertySpec.getOutputType() != OutputType.DIRECTORY) {
                    throw new IllegalStateException(
                            "Property should be an output directory property: " + propertyName);
                }
                FileUtils.forceMkdir(outputFile);
            } else {
                Files.asByteSink(outputFile).writeFrom(tarInput);
            }
            //noinspection OctalInteger
            fileSystem.chmod(outputFile, entry.getMode() & 0777);
            long lastModified = getModificationTime(entry);
            if (!outputFile.setLastModified(lastModified)) {
                throw new UnsupportedOperationException(
                        String.format("Could not set modification time for '%s'", outputFile));
            }
        }
    }
    if (!originSeen) {
        throw new IllegalStateException("Cached result format error, no origin metadata was found.");
    }
}

From source file:biz.ganttproject.impex.csv.TaskRecords.java

@Override
protected void postProcess() {
    for (Map.Entry<String, Task> wbsEntry : myWbsMap.entrySet()) {
        String outlineNumber = wbsEntry.getKey();
        List<String> components = Arrays.asList(outlineNumber.split("\\."));
        if (components.size() <= 1) {
            continue;
        }// w  ww .ja va 2 s . co  m
        String parentOutlineNumber = Joiner.on('.').join(components.subList(0, components.size() - 1));
        Task parentTask = myWbsMap.get(parentOutlineNumber);
        if (parentTask == null) {
            continue;
        }
        taskManager.getTaskHierarchy().move(wbsEntry.getValue(), parentTask, 0);
    }
    if (resourceManager != null) {
        Map<String, HumanResource> resourceMap = Maps.uniqueIndex(resourceManager.getResources(),
                new Function<HumanResource, String>() {
                    @Override
                    public String apply(HumanResource input) {
                        return input.getName();
                    }
                });
        for (Entry<Task, String> assignment : myAssignmentMap.entrySet()) {
            if (assignment.getValue() == null) {
                continue;
            }
            String[] names = assignment.getValue().split(";");
            for (String name : names) {
                HumanResource resource = resourceMap.get(name);
                if (resource != null) {
                    assignment.getKey().getAssignmentCollection().addAssignment(resource);
                }
            }
        }
    }
    Function<Integer, Task> taskIndex = new Function<Integer, Task>() {
        @Override
        public Task apply(Integer id) {
            return myTaskIdMap.get(String.valueOf(id));
        }
    };
    for (Entry<Task, String> entry : myPredecessorMap.entrySet()) {
        if (entry.getValue() == null) {
            continue;
        }
        Task successor = entry.getKey();
        String[] depSpecs = entry.getValue().split(";");
        try {
            Map<Integer, Supplier<TaskDependency>> constructors = TaskProperties
                    .parseDependencies(Arrays.asList(depSpecs), successor, taskIndex);
            for (Supplier<TaskDependency> constructor : constructors.values()) {
                constructor.get();
            }
        } catch (IllegalArgumentException e) {
            GPLogger.logToLogger(String.format("%s\nwhen parsing predecessor specification %s of task %s",
                    e.getMessage(), entry.getValue(), successor));
        } catch (TaskDependencyException e) {
            GPLogger.logToLogger(e);
        }
    }
}

From source file:com.b2international.snowowl.snomed.datastore.id.memory.DefaultSnomedIdentifierService.java

@Override
public Map<String, SctId> getSctIds(final Set<String> componentIds) {
    final Query<SctId> getSctIdsQuery = Query.select(SctId.class)
            .where(Expressions.matchAny(DocumentMapping._ID, componentIds)).limit(componentIds.size()).build();

    final Hits<SctId> existingIds = store.read(index -> index.search(getSctIdsQuery));
    final Map<String, SctId> existingIdsMap = Maps.uniqueIndex(existingIds, SctId::getSctid);

    if (existingIdsMap.size() == componentIds.size()) {
        return existingIdsMap;
    } else {//from   w w w .  ja  va  2s.c o m
        final Set<String> knownComponentIds = existingIdsMap.keySet();
        final Set<String> difference = ImmutableSet.copyOf(Sets.difference(componentIds, knownComponentIds));

        final ImmutableMap.Builder<String, SctId> resultBuilder = ImmutableMap.builder();
        resultBuilder.putAll(existingIdsMap);

        for (final String componentId : difference) {
            resultBuilder.put(componentId, buildSctId(componentId, IdentifierStatus.AVAILABLE));
        }

        return resultBuilder.build();
    }
}

From source file:org.jclouds.compute.config.BaseComputeServiceContextModule.java

@Provides
@Singleton/*from  www .  j a v a2s  .c  om*/
protected Supplier<Map<String, ? extends Image>> provideImageMap(
        @Memoized Supplier<Set<? extends Image>> images) {
    return Suppliers.compose(new Function<Set<? extends Image>, Map<String, ? extends Image>>() {

        @Override
        public Map<String, ? extends Image> apply(Set<? extends Image> from) {
            return Maps.uniqueIndex(from, new Function<Image, String>() {

                @Override
                public String apply(Image from) {
                    return from.getId();
                }

            });
        }

    }, images);
}

From source file:com.palantir.atlasdb.sweep.BackgroundSweeperImpl.java

@Nullable
private SweepProgressRowResult chooseNextTableToSweep(SweepTransaction t) {
    Set<String> allTables = Sets.difference(kvs.getAllTableNames(), AtlasDbConstants.hiddenTables);
    SweepPriorityTable oldPriorityTable = tableFactory.getSweepPriorityTable(t);
    SweepPriorityTable newPriorityTable = tableFactory.getSweepPriorityTable(t.delegate());

    // We read priorities from the past because we should prioritize based on what the sweeper will
    // actually be able to sweep. We read priorities from the present to make sure we don't repeatedly
    // sweep the same table while waiting for the past to catch up.
    List<SweepPriorityRowResult> oldPriorities = oldPriorityTable.getAllRowsUnordered().immutableCopy();
    List<SweepPriorityRowResult> newPriorities = newPriorityTable.getAllRowsUnordered().immutableCopy();
    Map<String, SweepPriorityRowResult> newPrioritiesByTableName = Maps.uniqueIndex(newPriorities,
            Functions.compose(SweepPriorityRow.getFullTableNameFun(), SweepPriorityRowResult.getRowNameFun()));
    String tableName = getTableToSweep(t, allTables, oldPriorities, newPrioritiesByTableName);
    if (tableName == null) {
        return null;
    }/*from  www .  ja  v  a2s  .  c  om*/
    RowResult<byte[]> rawResult = RowResult.<byte[]>create(SweepProgressRow.of(0).persistToBytes(),
            ImmutableSortedMap.<byte[], byte[]>orderedBy(UnsignedBytes.lexicographicalComparator())
                    .put(SweepProgressTable.SweepProgressNamedColumn.FULL_TABLE_NAME.getShortName(),
                            SweepProgressTable.FullTableName.of(tableName).persistValue())
                    .build());

    log.debug("Now starting to sweep {}.", tableName);
    return SweepProgressRowResult.of(rawResult);
}

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

@NotNull
public static Map<Integer, Todo> updateTodoMapWithCustomPropertiesAndWriteToDatabase(
        LicenseService.Iface licenseClient, Map<Integer, Todo> todoMap,
        Map<Integer, PropertyWithValue> customPropertiesMap, Map<Integer, Set<Integer>> todoPropertiesMap,
        User user) throws TException {
    for (Integer todoId : todoPropertiesMap.keySet()) {
        Todo todo = todoMap.get(todoId);
        if (!todo.isSetCustomPropertyToValue()) {
            todo.setCustomPropertyToValue(new HashMap<>());
        }/*  w  ww  .  j a  v a  2 s. c o  m*/
        for (Integer propertyWithValueId : todoPropertiesMap.get(todoId)) {
            PropertyWithValue propertyWithValue = customPropertiesMap.get(propertyWithValueId);
            todo.getCustomPropertyToValue().put(propertyWithValue.getProperty(), propertyWithValue.getValue());
        }
    }

    if (todoMap.values().size() > 0) {
        final List<Todo> addedTodos = licenseClient
                .addTodos(todoMap.values().stream().collect(Collectors.toList()), user);
        if (addedTodos != null) {
            final ImmutableMap<Integer, Todo> addedTodoMap = Maps.uniqueIndex(addedTodos, getTodoIdentifier());
            todoMap.putAll(addedTodoMap);
        }
    }
    return todoMap;
}

From source file:org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl.java

@Override
public synchronized void onCapabilitiesAdded(final Set<Capability> addedCaps) {
    // FIXME howto check for duplicates
    this.capabilities.putAll(Maps.uniqueIndex(addedCaps, CAPABILITY_TO_URI));
    notifyListeners();//from   w  w  w.  ja va2 s  . co  m
}