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.basepom.mojo.duplicatefinder.ResultCollector.java

public Map<String, Collection<ConflictResult>> getResults(final ConflictType type, final ConflictState state) {
    Multimap<String, ConflictResult> result = Multimaps.filterValues(results, new Predicate<ConflictResult>() {

        @Override/*from   ww  w .j a  v  a  2  s  .  c  om*/
        public boolean apply(@Nonnull ConflictResult conflictResult) {
            checkNotNull(conflictResult, "conflictResult is null");
            return conflictResult.getConflictState() == state && conflictResult.getType() == type
                    && !conflictResult.isExcepted();
        }
    });

    return ImmutableMap.copyOf(result.asMap());
}

From source file:com.hortonworks.streamline.streams.common.event.correlation.CorrelatedEventsGrouper.java

/**
 * Returns the group of correlated events per source where the group of related source events
 * produces the same downstream events/* w w  w  .j  a v a  2  s.c o  m*/
 *
 * @param sources the set of source component names
 * @return the group of correlated events per source
 */
public List<Set<String>> groupByRelatedSourceEvents(Set<String> sources) {
    Multimap<Set<String>, String> allEventsToSourceEvents = LinkedHashMultimap.create();
    Stream<String> rootEventIds = events.stream().filter(e -> e != null && e.getRootIds().isEmpty())
            .map(EventInformation::getEventId);
    rootEventIds.forEach(rootEventId -> {
        Map<String, EventInformation> allRelatedEvents = buildRelatedEventsMap(rootEventId);
        allEventsToSourceEvents.put(allRelatedEvents.keySet(), rootEventId);
    });

    List<Set<String>> result = new ArrayList<>();
    allEventsToSourceEvents.asMap().values().forEach(v -> result.add(new HashSet<>(v)));

    return result;
}

From source file:com.mogujie.instantrun.IntSwitch.java

private void visitClassifier(GeneratorAdapter mv, Set<String> strings) {
    visitInt();//from   w  w w .j ava  2 s . com

    Multimap<Integer, String> buckets = Multimaps.index(strings, HASH_METHOD);
    List<Map.Entry<Integer, Collection<String>>> sorted = Ordering.natural()
            .onResultOf(new Function<Map.Entry<Integer, Collection<String>>, Integer>() {
                @Override
                public Integer apply(Map.Entry<Integer, Collection<String>> entry) {
                    return entry.getKey();
                }
            }).immutableSortedCopy(buckets.asMap().entrySet());

    int sortedHashes[] = new int[sorted.size()];
    List<String> sortedCases[] = new List[sorted.size()];
    int index = 0;
    for (Map.Entry<Integer, Collection<String>> entry : sorted) {
        sortedHashes[index] = entry.getKey();
        sortedCases[index] = Lists.newCopyOnWriteArrayList(entry.getValue());
        index++;
    }

    // Label for each hash and for default.
    Label labels[] = new Label[sorted.size()];
    Label defaultLabel = new Label();
    for (int i = 0; i < sorted.size(); ++i) {
        labels[i] = new Label();
    }

    // Create a switch that dispatches to each label from the hash code of
    mv.visitLookupSwitchInsn(defaultLabel, sortedHashes, labels);

    // Create the cases.
    for (int i = 0; i < sorted.size(); ++i) {
        mv.visitLabel(labels[i]);
        visitx(mv, sortedCases[i]);
    }
    mv.visitLabel(defaultLabel);
    visitDefault();
}

From source file:com.cloudera.flume.master.TranslatingConfigurationManager.java

/**
 * Builds a two html tables that display parent/self configs and logical node
 * mapping.//from   w ww. j a  v a  2  s  .c  om
 * 
 * TODO convert to a report, do not depend on this output.
 */
@Override
synchronized public ReportEvent getMetrics() {
    StringBuilder html = new StringBuilder();
    html.append("<h2>Node configuration</h2>\n<table border=\"1\"><tr>"
            + "<th>Node</th><th>Version</th><th>Flow ID</th><th>Source</th><th>Sink</th>"
            + "<th>Translated Version</th><th>Translated Source</th><th>Translated Sink</th>" + "</tr>");

    Map<String, FlumeConfigData> cfgs = new TreeMap<String, FlumeConfigData>(parentMan.getAllConfigs());
    Map<String, FlumeConfigData> xcfgs = new TreeMap<String, FlumeConfigData>(selfMan.getTranslatedConfigs());

    for (Entry<String, FlumeConfigData> e : cfgs.entrySet()) {
        String ln = e.getKey();
        appendHtmlTranslatedFlumeConfigData(html, e.getKey(), e.getValue(), xcfgs.get(ln));
    }
    html.append("</table>\n\n");

    // a table that has a mapping from physical nodes to logical nodes.
    html.append("<h2>Physical/Logical Node mapping</h2>\n<table border=\"1\">"
            + "<tr><th>physical node</th><th>logical node</th></tr>");
    Multimap<String, String> nodes = parentMan.getLogicalNodeMap();
    synchronized (nodes) {
        for (Entry<String, Collection<String>> e : nodes.asMap().entrySet()) {
            ConfigManager.appendHtmlPhysicalLogicalMapping(html, e.getKey(), e.getValue());
        }
    }
    html.append("</table>\n\n");

    return ReportEvent.createLegacyHtmlReport("configs", html.toString());
}

From source file:org.apache.druid.indexing.common.TaskToolbox.java

public void publishSegments(Iterable<DataSegment> segments) throws IOException {
    // Request segment pushes for each set
    final Multimap<Interval, DataSegment> segmentMultimap = Multimaps.index(segments,
            new Function<DataSegment, Interval>() {
                @Override/*  w w w  . ja  v  a 2  s  .c o  m*/
                public Interval apply(DataSegment segment) {
                    return segment.getInterval();
                }
            });
    for (final Collection<DataSegment> segmentCollection : segmentMultimap.asMap().values()) {
        getTaskActionClient().submit(new SegmentInsertAction(ImmutableSet.copyOf(segmentCollection)));
    }
}

From source file:org.hupo.psi.calimocho.xgmml.GraphBuilder.java

private void addAttsFromMap(Multimap<String, Att> attMultimap, List<Att> atts) {
    for (Map.Entry<String, Collection<Att>> entry : attMultimap.asMap().entrySet()) {
        if (entry.getValue().size() > 1) {
            TreeSet<String> values = new TreeSet<String>();
            for (calimocho.internal.xgmml.Att att : entry.getValue()) {
                if (att.getValue() != null) {
                    values.add(att.getValue());
                }/*from  ww  w  .j ava  2  s  . c  o  m*/
            }

            calimocho.internal.xgmml.Att list = createAtt(entry.getKey(), StringUtils.join(values, ","));
            atts.add(list);
        } else {
            atts.add(entry.getValue().iterator().next());
        }
    }
}

From source file:com.eucalyptus.cloudwatch.common.internal.domain.alarms.AlarmManager.java

private static Map<String, Collection<String>> buildAccountIdToAlarmNamesMap(@Nullable final String accountId,
        @Nullable final Collection<String> alarmNames) {
    final Multimap<String, String> alarmNamesMultimap = HashMultimap.create();
    if (alarmNames != null) {
        if (accountId != null) {
            alarmNamesMultimap.putAll(accountId, alarmNames); // An ARN is also a valid name
        }/* w w  w .j  ava 2 s .com*/
        CollectionUtils.putAll(
                Optional.presentInstances(Iterables.transform(alarmNames,
                        CloudWatchResourceName.asArnOfType(CloudWatchResourceName.Type.alarm))),
                alarmNamesMultimap, CloudWatchResourceName.toNamespace(), CloudWatchResourceName.toName());
    }
    return alarmNamesMultimap.asMap();
}

From source file:co.cask.cdap.internal.app.runtime.flow.FlowUtils.java

/**
 * Configures all queues being used in a flow.
 *
 * @return A Multimap from flowletId to QueueName where the flowlet is a consumer of.
 *//*  ww  w . jav  a2 s. com*/
public static Multimap<String, QueueName> configureQueue(Program program, FlowSpecification flowSpec,
        StreamAdmin streamAdmin, QueueAdmin queueAdmin, TransactionExecutorFactory txExecutorFactory) {
    // Generate all queues specifications
    Id.Application appId = Id.Application.from(program.getNamespaceId(), program.getApplicationId());
    Table<QueueSpecificationGenerator.Node, String, Set<QueueSpecification>> queueSpecs = new SimpleQueueSpecificationGenerator(
            appId).create(flowSpec);

    // For each queue in the flow, gather all consumer groups information
    Multimap<QueueName, ConsumerGroupConfig> queueConfigs = HashMultimap.create();

    // Loop through each flowlet and generate the map from consumer flowlet id to queue
    ImmutableSetMultimap.Builder<String, QueueName> resultBuilder = ImmutableSetMultimap.builder();
    for (Map.Entry<String, FlowletDefinition> entry : flowSpec.getFlowlets().entrySet()) {
        String flowletId = entry.getKey();

        for (QueueSpecification queueSpec : Iterables.concat(queueSpecs.column(flowletId).values())) {
            resultBuilder.put(flowletId, queueSpec.getQueueName());
        }
    }

    // For each queue, gather all consumer groups.
    for (QueueSpecification queueSpec : Iterables.concat(queueSpecs.values())) {
        QueueName queueName = queueSpec.getQueueName();
        queueConfigs.putAll(queueName, getAllConsumerGroups(program, flowSpec, queueName, queueSpecs));
    }

    try {
        // Configure each stream consumer in the Flow. Also collects all queue configurers.
        final List<ConsumerGroupConfigurer> groupConfigurers = Lists.newArrayList();

        for (Map.Entry<QueueName, Collection<ConsumerGroupConfig>> entry : queueConfigs.asMap().entrySet()) {
            LOG.info("Queue config for {} : {}", entry.getKey(), entry.getValue());
            if (entry.getKey().isStream()) {
                Map<Long, Integer> configs = Maps.newHashMap();
                for (ConsumerGroupConfig config : entry.getValue()) {
                    configs.put(config.getGroupId(), config.getGroupSize());
                }
                streamAdmin.configureGroups(entry.getKey().toStreamId(), configs);
            } else {
                groupConfigurers.add(new ConsumerGroupConfigurer(queueAdmin.getQueueConfigurer(entry.getKey()),
                        entry.getValue()));
            }
        }

        // Configure queue transactionally
        try {
            Transactions.createTransactionExecutor(txExecutorFactory, groupConfigurers)
                    .execute(new TransactionExecutor.Subroutine() {
                        @Override
                        public void apply() throws Exception {
                            for (ConsumerGroupConfigurer configurer : groupConfigurers) {
                                configurer.configure();
                            }
                        }
                    });
        } finally {
            for (ConsumerGroupConfigurer configurer : groupConfigurers) {
                Closeables.closeQuietly(configurer);
            }
        }

        return resultBuilder.build();
    } catch (Exception e) {
        LOG.error("Failed to configure queues", e);
        throw Throwables.propagate(e);
    }
}

From source file:org.springframework.ide.eclipse.boot.dash.views.DeleteApplicationsAction.java

@Override
public void run() {
    //Deletes are implemented per BootDashModel. So sort selection into bins per model.
    Multimap<BootDashModel, BootDashElement> sortingBins = HashMultimap.create();
    for (BootDashElement e : getSelectedElements()) {
        BootDashModel model = e.getParent();
        //We are only capable of removing elements from a ModifiableModel (the 'local' model is read-only).
        if (model instanceof ModifiableModel) {
            sortingBins.put(model, e);/*  www.  j  a  v a2  s. c om*/
        }
    }
    //Now delete elements from corresponding models.
    for (final Entry<BootDashModel, Collection<BootDashElement>> workitem : sortingBins.asMap().entrySet()) {
        BootDashModel model = workitem.getKey();
        final ModifiableModel modifiable = (ModifiableModel) model; //cast is safe. Only ModifiableModel are added to sortingBins
        if (ui.confirmOperation("Deleting Applications",
                "Are you sure that you want to delete the selected applications from: "
                        + model.getRunTarget().getName() + "? The applications will be permanently removed.")) {
            Job job = new Job("Deleting apps from " + model.getRunTarget().getName()) {
                @Override
                protected IStatus run(IProgressMonitor monitor) {
                    modifiable.delete(workitem.getValue(), ui);
                    return Status.OK_STATUS;
                }

            };
            job.schedule();
        }
    }
}

From source file:org.eclipse.sirius.ui.business.api.viewpoint.ViewpointSelection.java

/**
 * Compute the missing viewpoint dependencies (if any) for all the
 * viewpoints enabled by the user.// ww  w  .  j ava  2 s.c om
 *
 * @param selected
 *            the viewpoints selection request by the user.
 * @return for each selected viewpoint which has missing dependencies, an
 *         entry with the selected viewpoint's name as key and the list of
 *         the missing viewpoints' names as value.
 */
public static Map<String, Collection<String>> getMissingDependencies(Set<Viewpoint> selected) {
    Set<String> selectedURIs = Sets
            .newHashSet(Iterables.filter(Iterables.transform(selected, new Function<Viewpoint, String>() {
                @Override
                public String apply(Viewpoint from) {
                    Option<URI> uri = new ViewpointQuery(from).getViewpointURI();
                    if (uri.some()) {
                        return uri.get().toString();
                    } else {
                        return null;
                    }
                }
            }), Predicates.notNull()));

    Multimap<String, String> result = HashMultimap.create();
    for (Viewpoint viewpoint : selected) {
        for (RepresentationExtensionDescription extension : new ViewpointQuery(viewpoint)
                .getAllRepresentationExtensionDescriptions()) {
            String extended = extension.getViewpointURI();
            Pattern pattern = Pattern.compile(extended);
            if (!ViewpointSelection.atLeastOneUriMatchesPattern(selectedURIs, pattern)) {
                result.put(viewpoint.getName(), extended.trim().replaceFirst("^viewpoint:/[^/]+/", "")); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
    }
    return result.asMap();
}