Example usage for com.google.common.collect Multimap asMap

List of usage examples for com.google.common.collect Multimap asMap

Introduction

In this page you can find the example usage for com.google.common.collect Multimap asMap.

Prototype

Map<K, Collection<V>> asMap();

Source Link

Document

Returns a view of this multimap as a Map from each distinct key to the nonempty collection of that key's associated values.

Usage

From source file:org.eclipse.xtext.serializer.sequencer.ContextFinder.java

protected Multimap<AbstractElement, ISerializationContext> collectAssignments(
        Multimap<IConstraint, ISerializationContext> constraints, EStructuralFeature feature) {
    Multimap<AbstractElement, ISerializationContext> result = ArrayListMultimap.create();
    for (Entry<IConstraint, Collection<ISerializationContext>> e : constraints.asMap().entrySet()) {
        IConstraint constraint = e.getKey();
        Collection<ISerializationContext> contexts = e.getValue();
        IFeatureInfo featureInfo = constraint.getFeatures()[constraint.getType().getFeatureID(feature)];
        List<IConstraintElement> assignments = featureInfo.getAssignments();
        for (IConstraintElement assignment : assignments) {
            result.putAll(assignment.getGrammarElement(), contexts);
        }//from   ww  w. java  2 s.c  om
    }
    return result;
}

From source file:sf.net.experimaestro.manager.plans.Plan.java

@Override
public Plan doCopy(boolean deep, Map<Object, Object> map) {
    Plan copy = new Plan(factory);
    for (Multimap<DotName, Operator> multimap : inputsList) {
        HashMultimap<DotName, Operator> mapCopy = HashMultimap.create();
        copy.inputsList.add(mapCopy);//from   ww  w  .ja  v a  2  s . c  o  m
        for (Map.Entry<DotName, Collection<Operator>> entry : multimap.asMap().entrySet()) {
            mapCopy.putAll(entry.getKey(),
                    deep ? Operator.copy(entry.getValue(), deep, map) : entry.getValue());
        }
    }

    return copy;
}

From source file:com.vecna.maven.jshint.report.JsHintCheckstyleReporter.java

/**
 * {@inheritDoc}//from   w  w w  . ja  v a2 s  .  c o m
 */
@Override
public void report(Multimap<String, JsHintError> errors, OutputStream output) throws MojoExecutionException {
    XMLOutputFactory outFactory = XMLOutputFactory.newInstance();

    try {
        XMLStreamWriter w = new IndentingXMLStreamWriter(outFactory.createXMLStreamWriter(output));

        w.writeStartDocument();
        w.writeStartElement("checkstyle");
        w.writeAttribute("version", "4.3");

        for (Entry<String, Collection<JsHintError>> entry : errors.asMap().entrySet()) {
            w.writeStartElement("file");
            w.writeAttribute("name", entry.getKey());

            for (JsHintError error : entry.getValue()) {
                w.writeStartElement("error");

                w.writeAttribute("line", String.valueOf(error.getLine()));
                w.writeAttribute("column", String.valueOf(error.getCharacter()));
                w.writeAttribute("severity", "error");
                w.writeAttribute("message", error.getReason());

                w.writeEndElement();
            }

            w.writeEndElement();
        }
        w.writeEndElement();
        w.writeEndDocument();
        w.close();
    } catch (XMLStreamException e) {
        throw new MojoExecutionException("failed to write the violation report", e);
    }
}

From source file:org.summer.dsl.model.types.util.FeatureOverridesService.java

protected Iterable<JvmFeature> removeOverridden(
        Multimap<Triple<EClass, String, Integer>, JvmFeature> featureIndex, ITypeArgumentContext ctx) {
    Set<JvmFeature> result = Sets.newLinkedHashSet(featureIndex.values());
    for (Collection<JvmFeature> featuresWithSameName : featureIndex.asMap().values()) {
        if (featuresWithSameName.size() > 1) {
            for (JvmFeature op1 : featuresWithSameName) {
                for (JvmFeature op2 : featuresWithSameName) {
                    if (result.contains(op1) && op1.getDeclaringType() != op2.getDeclaringType()
                            && internalIsOverridden(op1, op2, ctx, true))
                        result.remove(op2);
                }//from  ww w .  j  av a 2  s .  c o m
            }
        }
    }
    return result;
}

From source file:com.google.cloud.dataflow.sdk.transforms.CombineFns.java

/**
 * Populate display data for the {@code combineFns} that make up a composed combine transform.
 *
 * <p>The same combineFn class may be used multiple times, in which case we must take special care
 * to register display data with unique namespaces.
 *///w  w w .  j a va  2  s . c o  m
private static void populateDisplayData(DisplayData.Builder builder,
        List<? extends HasDisplayData> combineFns) {

    // NB: ArrayListMultimap necessary to maintain ordering of combineFns of the same type.
    Multimap<Class<?>, HasDisplayData> combineFnMap = ArrayListMultimap.create();

    for (int i = 0; i < combineFns.size(); i++) {
        HasDisplayData combineFn = combineFns.get(i);
        builder.add(
                DisplayData.item("combineFn" + (i + 1), combineFn.getClass()).withLabel("Combine Function"));
        combineFnMap.put(combineFn.getClass(), combineFn);
    }

    for (Map.Entry<Class<?>, Collection<HasDisplayData>> combineFnEntries : combineFnMap.asMap().entrySet()) {

        Collection<HasDisplayData> classCombineFns = combineFnEntries.getValue();
        if (classCombineFns.size() == 1) {
            // Only one combineFn of this type, include it directly.
            builder.include(Iterables.getOnlyElement(classCombineFns));

        } else {
            // Multiple combineFns of same type, add a namespace suffix so display data is
            // unique and ordered.
            String baseNamespace = combineFnEntries.getKey().getName();
            for (int i = 0; i < combineFns.size(); i++) {
                HasDisplayData combineFn = combineFns.get(i);
                String namespace = String.format("%s#%d", baseNamespace, i + 1);
                builder.include(combineFn, namespace);
            }
        }
    }
}

From source file:io.prestosql.sql.parser.ErrorHandler.java

@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
        String message, RecognitionException e) {
    try {//from   w  w  w  .  j  a  v a2  s.co  m
        Parser parser = (Parser) recognizer;

        ATN atn = parser.getATN();

        ATNState currentState;
        Token currentToken;
        RuleContext context;

        if (e != null) {
            currentState = atn.states.get(e.getOffendingState());
            currentToken = e.getOffendingToken();
            context = e.getCtx();

            if (e instanceof NoViableAltException) {
                currentToken = ((NoViableAltException) e).getStartToken();
            }
        } else {
            currentState = atn.states.get(parser.getState());
            currentToken = parser.getCurrentToken();
            context = parser.getContext();
        }

        Analyzer analyzer = new Analyzer(atn, parser.getVocabulary(), specialRules, specialTokens, ignoredRules,
                parser.getTokenStream());
        Multimap<Integer, String> candidates = analyzer.process(currentState, currentToken.getTokenIndex(),
                context);

        // pick the candidate tokens associated largest token index processed (i.e., the path that consumed the most input)
        String expected = candidates.asMap().entrySet().stream().max(Comparator.comparing(Map.Entry::getKey))
                .get().getValue().stream().sorted().collect(Collectors.joining(", "));

        message = String.format("mismatched input '%s'. Expecting: %s", ((Token) offendingSymbol).getText(),
                expected);
    } catch (Exception exception) {
        LOG.error(exception,
                "Unexpected failure when handling parsing error. This is likely a bug in the implementation");
    }

    throw new ParsingException(message, e, line, charPositionInLine);
}

From source file:org.onosproject.incubator.store.resource.impl.DistributedLabelResourceStore.java

@Override
public boolean releaseToDevicePool(Multimap<DeviceId, LabelResource> release) {
    Map<DeviceId, Collection<LabelResource>> maps = release.asMap();
    Set<DeviceId> deviceIdSet = maps.keySet();
    LabelResourceRequest request = null;
    for (Iterator<DeviceId> it = deviceIdSet.iterator(); it.hasNext();) {
        DeviceId deviceId = (DeviceId) it.next();
        Device device = (Device) deviceService.getDevice(deviceId);
        if (device == null) {
            continue;
        }/*from   ww  w . j  av a 2 s .  co  m*/
        ImmutableSet<LabelResource> collection = ImmutableSet.copyOf(maps.get(deviceId));
        request = new LabelResourceRequest(deviceId, LabelResourceRequest.Type.RELEASE, 0, collection);
        NodeId master = mastershipService.getMasterFor(deviceId);

        if (master == null) {
            log.warn("Failed to releaseToDevicePool: No master for {}", deviceId);
            return false;
        }

        if (master.equals(clusterService.getLocalNode().id())) {
            return internalRelease(request);
        }

        log.trace("Forwarding request to {}, which is the primary (master) for device {}", master, deviceId);

        return complete(
                clusterCommunicator.sendAndReceive(request, LabelResourceMessageSubjects.LABEL_POOL_RELEASE,
                        SERIALIZER::encode, SERIALIZER::decode, master));
    }
    return false;
}

From source file:jbyoshi.gitupdate.processor.Push.java

@Override
public void registerTasks(Repository repo, Git git, Task root) throws Exception {
    Task me = root.newChild(getClass().getSimpleName());
    // Group the branches by their remotes.
    Multimap<String, String> branchList = HashMultimap.create();
    for (String branch : Utils.getLocalBranches(repo).keySet()) {
        String remote = Utils.getPushRemote(repo, branch);
        if (remote == null) {
            remote = new BranchConfig(repo.getConfig(), branch).getRemote();
        }//from   w ww .j  a v a 2 s .  co  m
        if (remote != null) {
            branchList.put(remote, branch);
        }
    }
    for (Map.Entry<String, Collection<String>> remote : branchList.asMap().entrySet()) {
        me.newChild(remote.getKey(), report -> {
            try {
                process(repo, git, remote.getKey(), remote.getValue(), report);
            } catch (Exception e) {
                report.newErrorChild(e);
            }
        });
    }
}

From source file:com.manydesigns.portofino.pageactions.crud.ModelSelectionProviderSupport.java

public Map<List<String>, Collection<String>> getAvailableSelectionProviderNames() {
    Multimap<List<String>, String> namesMap = HashMultimap.create();
    for (Map.Entry<List<String>, ModelSelectionProvider> e : availableSelectionProviders.entries()) {
        namesMap.put(e.getKey(), e.getValue().getName());
    }//from   ww w . j  a v  a2 s . c  om
    return namesMap.asMap();
}

From source file:com.haulmont.timesheets.global.WeeklyReportConverter.java

public List<WeeklyReportEntry> convertFromTimeEntries(List<TimeEntry> timeEntries) {

    if (timeEntries.isEmpty()) {
        return Collections.emptyList();
    }/*from  w  ww . j av  a2  s  .com*/

    final Multimap<TimeEntryGroupKey, TimeEntry> groupedTimeEntries = ArrayListMultimap.create();

    for (TimeEntry timeEntry : timeEntries) {
        groupedTimeEntries.put(new TimeEntryGroupKey(timeEntry), timeEntry);
    }

    if (groupedTimeEntries.isEmpty()) {
        return Collections.emptyList();
    }

    List<WeeklyReportEntry> reportEntries = new ArrayList<>();
    for (Map.Entry<TimeEntryGroupKey, Collection<TimeEntry>> entry : groupedTimeEntries.asMap().entrySet()) {
        WeeklyReportEntry reportEntry = new WeeklyReportEntry();
        TimeEntryGroupKey entryKey = entry.getKey();
        reportEntry.setProject(entryKey.project);
        reportEntry.setTask(entryKey.task);
        reportEntry.setActivityType(entryKey.activityType);
        for (TimeEntry timeEntry : entry.getValue()) {
            reportEntry.addTimeEntry(timeEntry);
        }
        reportEntries.add(reportEntry);
    }

    return reportEntries;
}