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.presto.mysql.CachingMySQLSchemaProvider.java

private Map<String, String> loadAllTables(final String databaseName) throws Exception {
    return retry().stopOn(NotFoundException.class).stopOnIllegalExceptions().run("getAllTables",
            new Callable<Map<String, String>>() {
                @Override//from   w  w w  .  j a v  a 2s.  c om
                public Map<String, String> call() throws SchemaNotFoundException {
                    String caseSensitiveDatabaseName = getCaseSensitiveSchemaName(databaseName);
                    if (caseSensitiveDatabaseName == null) {
                        caseSensitiveDatabaseName = databaseName;
                    }
                    List<String> tables = session.getAllTables(caseSensitiveDatabaseName);
                    Map<String, String> nameMap = Maps.uniqueIndex(tables, toLowerCase());

                    if (tables.isEmpty()) {
                        // Check to see if the database exists
                        session.getSchema(databaseName);
                    }
                    return nameMap;
                }
            });
}

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

@NotNull
public static Map<Integer, Todo> getTodoMapAndWriteMissingToDatabase(LicenseService.Iface licenseClient,
        Map<Integer, Obligation> obligationMap, Map<Integer, Set<Integer>> obligationTodoMapping,
        InputStream in, User user) throws TException {
    List<CSVRecord> todoRecords = ImportCSV.readAsCSVRecords(in);
    final List<Todo> todos = CommonUtils.nullToEmptyList(licenseClient.getTodos());
    Map<Integer, Todo> todoMap = Maps.newHashMap(Maps.uniqueIndex(todos, getTodoIdentifier()));
    final List<Todo> todosToAdd = ConvertRecord.convertTodos(todoRecords);
    final ImmutableList<Todo> filteredTodos = getElementsWithIdentifiersNotInMap(getTodoIdentifier(), todoMap,
            todosToAdd);/*w w  w.  j  av  a 2  s.c  o  m*/
    final ImmutableMap<Integer, Todo> filteredMap = Maps.uniqueIndex(filteredTodos, getTodoIdentifier());
    putToTodos(obligationMap, filteredMap, obligationTodoMapping);
    //insertCustomProperties

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

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

private static ImmutableMap<WindowId, IViewInvalidationAdvisor> makeViewInvalidationAdvisorsMap(
        final List<IViewInvalidationAdvisor> viewInvalidationAdvisors) {
    try {//  w w  w .  j  a  v a 2s .  c  o  m
        return Maps.uniqueIndex(viewInvalidationAdvisors, advisor -> {
            final WindowId windowId = advisor.getWindowId();
            Check.assumeNotNull(windowId, "windowId shall not be null for {}", advisor);
            return windowId;
        });
    } catch (IllegalArgumentException e) {
        final String message = "The given collection of " + IViewInvalidationAdvisor.class
                + " implementors contains more than one element with the same window-id";
        throw new AdempiereException(message, e)
                .setParameter("viewInvalidationAdvisors", viewInvalidationAdvisors).appendParametersToMessage();
    }
}

From source file:org.gradle.api.internal.tasks.cache.TarTaskOutputPacker.java

private void unpack(TaskOutputsInternal taskOutputs, TarInputStream tarInput) throws IOException {
    Map<String, TaskOutputFilePropertySpec> propertySpecs = Maps.uniqueIndex(taskOutputs.getFileProperties(),
            new Function<TaskFilePropertySpec, String>() {
                @Override/*from   www  .  j a  va 2  s.  c  o m*/
                public String apply(TaskFilePropertySpec propertySpec) {
                    return propertySpec.getPropertyName();
                }
            });
    TarEntry entry;
    while ((entry = tarInput.getNextEntry()) != null) {
        String name = entry.getName();
        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 IOException(String.format("Could not set modification time for '%s'", outputFile));
        }
    }
}

From source file:org.sonar.server.test.ws.ListAction.java

private Map<String, ComponentDto> buildComponentsByTestFileUuid(DbSession dbSession, List<TestDoc> tests) {
    List<String> fileUuids = Lists.transform(tests, new TestToFileUuidFunction());
    List<ComponentDto> components = dbClient.componentDao().selectByUuids(dbSession, fileUuids);

    return Maps.uniqueIndex(components, ComponentDto::uuid);
}

From source file:net.sourceforge.ganttproject.io.GanttCSVOpen.java

private static RecordGroup createTaskRecordGroup(final TaskManager taskManager,
        final HumanResourceManager resourceManager) {
    return new RecordGroup(Sets.newHashSet(getFieldNames(TaskFields.values()))) {
        private Map<Task, String> myAssignmentMap = Maps.newHashMap();
        private Map<Task, String> myPredecessorMap = Maps.newHashMap();
        private Map<String, Task> myTaskIdMap = Maps.newHashMap();

        @Override/*from   w  ww  .j a va  2 s  .  c  o  m*/
        public void setHeader(List<String> header) {
            super.setHeader(header);
            createCustomProperties(getCustomFields(), taskManager.getCustomPropertyManager());
        }

        @Override
        protected void process(CSVRecord record) {
            assert record.size() > 0;
            // Create the task
            TaskManager.TaskBuilder builder = taskManager.newTaskBuilder()
                    .withName(record.get(TaskFields.NAME.toString()))
                    .withStartDate(language.parseDate(record.get(TaskFields.BEGIN_DATE.toString())))
                    .withWebLink(record.get(TaskFields.WEB_LINK.toString()))
                    .withNotes(record.get(TaskFields.NOTES.toString()));
            if (record.get(TaskDefaultColumn.DURATION.getName()) != null) {
                builder = builder.withDuration(
                        taskManager.createLength(record.get(TaskDefaultColumn.DURATION.getName())));
            }
            if (Objects.equal(record.get(TaskFields.BEGIN_DATE.toString()),
                    record.get(TaskFields.END_DATE.toString()))
                    && "0".equals(record.get(TaskDefaultColumn.DURATION.getName()))) {
                builder = builder.withLegacyMilestone();
            }
            if (!Strings.isNullOrEmpty(record.get(TaskFields.COMPLETION.toString()))) {
                builder = builder
                        .withCompletion(Integer.parseInt(record.get(TaskFields.COMPLETION.toString())));
            }
            Task task = builder.build();

            if (record.get(TaskDefaultColumn.ID.getName()) != null) {
                myTaskIdMap.put(record.get(TaskDefaultColumn.ID.getName()), task);
            }
            myAssignmentMap.put(task, record.get(TaskFields.RESOURCES.toString()));
            myPredecessorMap.put(task, record.get(TaskDefaultColumn.PREDECESSORS.getName()));
            for (String customField : getCustomFields()) {
                String value = record.get(customField);
                CustomPropertyDefinition def = taskManager.getCustomPropertyManager()
                        .getCustomPropertyDefinition(customField);
                if (def == null) {
                    GPLogger.logToLogger(
                            "Can't find custom field with name=" + customField + " value=" + value);
                    continue;
                }
                if (value != null) {
                    task.getCustomValues().addCustomProperty(def, value);
                }
            }
        }

        @Override
        protected void postProcess() {
            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()) {
                    String[] names = assignment.getValue().split(";");
                    for (String name : names) {
                        HumanResource resource = resourceMap.get(name);
                        if (resource != null) {
                            assignment.getKey().getAssignmentCollection().addAssignment(resource);
                        }
                    }
                }
            }
            for (Entry<Task, String> predecessor : myPredecessorMap.entrySet()) {
                if (predecessor.getValue() == null) {
                    continue;
                }
                String[] ids = predecessor.getValue().split(";");
                for (String id : ids) {
                    Task dependee = myTaskIdMap.get(id);
                    if (dependee != null) {
                        try {
                            taskManager.getDependencyCollection().createDependency(predecessor.getKey(),
                                    dependee);
                        } catch (TaskDependencyException e) {
                            GPLogger.logToLogger(e);
                        }
                    }
                }
            }
        }
    };
}

From source file:org.kie.workbench.common.screens.projecteditor.client.build.BuildExecutor.java

private void buildDeployWithMultipleServerTemplatesAvailable(Collection<ServerTemplate> serverTemplates,
        String defaultContainerId, String defaultContainerAlias, boolean defaultStartContainer) {
    final Map<String, ServerTemplate> serverTemplatesIds = Maps.uniqueIndex(serverTemplates, s -> s.getId());
    final Map<String, Set<String>> containerNames = Maps.transformEntries(serverTemplatesIds,
            (id, server) -> FluentIterable.from(server.getContainersSpec()).transform(c -> c.getContainerName())
                    .toSet());//from www.  j  av  a  2s  .c  o  m
    deploymentScreenPopupView.addServerTemplates(
            FluentIterable.from(serverTemplatesIds.keySet()).toSortedSet(String.CASE_INSENSITIVE_ORDER));
    deploymentScreenPopupView.setValidateExistingContainerCallback(containerName -> FluentIterable
            .from(containerNames.get(deploymentScreenPopupView.getServerTemplate())).contains(containerName));
    deploymentScreenPopupView.setContainerId(defaultContainerId);
    deploymentScreenPopupView.setContainerAlias(defaultContainerAlias);
    deploymentScreenPopupView.setStartContainer(defaultStartContainer);
    deploymentScreenPopupView.configure(() -> {
        final String containerId = deploymentScreenPopupView.getContainerId();
        final String containerAlias = deploymentScreenPopupView.getContainerAlias();
        final String serverTemplate = deploymentScreenPopupView.getServerTemplate();
        final boolean startContainer = deploymentScreenPopupView.getStartContainer();

        getSafeExecutedCommand(getBuildDeployProvisionCommand(DeploymentMode.VALIDATED, containerId,
                containerAlias, serverTemplate, startContainer)).execute();

        deploymentScreenPopupView.hide();
    });
    deploymentScreenPopupView.show();
}

From source file:cpw.mods.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.
 *//*ww w.j  a  v  a2 s  . c om*/
private void sortModList() {
    FMLLog.finer("Verifying mod requirements are satisfied");
    try {
        BiMap<String, ArtifactVersion> modVersions = HashBiMap.create();
        for (ModContainer mod : getActiveModList()) {
            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);
            }
            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);
            }
        }

        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:io.prestosql.plugin.jmx.JmxMetadata.java

@Override
public Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle) {
    JmxTableHandle jmxTableHandle = (JmxTableHandle) tableHandle;
    return ImmutableMap.copyOf(Maps.uniqueIndex(jmxTableHandle.getColumnHandles(),
            column -> column.getColumnName().toLowerCase(ENGLISH)));
}

From source file:com.b2international.snowowl.snomed.datastore.index.change.ConceptChangeProcessor.java

@Override
public void process(ICDOCommitChangeSet commitChangeSet, RevisionSearcher searcher) throws IOException {
    // process concept deletions first
    deleteRevisions(SnomedConceptDocument.class,
            commitChangeSet.getDetachedComponents(SnomedPackage.Literals.CONCEPT));
    // collect member changes
    this.referringRefSets = HashMultimap.create(memberChangeProcessor.process(commitChangeSet, searcher));

    // collect new and dirty reference sets
    final Map<String, SnomedRefSet> newAndDirtyRefSetsById = newHashMap(FluentIterable
            .from(Iterables.concat(commitChangeSet.getNewComponents(), commitChangeSet.getDirtyComponents()))
            .filter(SnomedRefSet.class).uniqueIndex(new Function<SnomedRefSet, String>() {
                @Override//from ww w  .j  a va 2  s.  com
                public String apply(SnomedRefSet input) {
                    return input.getIdentifierId();
                }
            }));
    // collect deleted reference sets
    final Set<Long> deletedRefSets = newHashSet(CDOIDUtils.createCdoIdToLong(
            commitChangeSet.getDetachedComponents(SnomedRefSetPackage.Literals.SNOMED_REF_SET)));

    // index new concepts
    for (final Concept concept : commitChangeSet.getNewComponents(Concept.class)) {
        final String id = concept.getId();
        final Builder doc = SnomedConceptDocument.builder().id(id);
        update(doc, concept, null);
        SnomedRefSet refSet = newAndDirtyRefSetsById.remove(id);
        if (refSet != null) {
            doc.refSet(refSet);
        }
        doc.preferredDescriptions(toDescriptionFragments(concept));
        indexNewRevision(concept.cdoID(), doc.build());
    }

    // collect dirty concepts for reindex
    final Map<String, Concept> dirtyConceptsById = Maps
            .uniqueIndex(commitChangeSet.getDirtyComponents(Concept.class), Concept::getId);

    final Set<String> dirtyConceptIds = collectDirtyConceptIds(searcher, commitChangeSet);

    final Multimap<String, Description> dirtyDescriptionsByConcept = Multimaps
            .index(getDirtyDescriptions(commitChangeSet), d -> d.getConcept().getId());

    // remaining new and dirty reference sets should be connected to a non-new concept, so add them here
    dirtyConceptIds.addAll(newAndDirtyRefSetsById.keySet());
    dirtyConceptIds.addAll(dirtyDescriptionsByConcept.keySet());

    if (!dirtyConceptIds.isEmpty()) {
        // fetch all dirty concept documents by their ID
        final Query<SnomedConceptDocument> query = Query.select(SnomedConceptDocument.class)
                .where(SnomedConceptDocument.Expressions.ids(dirtyConceptIds)).limit(dirtyConceptIds.size())
                .build();
        final Map<String, SnomedConceptDocument> currentConceptDocumentsById = Maps
                .uniqueIndex(searcher.search(query), ComponentUtils.<String>getIdFunction());

        // update dirty concepts
        for (final String id : dirtyConceptIds) {
            final Concept concept = dirtyConceptsById.get(id);
            final SnomedConceptDocument currentDoc = currentConceptDocumentsById.get(id);
            if (currentDoc == null) {
                throw new IllegalStateException("Current concept revision should not be null for: " + id);
            }
            final Builder doc = SnomedConceptDocument.builder(currentDoc);
            update(doc, concept, currentDoc);
            SnomedRefSet refSet = newAndDirtyRefSetsById.remove(id);
            if (refSet != null) {
                doc.refSet(refSet);
            }
            // clear refset props when deleting refset
            if (deletedRefSets.contains(currentDoc.getRefSetStorageKey())) {
                doc.clearRefSet();
            }

            if (concept != null) {
                doc.preferredDescriptions(toDescriptionFragments(concept));
            } else {
                Collection<Description> dirtyDescriptions = dirtyDescriptionsByConcept.get(id);
                if (!dirtyDescriptions.isEmpty()) {
                    Map<String, SnomedDescriptionFragment> newDescriptions = newHashMap(Maps.uniqueIndex(
                            currentDoc.getPreferredDescriptions(), SnomedDescriptionFragment::getId));
                    for (Description dirtyDescription : dirtyDescriptions) {
                        newDescriptions.remove(dirtyDescription.getId());
                        if (dirtyDescription.isActive()
                                && !getPreferredLanguageMembers(dirtyDescription).isEmpty()) {
                            newDescriptions.put(dirtyDescription.getId(),
                                    toDescriptionFragment(dirtyDescription));
                        }
                    }
                    doc.preferredDescriptions(newDescriptions.values().stream()
                            .sorted(DESCRIPTION_FRAGMENT_ORDER).collect(Collectors.toList()));
                } else {
                    doc.preferredDescriptions(currentDoc.getPreferredDescriptions());
                }
            }

            if (concept != null) {
                indexChangedRevision(concept.cdoID(), doc.build());
            } else {
                indexChangedRevision(currentDoc.getStorageKey(), doc.build());
            }
        }
    }
}