Example usage for com.google.common.collect Multimaps transformValues

List of usage examples for com.google.common.collect Multimaps transformValues

Introduction

In this page you can find the example usage for com.google.common.collect Multimaps transformValues.

Prototype

public static <K, V1, V2> ListMultimap<K, V2> transformValues(ListMultimap<K, V1> fromMultimap,
        final Function<? super V1, V2> function) 

Source Link

Document

Returns a view of a ListMultimap where each value is transformed by a function.

Usage

From source file:com.yodle.vantage.component.dao.IssueDao.java

public Map<String, Collection<Issue>> getIssuesTransitivelyAffectingVersions(String component) {
    List<Map<String, Object>> rs = jdbcTemplate.queryForList("MATCH (c_par:Component {name:{1}})"
            + "<-[:VERSION_OF]-(v_par:Version)" + "-[:DEPENDS_ON]->(v:Version)"
            + "<-[:PRECEDES|:AFFECTS*]-(i:Issue)" + "MATCH (v)-[:VERSION_OF]->(c:Component)"
            + "MATCH (i)-[:AFFECTS]->(av:Version)" + "WHERE NOT (v)<-[:PRECEDES|:FIXED_BY*]-(i) "
            + "OPTIONAL MATCH (i)-[:FIXED_BY]->(fv:Version)"
            + "RETURN v_par.version, i.id, i.level, i.message, av.version, fv.version, c.name, v.version",
            component);/*  w  ww. ja  v  a2  s. c o  m*/

    ImmutableListMultimap<String, Map<String, Object>> grouped = Multimaps.index(rs,
            (row -> (String) row.get("v_par.version")));
    return Multimaps.transformValues(grouped, (this::toIssue)).asMap();
}

From source file:com.facebook.buck.cxx.CxxLibraryMetadataFactory.java

public static void addCxxPreprocessorInputFromArgs(Builder cxxPreprocessorInputBuilder, CommonArg args,
        CxxPlatform platform, Function<StringWithMacros, Arg> stringWithMacrosArgFunction) {
    cxxPreprocessorInputBuilder.putAllPreprocessorFlags(
            Multimaps.transformValues(CxxFlags.getLanguageFlagsWithMacros(args.getExportedPreprocessorFlags(),
                    args.getExportedPlatformPreprocessorFlags(), args.getExportedLangPreprocessorFlags(),
                    args.getExportedLangPlatformPreprocessorFlags(), platform), stringWithMacrosArgFunction));
    cxxPreprocessorInputBuilder.addAllFrameworks(args.getFrameworks());
}

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

private ImmutableList<Arg> getExtensionArgs(BuildTarget buildTarget, ProjectFilesystem projectFilesystem,
        ActionGraphBuilder graphBuilder, SourcePathResolver pathResolver, SourcePathRuleFinder ruleFinder,
        CellPathResolver cellRoots, LuaPlatform luaPlatform, CxxLuaExtensionDescriptionArg args) {

    CxxPlatform cxxPlatform = luaPlatform.getCxxPlatform();

    // Extract all C/C++ sources from the constructor arg.
    ImmutableMap<String, CxxSource> srcs = CxxDescriptionEnhancer.parseCxxSources(buildTarget, graphBuilder,
            ruleFinder, pathResolver, cxxPlatform, args);
    ImmutableMap<Path, SourcePath> headers = CxxDescriptionEnhancer.parseHeaders(buildTarget, graphBuilder,
            ruleFinder, pathResolver, Optional.of(cxxPlatform), args);

    // Setup the header symlink tree and combine all the preprocessor input from this rule
    // and all dependencies.
    HeaderSymlinkTree headerSymlinkTree = CxxDescriptionEnhancer.requireHeaderSymlinkTree(buildTarget,
            projectFilesystem, ruleFinder, graphBuilder, cxxPlatform, headers, HeaderVisibility.PRIVATE, true);
    ImmutableSet<BuildRule> deps = args.getCxxDeps().get(graphBuilder, cxxPlatform);
    ImmutableList<CxxPreprocessorInput> cxxPreprocessorInput = ImmutableList.<CxxPreprocessorInput>builder()
            .add(luaPlatform.getLuaCxxLibrary(graphBuilder).getCxxPreprocessorInput(cxxPlatform, graphBuilder))
            .addAll(CxxDescriptionEnhancer.collectCxxPreprocessorInput(buildTarget, cxxPlatform, graphBuilder,
                    deps,/*from  ww w.  j  av a2 s  .co  m*/
                    ImmutableListMultimap.copyOf(Multimaps.transformValues(
                            CxxFlags.getLanguageFlagsWithMacros(args.getPreprocessorFlags(),
                                    args.getPlatformPreprocessorFlags(), args.getLangPreprocessorFlags(),
                                    args.getLangPlatformPreprocessorFlags(), cxxPlatform),
                            f -> CxxDescriptionEnhancer.toStringWithMacrosArgs(buildTarget, cellRoots,
                                    graphBuilder, cxxPlatform, f))),
                    ImmutableList.of(headerSymlinkTree), ImmutableSet.of(),
                    CxxPreprocessables.getTransitiveCxxPreprocessorInput(cxxPlatform, graphBuilder, deps),
                    args.getRawHeaders()))
            .build();

    // Generate rule to build the object files.
    ImmutableMultimap<CxxSource.Type, Arg> compilerFlags = ImmutableListMultimap
            .copyOf(Multimaps.transformValues(
                    CxxFlags.getLanguageFlagsWithMacros(args.getCompilerFlags(),
                            args.getPlatformCompilerFlags(), args.getLangCompilerFlags(),
                            args.getLangPlatformCompilerFlags(), cxxPlatform),
                    f -> CxxDescriptionEnhancer.toStringWithMacrosArgs(buildTarget, cellRoots, graphBuilder,
                            cxxPlatform, f)));
    ImmutableMap<CxxPreprocessAndCompile, SourcePath> picObjects = CxxSourceRuleFactory
            .of(projectFilesystem, buildTarget, graphBuilder, pathResolver, ruleFinder, cxxBuckConfig,
                    cxxPlatform, cxxPreprocessorInput, compilerFlags, args.getPrefixHeader(),
                    args.getPrecompiledHeader(), PicType.PIC)
            .requirePreprocessAndCompileRules(srcs);

    ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();
    CxxFlags.getFlagsWithMacrosWithPlatformMacroExpansion(args.getLinkerFlags(), args.getPlatformLinkerFlags(),
            cxxPlatform).stream()
            .map(f -> CxxDescriptionEnhancer.toStringWithMacrosArgs(buildTarget, cellRoots, graphBuilder,
                    cxxPlatform, f))
            .forEach(argsBuilder::add);

    // Add object files into the args.
    argsBuilder.addAll(SourcePathArg.from(picObjects.values()));

    return argsBuilder.build();
}

From source file:com.b2international.snowowl.snomed.core.ecl.EclExpression.java

public Promise<Multimap<String, Integer>> resolveToConceptsWithGroups(final BranchContext context) {
    if (conceptsWithGroups == null) {
        final Set<String> characteristicTypes = isInferred()
                ? SnomedEclRefinementEvaluator.INFERRED_CHARACTERISTIC_TYPES
                : SnomedEclRefinementEvaluator.STATED_CHARACTERISTIC_TYPES;
        conceptsWithGroups = SnomedRequests.prepareSearchRelationship().all().filterByActive(true)
                .filterByCharacteristicTypes(characteristicTypes).filterBySource(ecl)
                .filterByGroup(1, Integer.MAX_VALUE).setEclExpressionForm(expressionForm)
                .setFields(SnomedRelationshipIndexEntry.Fields.ID,
                        SnomedRelationshipIndexEntry.Fields.SOURCE_ID,
                        SnomedRelationshipIndexEntry.Fields.GROUP)
                .build(context.id(), context.branchPath()).execute(context.service(IEventBus.class))
                .then(new Function<SnomedRelationships, Multimap<String, Integer>>() {
                    @Override//  w w w  .j a  va 2s.co m
                    public Multimap<String, Integer> apply(SnomedRelationships input) {
                        final Multimap<String, SnomedRelationship> relationshipsBySource = Multimaps
                                .index(input, SnomedRelationship::getSourceId);
                        final Multimap<String, Integer> groupsByRelationshipId = Multimaps
                                .transformValues(relationshipsBySource, SnomedRelationship::getGroup);
                        return ImmutableSetMultimap.copyOf(groupsByRelationshipId);
                    }
                });
    }
    return conceptsWithGroups;
}

From source file:com.yodle.vantage.component.dao.IssueDao.java

public Map<Version, Collection<Issue>> getIssuesByDependenciesOf(String component, String version) {
    List<Map<String, Object>> rs = jdbcTemplate.queryForList(
            "MATCH (c_par:Component {name:{1}})<-[:VERSION_OF]-(v_par:Version {version:{2}})-[:DEPENDS_ON]->"
                    + "(v:Version)<-[:PRECEDES|:AFFECTS*]-(i:Issue)" + "MATCH (v)-[:VERSION_OF]->(c:Component)"
                    + "MATCH (i)-[:AFFECTS]->(av:Version)" + "WHERE NOT (v)<-[:PRECEDES|:FIXED_BY*]-(i) "
                    + "OPTIONAL MATCH (i)-[:FIXED_BY]->(fv:Version)"
                    + "RETURN v.version, c.name, i.id, i.level, i.message, av.version, fv.version",
            component, version);//from   w w  w.j a  va 2  s .com

    ImmutableListMultimap<Version, Map<String, Object>> grouped = Multimaps.index(rs,
            (row -> new Version((String) row.get("c.name"), (String) row.get("v.version"))));
    return Multimaps.transformValues(grouped, this::toIssue).asMap();
}

From source file:ru.org.linux.tag.TagPageController.java

private ImmutableMap<String, Object> getForumSection(@Nonnull String tag, int tagId)
        throws TagNotFoundException {
    Section forumSection = sectionService.getSection(Section.SECTION_FORUM);

    TopicListDto topicListDto = new TopicListDto();

    topicListDto.setSection(forumSection.getId());
    topicListDto.setCommitMode(TopicListDao.CommitMode.POSTMODERATED_ONLY);

    topicListDto.setTag(tagId);//from  w w  w .  j a v a  2 s. c o  m

    topicListDto.setLimit(FORUM_TOPIC_COUNT);
    topicListDto.setLastmodSort(true);

    List<Topic> forumTopics = topicListService.getTopics(topicListDto);

    ImmutableListMultimap<String, Topic> sections = datePartition(forumTopics, LASTMOD_EXTRACTOR);

    ImmutableMap.Builder<String, Object> out = ImmutableMap.builder();

    if (forumTopics.size() == FORUM_TOPIC_COUNT) {
        out.put("moreForum", TagTopicListController.tagListUrl(tag, forumSection));
    }

    out.put("addForum", AddTopicController.getAddUrl(forumSection, tag));

    out.put("forum", split(Multimaps.transformValues(sections, forumPrepareFunction)));

    return out.build();
}

From source file:com.facebook.buck.features.python.CxxPythonExtensionDescription.java

private ImmutableMap<CxxPreprocessAndCompile, SourcePath> requireCxxObjects(BuildTarget target,
        ProjectFilesystem projectFilesystem, ActionGraphBuilder graphBuilder, SourcePathResolver pathResolver,
        SourcePathRuleFinder ruleFinder, CellPathResolver cellRoots, CxxPlatform cxxPlatform,
        CxxPythonExtensionDescriptionArg args, ImmutableSet<BuildRule> deps) {

    // Extract all C/C++ sources from the constructor arg.
    ImmutableMap<String, CxxSource> srcs = CxxDescriptionEnhancer.parseCxxSources(target, graphBuilder,
            ruleFinder, pathResolver, cxxPlatform, args);
    ImmutableMap<Path, SourcePath> headers = CxxDescriptionEnhancer.parseHeaders(target, graphBuilder,
            ruleFinder, pathResolver, Optional.of(cxxPlatform), args);

    // Setup the header symlink tree and combine all the preprocessor input from this rule
    // and all dependencies.
    HeaderSymlinkTree headerSymlinkTree = CxxDescriptionEnhancer.requireHeaderSymlinkTree(target,
            projectFilesystem, ruleFinder, graphBuilder, cxxPlatform, headers, HeaderVisibility.PRIVATE, true);

    ImmutableList<CxxPreprocessorInput> cxxPreprocessorInput = CxxDescriptionEnhancer
            .collectCxxPreprocessorInput(target, cxxPlatform, graphBuilder, deps,
                    ImmutableListMultimap.copyOf(Multimaps.transformValues(
                            CxxFlags.getLanguageFlagsWithMacros(args.getPreprocessorFlags(),
                                    args.getPlatformPreprocessorFlags(), args.getLangPreprocessorFlags(),
                                    args.getLangPlatformPreprocessorFlags(), cxxPlatform),
                            f -> CxxDescriptionEnhancer.toStringWithMacrosArgs(target, cellRoots, graphBuilder,
                                    cxxPlatform, f))),
                    ImmutableList.of(headerSymlinkTree), ImmutableSet.of(),
                    CxxPreprocessables.getTransitiveCxxPreprocessorInput(cxxPlatform, graphBuilder, deps),
                    args.getRawHeaders());

    // Generate rule to build the object files.
    ImmutableMultimap<CxxSource.Type, Arg> compilerFlags = ImmutableListMultimap
            .copyOf(Multimaps.transformValues(
                    CxxFlags.getLanguageFlagsWithMacros(args.getCompilerFlags(),
                            args.getPlatformCompilerFlags(), args.getLangCompilerFlags(),
                            args.getLangPlatformCompilerFlags(), cxxPlatform),
                    f -> CxxDescriptionEnhancer.toStringWithMacrosArgs(target, cellRoots, graphBuilder,
                            cxxPlatform, f)));
    CxxSourceRuleFactory factory = CxxSourceRuleFactory.of(projectFilesystem, target, graphBuilder,
            pathResolver, ruleFinder, cxxBuckConfig, cxxPlatform, cxxPreprocessorInput, compilerFlags,
            args.getPrefixHeader(), args.getPrecompiledHeader(), PicType.PIC);
    return factory.requirePreprocessAndCompileRules(srcs);
}

From source file:com.palantir.atlasdb.keyvalue.impl.ValidatingQueryRewritingKeyValueService.java

@Override
public void putWithTimestamps(String tableName, Multimap<Cell, Value> cellValues)
        throws KeyAlreadyExistsException {
    if (cellValues.isEmpty()) {
        return;//  w  w  w  .j a v a2  s  .  c  om
    }
    Validate.isTrue(!tableName.equals(TransactionConstants.TRANSACTION_TABLE), TRANSACTION_ERROR);

    long lastTimestamp = -1;
    boolean allAtSameTimestamp = true;
    for (Value value : cellValues.values()) {
        long timestamp = value.getTimestamp();
        Validate.isTrue(timestamp != Long.MAX_VALUE);
        Validate.isTrue(timestamp >= 0);
        if (lastTimestamp != -1 && timestamp != lastTimestamp) {
            allAtSameTimestamp = false;
        }
        lastTimestamp = timestamp;
    }

    if (allAtSameTimestamp) {
        Multimap<Cell, byte[]> cellValuesWithStrippedTimestamp = Multimaps.transformValues(cellValues,
                Value.GET_VALUE);

        Map<Cell, byte[]> putMap = Maps.transformValues(cellValuesWithStrippedTimestamp.asMap(),
                new Function<Collection<byte[]>, byte[]>() {

                    @Override
                    public byte[] apply(Collection<byte[]> input) {
                        try {
                            return Iterables.getOnlyElement(input);
                        } catch (IllegalArgumentException e) {
                            log.error(
                                    "Application tried to put multiple same-cell values in at same timestamp; attempting to perform last-write-wins, but ordering is not guaranteed.");
                            return Iterables.getLast(input);
                        }
                    }

                });

        put(tableName, putMap, lastTimestamp);
        return;
    }
    delegate.putWithTimestamps(tableName, cellValues);
}

From source file:eu.esdihumboldt.hale.common.align.io.impl.internal.JaxbToAlignment.java

private static UnmigratedCell createUnmigratedCell(CellType cell, LoadAlignmentContext context,
        IOReporter reporter, EntityResolver resolver, ServiceProvider serviceProvider) {
    // The sourceCell represents the cell as it was imported from the
    // XML alignment. The conversion to the resolved cell must be performed
    // later by migrating the UnmigratedCell returned from this function.
    final DefaultCell sourceCell = new DefaultCell();
    sourceCell.setTransformationIdentifier(cell.getRelation());

    final FunctionDefinition<?> cellFunction = FunctionUtil
            .getFunction(sourceCell.getTransformationIdentifier(), serviceProvider);
    final CellMigrator migrator;
    if (cellFunction != null) {
        migrator = cellFunction.getCustomMigrator().orElse(new DefaultCellMigrator());
    } else {//from   w  ww.j  a v a2s.  c  o m
        migrator = new DefaultCellMigrator();
    }

    Map<EntityDefinition, EntityDefinition> mappings = new HashMap<>();
    try {
        // The returned Entity pair consists of
        // (1st) a dummy entity representing the entity read from JAXB
        // (2nd) the resolved entity
        ListMultimap<String, Pair<Entity, Entity>> convertedSourceEntities = convertEntities(cell.getSource(),
                context.getSourceTypes(), SchemaSpaceID.SOURCE, resolver);
        if (convertedSourceEntities == null) {
            sourceCell.setSource(null);
        } else {
            sourceCell.setSource(Multimaps.transformValues(convertedSourceEntities, pair -> pair.getFirst()));
            for (Pair<Entity, Entity> pair : convertedSourceEntities.values()) {
                mappings.put(pair.getFirst().getDefinition(), pair.getSecond().getDefinition());
            }
        }

        ListMultimap<String, Pair<Entity, Entity>> convertedTargetEntities = convertEntities(cell.getTarget(),
                context.getTargetTypes(), SchemaSpaceID.TARGET, resolver);
        if (convertedTargetEntities == null) {
            sourceCell.setTarget(null);
        } else {
            sourceCell.setTarget(Multimaps.transformValues(convertedTargetEntities, pair -> pair.getFirst()));
            for (Pair<Entity, Entity> pair : convertedTargetEntities.values()) {
                mappings.put(pair.getFirst().getDefinition(), pair.getSecond().getDefinition());
            }
        }

        if (sourceCell.getTarget() == null || sourceCell.getTarget().isEmpty()) {
            // target is mandatory for cells!
            throw new IllegalStateException("Cannot create cell without target");
        }
    } catch (Exception e) {
        if (reporter != null) {
            reporter.error(new IOMessageImpl("Could not create cell", e));
        }
        return null;
    }

    if (!cell.getAbstractParameter().isEmpty()) {
        ListMultimap<String, ParameterValue> parameters = ArrayListMultimap.create();
        for (JAXBElement<? extends AbstractParameterType> param : cell.getAbstractParameter()) {
            AbstractParameterType apt = param.getValue();
            if (apt instanceof ParameterType) {
                // treat string parameters or null parameters
                ParameterType pt = (ParameterType) apt;
                ParameterValue pv = new ParameterValue(pt.getType(), Value.of(pt.getValue()));
                parameters.put(pt.getName(), pv);
            } else if (apt instanceof ComplexParameterType) {
                // complex parameters
                ComplexParameterType cpt = (ComplexParameterType) apt;
                parameters.put(cpt.getName(), new ParameterValue(new ElementValue(cpt.getAny(), context)));
            } else
                throw new IllegalStateException("Illegal parameter type");
        }
        sourceCell.setTransformationParameters(parameters);
    }

    // annotations & documentation
    for (Object element : cell.getDocumentationOrAnnotation()) {
        if (element instanceof AnnotationType) {
            // add annotation to the cell
            AnnotationType annot = (AnnotationType) element;

            // but first load it from the DOM
            AnnotationDescriptor<?> desc = AnnotationExtension.getInstance().get(annot.getType());
            if (desc != null) {
                try {
                    Object value = desc.fromDOM(annot.getAny(), null);
                    sourceCell.addAnnotation(annot.getType(), value);
                } catch (Exception e) {
                    if (reporter != null) {
                        reporter.error(new IOMessageImpl("Error loading cell annotation", e));
                    } else
                        throw new IllegalStateException("Error loading cell annotation", e);
                }
            } else
                reporter.error(new IOMessageImpl(
                        "Cell annotation of type {0} unknown, cannot load the annotation object", null, -1, -1,
                        annot.getType()));
        } else if (element instanceof DocumentationType) {
            // add documentation to the cell
            DocumentationType doc = (DocumentationType) element;
            sourceCell.getDocumentation().put(doc.getType(), doc.getValue());
        }
    }

    sourceCell.setId(cell.getId());

    // a default value is assured for priority
    String priorityStr = cell.getPriority().value();
    Priority priority = Priority.fromValue(priorityStr);
    if (priority != null) {
        sourceCell.setPriority(priority);
    } else {
        // TODO check if it makes sense to do something. Default value is
        // used.
        throw new IllegalArgumentException();
    }

    return new UnmigratedCell(sourceCell, migrator, mappings);
}

From source file:com.facebook.buck.cxx.CxxLibraryFactory.java

private static ImmutableMap<CxxPreprocessAndCompile, SourcePath> requireCxxObjects(BuildTarget buildTarget,
        ProjectFilesystem projectFilesystem, ActionGraphBuilder graphBuilder,
        SourcePathResolver sourcePathResolver, SourcePathRuleFinder ruleFinder, CellPathResolver cellRoots,
        CxxBuckConfig cxxBuckConfig, CxxPlatform cxxPlatform, PicType pic, CxxLibraryDescriptionArg args,
        ImmutableSet<BuildRule> deps,
        CxxLibraryDescription.TransitiveCxxPreprocessorInputFunction transitivePreprocessorInputs,
        Optional<CxxLibraryDescriptionDelegate> delegate) {

    boolean shouldCreatePrivateHeadersSymlinks = args.getXcodePrivateHeadersSymlinks()
            .orElse(cxxPlatform.getPrivateHeadersSymlinksEnabled());

    HeaderSymlinkTree headerSymlinkTree = CxxDescriptionEnhancer.requireHeaderSymlinkTree(buildTarget,
            projectFilesystem, ruleFinder, graphBuilder, cxxPlatform,
            CxxDescriptionEnhancer.parseHeaders(buildTarget, graphBuilder, ruleFinder, sourcePathResolver,
                    Optional.of(cxxPlatform), args),
            HeaderVisibility.PRIVATE, shouldCreatePrivateHeadersSymlinks);

    ImmutableList.Builder<HeaderSymlinkTree> privateHeaderSymlinkTrees = ImmutableList.builder();
    privateHeaderSymlinkTrees.add(headerSymlinkTree);
    delegate.ifPresent(d -> d.getPrivateHeaderSymlinkTree(buildTarget, graphBuilder, cxxPlatform)
            .ifPresent(h -> privateHeaderSymlinkTrees.add(h)));

    // Create rule to build the object files.
    ImmutableMultimap<CxxSource.Type, Arg> compilerFlags = ImmutableListMultimap
            .copyOf(Multimaps.transformValues(
                    CxxFlags.getLanguageFlagsWithMacros(args.getCompilerFlags(),
                            args.getPlatformCompilerFlags(), args.getLangCompilerFlags(),
                            args.getLangPlatformCompilerFlags(), cxxPlatform),
                    f -> CxxDescriptionEnhancer.toStringWithMacrosArgs(buildTarget, cellRoots, graphBuilder,
                            cxxPlatform, f)));
    return CxxSourceRuleFactory
            .of(projectFilesystem, buildTarget, graphBuilder, sourcePathResolver, ruleFinder, cxxBuckConfig,
                    cxxPlatform,//from w  w w .j ava 2  s .co m
                    CxxLibraryDescription.getPreprocessorInputsForBuildingLibrarySources(cxxBuckConfig,
                            graphBuilder, cellRoots, buildTarget, args, cxxPlatform, deps,
                            transitivePreprocessorInputs, privateHeaderSymlinkTrees.build()),
                    compilerFlags, args.getPrefixHeader(), args.getPrecompiledHeader(), pic)
            .requirePreprocessAndCompileRules(CxxDescriptionEnhancer.parseCxxSources(buildTarget, graphBuilder,
                    ruleFinder, sourcePathResolver, cxxPlatform, args));
}