Example usage for com.google.common.collect LinkedListMultimap create

List of usage examples for com.google.common.collect LinkedListMultimap create

Introduction

In this page you can find the example usage for com.google.common.collect LinkedListMultimap create.

Prototype

public static <K, V> LinkedListMultimap<K, V> create() 

Source Link

Document

Creates a new, empty LinkedListMultimap with the default initial capacity.

Usage

From source file:org.eclipse.sirius.common.ui.tools.api.navigator.GroupingContentProvider.java

private LinkedListMultimap<Object, Object> buildChildrenContainerMapping(Object[] children) {
    LinkedListMultimap<Object, Object> childrenContainingMapping = LinkedListMultimap.create();
    Object noContainingFeature = new Object();
    for (Object child : children) {
        Object containingFeature;
        if (child instanceof EObject) {
            containingFeature = ((EObject) child).eContainingFeature();
        } else if (child instanceof TreeItemWrapper) {
            Object wrappedObject = ((TreeItemWrapper) child).getWrappedObject();
            if (wrappedObject instanceof EObject) {
                containingFeature = ((EObject) wrappedObject).eContainingFeature();
            } else {
                containingFeature = noContainingFeature;
            }/*from  w  w w  .jav a2  s. c o  m*/
        } else {
            containingFeature = noContainingFeature;
        }
        childrenContainingMapping.put(containingFeature, child);
    }
    return childrenContainingMapping;
}

From source file:org.apache.s4.edsl.AppBuilder.java

private void setStreamField(ProcessingElement pe, Collection<StreamBuilder<? extends Event>> streams)
        throws Exception {

    /*// w  w w  .  jav a 2s  .  c  om
     * Create a map of the stream fields to the corresponding generic type. We will use this info to assign the
     * streams. If the field type matches the stream type and there is no ambiguity, then the assignment is easy. If
     * more than one field has the same type, then then we need to do more work.
     */
    Field[] fields = pe.getClass().getDeclaredFields();
    Multimap<String, Field> typeMap = LinkedListMultimap.create();
    logger.debug("Analyzing PE [{}].", pe.getClass().getName());
    for (Field field : fields) {
        logger.trace("Field [{}] is of generic type [{}].", field.getName(), field.getGenericType());

        if (field.getType() == Stream[].class) {
            logger.debug("Found stream field: {}", field.getGenericType());

            /* Track what fields have streams with the same event type. */
            String key = field.getGenericType().toString();
            typeMap.put(key, field);
        }
    }

    /* Assign streams to stream fields. */
    Multimap<Field, Stream<? extends Event>> assignment = LinkedListMultimap.create();
    for (StreamBuilder<? extends Event> sm : streams) {

        Stream<? extends Event> stream = sm.stream;
        Class<? extends Event> eventType = sm.type;
        String key = Stream.class.getCanonicalName() + "<" + eventType.getCanonicalName() + ">[]";
        if (typeMap.containsKey(key)) {
            String fieldName;
            Field field;
            Collection<Field> streamFields = typeMap.get(key);
            int numStreamFields = streamFields.size();
            logger.debug("Found [{}] stream fields for type [{}].", numStreamFields, key);

            if (numStreamFields > 1) {

                /*
                 * There is more than one field that can be used for this stream type. To resolve the ambiguity we
                 * need additional information. The app graph should include the name of the field that should be
                 * used to assign this stream. If the name is missing we bail out.
                 */
                fieldName = sm.fieldName;

                /* Bail out. */
                if (fieldName == null) {
                    String msg = String.format(
                            "There are [%d] stream fields in PE [%s]. To assign stream [%s] you need to provide the field name in the application graph using the method withFiled(). See Javadocs for an example.",
                            numStreamFields, pe.getClass().getName(), stream.getName());
                    logger.error(msg);
                    throw new Exception(msg);
                }

                /* Use the provided field name to choose the PE field. */
                field = pe.getClass().getDeclaredField(fieldName);

            } else {

                /*
                 * The easy case, no ambiguity, we don't need an explicit field name to be provided. We have the
                 * field that matches the stream type.
                 */
                Iterator<Field> iter = streamFields.iterator();
                field = iter.next(); // Note that numStreamFields == 1, the size of this collection is 1.
                logger.debug("Using field [{}].", field.getName());
            }

            /*
             * By now, we found the field to use for this stream or we bailed out. We are not ready to finish yet.
             * There may be more than one stream that needs to be assigned to this field. The stream fields must be
             * arrays by convention and there may be more than one stream assigned to this fields. For now we create
             * a multimap from field to streams so we can construct the array in the next step.
             */
            assignment.put(field, stream);

        } else {

            /* We couldn't find a match. Tell user to fix the EDSL code. */
            String msg = String.format(
                    "There is no stream of type [%s] in PE [%s]. I was unable to assign stream [%s].", key,
                    pe.getClass().getName(), stream.getName());
            logger.error(msg);
            throw new Exception(msg);

        }
    }
    /* Now we construct the array and do the final assignment. */

    Map<Field, Collection<Stream<? extends Event>>> assignmentMap = assignment.asMap();
    for (Map.Entry<Field, Collection<Stream<? extends Event>>> entry : assignmentMap.entrySet()) {
        Field f = entry.getKey();

        int arraySize = entry.getValue().size();
        @SuppressWarnings("unchecked")
        Stream<? extends Event> streamArray[] = (Stream<? extends Event>[]) Array.newInstance(Stream.class,
                arraySize);
        int i = 0;
        for (Stream<? extends Event> s : entry.getValue()) {
            streamArray[i++] = s;

            f.setAccessible(true);
            f.set(pe, streamArray);
            logger.debug("Assigned [{}] streams to field [{}].", streamArray.length, f.getName());
        }
    }
}

From source file:com.google.gerrit.server.plugins.PluginGuiceEnvironment.java

void onReloadPlugin(Plugin oldPlugin, Plugin newPlugin) {
    for (ReloadPluginListener l : onReload) {
        l.onReloadPlugin(oldPlugin, newPlugin);
    }//  w ww.  jav a2s .  c  o m

    // Index all old registrations by the raw type. These may be replaced
    // during the reattach calls below. Any that are not replaced will be
    // removed when the old plugin does its stop routine.
    ListMultimap<TypeLiteral<?>, ReloadableRegistrationHandle<?>> old = LinkedListMultimap.create();
    for (ReloadableRegistrationHandle<?> h : oldPlugin.getReloadableHandles()) {
        old.put(h.getKey().getTypeLiteral(), h);
    }

    RequestContext oldContext = enter(newPlugin);
    try {
        reattachMap(old, sysMaps, newPlugin.getSysInjector(), newPlugin);
        reattachMap(old, sshMaps, newPlugin.getSshInjector(), newPlugin);
        reattachMap(old, httpMaps, newPlugin.getHttpInjector(), newPlugin);

        reattachSet(old, sysSets, newPlugin.getSysInjector(), newPlugin);
        reattachSet(old, sshSets, newPlugin.getSshInjector(), newPlugin);
        reattachSet(old, httpSets, newPlugin.getHttpInjector(), newPlugin);

        reattachItem(old, sysItems, newPlugin.getSysInjector(), newPlugin);
    } finally {
        exit(oldContext);
    }
}

From source file:com.ning.http.client.RequestBuilderBase.java

public T addParameter(String key, String value) throws IllegalArgumentException {
    if ((request.type != RequestType.POST) && (request.type != RequestType.PUT)) {
        throw new IllegalArgumentException("Request type has to POST or PUT for form parameters");
    }/*w w w  .  j av  a2 s  .  c o  m*/
    resetNonMultipartData();
    resetMultipartData();
    if (request.params == null) {
        request.params = LinkedListMultimap.create();
    }
    request.params.put(key, value);
    return derived.cast(this);
}

From source file:mods.railcraft.common.util.misc.ChunkManager.java

@Override
public ListMultimap<String, Ticket> playerTicketsLoaded(ListMultimap<String, Ticket> tickets, World world) {
    if (RailcraftConfig.printAnchorLocations())
        for (Ticket ticket : tickets.values()) {
            Entity entity = ticket.getEntity();
            if (entity == null) {
                int x = ticket.getModData().getInteger("xCoord");
                int y = ticket.getModData().getInteger("yCoord");
                int z = ticket.getModData().getInteger("zCoord");
                String type = ticket.getModData().getString("type");

                if (y >= 0) {
                    printAnchor(LocalizationPlugin.translate(type + ".name"), x, y, z);
                }//from   ww w  .j av a 2 s.  co m
            }
        }
    return LinkedListMultimap.create();
}

From source file:org.glowroot.ui.JvmJsonService.java

@GET(path = "/backend/jvm/thread-dump", permission = "agent:jvm:threadDump")
String getThreadDump(@BindAgentId String agentId) throws Exception {
    checkNotNull(liveJvmService);//ww  w.  j  a  va  2s.  c  o m
    ThreadDump threadDump;
    try {
        threadDump = liveJvmService.getThreadDump(agentId);
    } catch (AgentNotConnectedException e) {
        logger.debug(e.getMessage(), e);
        return "{\"agentNotConnected\":true}";
    }
    List<ThreadDump.Thread> allThreads = Lists.newArrayList();
    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    try {
        jg.writeStartObject();
        jg.writeArrayFieldStart("transactions");
        List<Transaction> transactions = new TransactionOrderingByTotalTimeDesc()
                .sortedCopy(threadDump.getTransactionList());
        for (ThreadDump.Transaction transaction : transactions) {
            writeTransactionThread(transaction, jg);
            allThreads.addAll(transaction.getThreadList());
        }
        jg.writeEndArray();

        List<ThreadDump.Thread> unmatchedThreads = new ThreadOrderingByStackTraceSizeDesc()
                .sortedCopy(threadDump.getUnmatchedThreadList());
        Multimap<ThreadDump.Thread, ThreadDump.Thread> unmatchedThreadsGroupedByStackTrace = LinkedListMultimap
                .create();
        List<ThreadDump.Thread> glowrootThreads = Lists.newArrayList();
        for (ThreadDump.Thread thread : unmatchedThreads) {
            if (thread.getName().startsWith("Glowroot-")) {
                glowrootThreads.add(thread);
            } else {
                unmatchedThreadsGroupedByStackTrace.put(getGrouping(thread), thread);
            }
            allThreads.add(thread);
        }
        jg.writeArrayFieldStart("unmatchedThreadsByStackTrace");
        for (Map.Entry<ThreadDump.Thread, Collection<ThreadDump.Thread>> entry : unmatchedThreadsGroupedByStackTrace
                .asMap().entrySet()) {
            jg.writeStartArray();
            for (ThreadDump.Thread thread : entry.getValue()) {
                writeThread(thread, jg);
            }
            jg.writeEndArray();
        }
        jg.writeStartArray();
        for (ThreadDump.Thread thread : glowrootThreads) {
            writeThread(thread, jg);
        }
        jg.writeEndArray();
        jg.writeEndArray();

        jg.writeFieldName("threadDumpingThread");
        writeThread(threadDump.getThreadDumpingThread(), jg);
        allThreads.add(threadDump.getThreadDumpingThread());
        writeDeadlockedCycles(allThreads, jg);
        jg.writeEndObject();
    } finally {
        jg.close();
    }
    return sb.toString();
}

From source file:org.apache.hadoop.hbase.rsgroup.RSGroupBasedLoadBalancer.java

@Override
public ServerName randomAssignment(HRegionInfo region, List<ServerName> servers) throws HBaseIOException {
    ListMultimap<String, HRegionInfo> regionMap = LinkedListMultimap.create();
    ListMultimap<String, ServerName> serverMap = LinkedListMultimap.create();
    generateGroupMaps(Lists.newArrayList(region), servers, regionMap, serverMap);
    List<ServerName> filteredServers = serverMap.get(regionMap.keySet().iterator().next());
    return this.internalBalancer.randomAssignment(region, filteredServers);
}

From source file:com.android.tools.idea.templates.GradleFilePsiMerger.java

/**
 * Looks for statements adding dependencies to different configurations (which look like 'configurationName "dependencyCoordinate"')
 * and tries to parse them into Gradle coordinates. If successful, adds the new coordinate to the map and removes the corresponding
 * PsiElement from the tree./*  w ww  .  j  a  v  a2  s .  c  o  m*/
 *
 * @return true if new items were added to the map
 */
private static boolean pullDependenciesIntoMap(@NotNull PsiElement root,
        @NotNull Map<String, Multimap<String, GradleCoordinate>> allConfigurations,
        @Nullable List<String> unparsedDependencies) {
    boolean wasMapUpdated = false;
    for (PsiElement existingElem : root.getChildren()) {
        if (existingElem instanceof GrCall) {
            PsiElement reference = existingElem.getFirstChild();
            if (reference instanceof GrReferenceExpression) {
                final String configurationName = reference.getText();
                boolean parsed = false;
                GrCall call = (GrCall) existingElem;
                GrArgumentList arguments = call.getArgumentList();
                // Don't try merging dependencies if one of them has a closure block attached.
                if (arguments != null && call.getClosureArguments().length == 0) {
                    GrExpression[] expressionArguments = arguments.getExpressionArguments();
                    if (expressionArguments.length == 1 && expressionArguments[0] instanceof GrLiteral) {
                        Object value = ((GrLiteral) expressionArguments[0]).getValue();
                        if (value instanceof String) {
                            String coordinateText = (String) value;
                            GradleCoordinate coordinate = GradleCoordinate
                                    .parseCoordinateString(coordinateText);
                            if (coordinate != null) {
                                parsed = true;
                                Multimap<String, GradleCoordinate> map = allConfigurations
                                        .get(configurationName);
                                if (map == null) {
                                    map = LinkedListMultimap.create();
                                    allConfigurations.put(configurationName, map);
                                }
                                if (!map.get(coordinate.getId()).contains(coordinate)) {
                                    map.put(coordinate.getId(), coordinate);
                                    existingElem.delete();
                                    wasMapUpdated = true;
                                }
                            }
                        }
                    }
                    if (!parsed && unparsedDependencies != null) {
                        unparsedDependencies.add(existingElem.getText());
                    }
                }
            }
        }

    }
    return wasMapUpdated;
}

From source file:org.ambraproject.wombat.controller.BrowseController.java

private List<TypedArticleGroup> buildArticleGroups(Site site, String issueId, List<Map<String, ?>> articles)
        throws IOException {
    // Articles grouped by their type. Order within the value lists is significant.
    ArticleType.Dictionary typeDictionary = ArticleType.getDictionary(site.getTheme());
    ListMultimap<ArticleType, Map<String, Object>> groupedArticles = LinkedListMultimap.create();
    for (Map<String, ?> article : articles) {
        if (!article.containsKey("revisionNumber"))
            continue; // Omit unpublished articles

        Map<String, Object> populatedArticle = new HashMap<>(article);

        Map<String, ?> ingestion = (Map<String, ?>) article.get("ingestion");
        ArticleType articleType = typeDictionary.lookUp((String) ingestion.get("articleType"));

        populateRelatedArticles(populatedArticle);

        populateAuthors(populatedArticle, site);

        groupedArticles.put(articleType, populatedArticle);
    }/*w  ww  .  j a  va2 s . c  o  m*/

    // The article types supported by this site, in the order in which they are supposed to appear.
    ImmutableList<ArticleType> articleTypes = typeDictionary.getSequence();

    // Produce a correctly ordered list of TypedArticleGroup, populated with the article groups.
    List<TypedArticleGroup> articleGroups = new ArrayList<>(articleTypes.size());
    for (ArticleType articleType : articleTypes) {
        List<Map<String, Object>> articlesOfType = groupedArticles.removeAll(articleType);
        if (!articlesOfType.isEmpty()) {
            articleGroups.add(new TypedArticleGroup(articleType, articlesOfType));
        }
    }

    // If any article groups were not matched, append them to the end.
    for (Map.Entry<ArticleType, List<Map<String, Object>>> entry : Multimaps.asMap(groupedArticles)
            .entrySet()) {
        ArticleType type = entry.getKey();
        TypedArticleGroup group = new TypedArticleGroup(type, entry.getValue());
        articleGroups.add(group);

        log.warn(String.format("Issue %s has articles of type \"%s\", which is not configured for %s: %s",
                issueId, type.getName(), site.getKey(),
                Lists.transform(group.articles, article -> article.get("doi"))));
    }

    return articleGroups;
}

From source file:eu.trentorise.opendata.commons.TodUtils.java

/**
 * Extracts parameters from given url. Works also with multiple params with
 * same name./*w w w  .j a  v  a  2s . c  om*/
 *
 * @return map of param name : [args]
 * @throws IllegalArgumentException
 * @since 1.1
 */
public static Multimap<String, String> parseUrlParams(String url) {
    URL u;
    try {
        u = new URL(url);
    } catch (MalformedURLException ex) {
        throw new IllegalArgumentException("Ill formed url!", ex);
    }
    Multimap<String, String> queryPairs = LinkedListMultimap.create();
    final String[] pairs = u.getQuery().split("&");

    try {
        for (String pair : pairs) {
            final int idx = pair.indexOf("=");

            final String key;

            key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;

            final String value = idx > 0 && pair.length() > idx + 1
                    ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8")
                    : "";
            queryPairs.put(key, value);
        }
        return queryPairs;
    } catch (UnsupportedEncodingException ex) {
        throw new IllegalArgumentException("Encoding not supported!", ex);
    }
}