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

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

Introduction

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

Prototype

boolean put(@Nullable K key, @Nullable V value);

Source Link

Document

Stores a key-value pair in this multimap.

Usage

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

/**
 * Extracts parameters from given url. Works also with multiple params with
 * same name.//from  w  w w.  j av  a  2  s .  c  o m
 *
 * @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);
    }
}

From source file:io.prestosql.execution.scheduler.NodeScheduler.java

public static SplitPlacementResult selectDistributionNodes(NodeMap nodeMap, NodeTaskMap nodeTaskMap,
        int maxSplitsPerNode, int maxPendingSplitsPerTask, Set<Split> splits, List<RemoteTask> existingTasks,
        BucketNodeMap bucketNodeMap) {/*from  w  w  w  . j  a  v a2 s  .co m*/
    Multimap<Node, Split> assignments = HashMultimap.create();
    NodeAssignmentStats assignmentStats = new NodeAssignmentStats(nodeTaskMap, nodeMap, existingTasks);

    Set<Node> blockedNodes = new HashSet<>();
    for (Split split : splits) {
        // node placement is forced by the bucket to node map
        Node node = bucketNodeMap.getAssignedNode(split).get();

        // if node is full, don't schedule now, which will push back on the scheduling of splits
        if (assignmentStats.getTotalSplitCount(node) < maxSplitsPerNode
                || assignmentStats.getQueuedSplitCountForStage(node) < maxPendingSplitsPerTask) {
            assignments.put(node, split);
            assignmentStats.addAssignedSplit(node);
        } else {
            blockedNodes.add(node);
        }
    }

    ListenableFuture<?> blocked = toWhenHasSplitQueueSpaceFuture(blockedNodes, existingTasks,
            calculateLowWatermark(maxPendingSplitsPerTask));
    return new SplitPlacementResult(blocked, ImmutableMultimap.copyOf(assignments));
}

From source file:org.eclipse.incquery.tooling.core.project.ProjectGenerationHelper.java

/**
 * Updates the selected project to contain the selected extension. The extensions are identified using an identifier
 * and extension point together; old extensions are replaced with the new ones, other extensions are kept intact. An
 * extension will be ignored, if exist in the removedExtensions list.
 * /*from ww  w .  j  a va  2 s. c o m*/
 * @param project
 *            an existing, open PDE plug-in project
 * @param contributedExtensions
 * @param removedExtensions
 * @param monitor
 * @throws CoreException
 */
public static void ensureExtensions(IProject project, Iterable<IPluginExtension> contributedExtensions,
        Iterable<Pair<String, String>> removedExtensions, IProgressMonitor monitor) throws CoreException {
    Preconditions.checkArgument(project.exists() && project.isOpen() && (PDE.hasPluginNature(project)),
            INVALID_PROJECT_MESSAGE);

    if (StringExtensions.isNullOrEmpty(project.getName())) {
        return;
    }
    Multimap<String, IPluginExtension> extensionMap = ArrayListMultimap.create();
    for (IPluginExtension extension : contributedExtensions) {
        extensionMap.put(extension.getId(), extension);
    }
    // XXX Using two APIs to extension generation: one to read and one to
    // write
    IFile pluginXml = PDEProject.getPluginXml(project);
    IPluginModel plugin = (IPluginModel) PDECore.getDefault().getModelManager().findModel(project);
    WorkspacePluginModel fModel = new WorkspacePluginModel(pluginXml, false);
    fModel.setEditable(true);
    fModel.load();
    // Storing a write-only plugin.xml model
    IExtensions extensions = fModel.getExtensions();
    // Storing a read-only plugin.xml model
    if (plugin != null) {
        IExtensions readExtension = plugin.getExtensions();
        nextExtension: for (final IPluginExtension extension : readExtension.getExtensions()) {
            String id = getExtensionId(extension, project);
            boolean extensionToCreateFound = isExtensionInMap(extensionMap, extension, extension.getId());
            if (!extensionToCreateFound) {
                extensionToCreateFound = isExtensionInMap(extensionMap, extension, id);
            }
            if (extensionToCreateFound) {
                continue nextExtension;
            }
            // remove if contained in the removables
            final String extensionId = id;
            Pair<String, String> removable = Iterables.find(removedExtensions,
                    new Predicate<Pair<String, String>>() {
                        @Override
                        public boolean apply(Pair<String, String> p) {
                            return p.getKey().equals(extensionId) && p.getValue().equals(extension.getPoint());
                        }
                    }, null);

            if (removable == null) {
                // XXX cloning extensions to remove project name prefixes
                IPluginExtension cloneExtension = fModel.createExtension();
                cloneExtension.setId(id);
                String name = extension.getName();
                if (name != null && !name.isEmpty()) {
                    cloneExtension.setName(name);
                }
                cloneExtension.setPoint(extension.getPoint());
                for (IPluginObject obj : extension.getChildren()) {
                    cloneExtension.add(obj);
                }
                cloneExtension.setInTheModel(true);
                extensions.add(cloneExtension);
            }
        }
        for (IPluginExtensionPoint point : readExtension.getExtensionPoints()) {
            extensions.add(point);
        }
    }
    for (IPluginExtension contribExtension : contributedExtensions) {
        extensions.add(contribExtension);
        contribExtension.setInTheModel(true);
    }
    fModel.save();
}

From source file:org.jetbrains.kotlin.grammar.ConfluenceHyperlinksGenerator.java

private static StringBuilder generate(List<Token> tokens) throws IOException {
    StringBuilder result = new StringBuilder("h1. Contents\n").append("{toc:style=disc|indent=20px}");

    Set<String> declaredSymbols = new HashSet<String>();
    Set<String> usedSymbols = new HashSet<String>();
    Multimap<String, String> usages = Multimaps.newSetMultimap(Maps.<String, Collection<String>>newHashMap(),
            new Supplier<Set<String>>() {
                @Override//from w w  w.  j  a  va  2s  .com
                public Set<String> get() {
                    return Sets.newHashSet();
                }
            });

    Declaration lastDeclaration = null;
    for (Token advance : tokens) {
        if (advance instanceof Declaration) {
            Declaration declaration = (Declaration) advance;
            lastDeclaration = declaration;
            declaredSymbols.add(declaration.getName());
        } else if (advance instanceof Identifier) {
            Identifier identifier = (Identifier) advance;
            assert lastDeclaration != null;
            usages.put(identifier.getName(), lastDeclaration.getName());
            usedSymbols.add(identifier.getName());
        }
    }

    for (Token token : tokens) {
        if (token instanceof Declaration) {
            Declaration declaration = (Declaration) token;
            result.append("{anchor:").append(declaration.getName()).append("}");
            if (!usedSymbols.contains(declaration.getName())) {
                //                    result.append("(!) *Unused!* ");
                System.out.println("Unused: " + tokenWithPosition(token));
            }
            Collection<String> myUsages = usages.get(declaration.getName());
            if (!myUsages.isEmpty()) {
                result.append("\\[{color:grey}Used by ");
                for (Iterator<String> iterator = myUsages.iterator(); iterator.hasNext();) {
                    String usage = iterator.next();
                    result.append("[#").append(usage).append("]");
                    if (iterator.hasNext()) {
                        result.append(", ");
                    }
                }
                result.append("{color}\\]\n");
            }
            result.append(token);
            continue;
        } else if (token instanceof Identifier) {
            Identifier identifier = (Identifier) token;
            if (!declaredSymbols.contains(identifier.getName())) {
                result.append("(!) *Undeclared!* ");
                System.out.println("Undeclared: " + tokenWithPosition(token));
            }
        }
        result.append(token);
    }
    return result;
}

From source file:org.gradle.model.internal.manage.binding.DefaultStructBindingsStore.java

private static <T> Set<StructMethodBinding> collectMethodBindings(
        StructBindingExtractionContext<T> extractionContext,
        Map<String, Multimap<PropertyAccessorType, StructMethodBinding>> propertyBindings) {
    Collection<WeaklyTypeReferencingMethod<?, ?>> implementedMethods = collectImplementedMethods(
            extractionContext.getImplementedSchemas());
    Map<Wrapper<Method>, WeaklyTypeReferencingMethod<?, ?>> publicViewImplMethods = collectPublicViewImplMethods(
            extractionContext.getPublicSchema());
    Map<Wrapper<Method>, WeaklyTypeReferencingMethod<?, ?>> delegateMethods = collectDelegateMethods(
            extractionContext.getDelegateSchema());

    ImmutableSet.Builder<StructMethodBinding> methodBindingsBuilder = ImmutableSet.builder();
    for (WeaklyTypeReferencingMethod<?, ?> weakImplementedMethod : implementedMethods) {
        Method implementedMethod = weakImplementedMethod.getMethod();
        PropertyAccessorType accessorType = PropertyAccessorType.of(implementedMethod);

        Wrapper<Method> methodKey = SIGNATURE_EQUIVALENCE.wrap(implementedMethod);
        WeaklyTypeReferencingMethod<?, ?> weakDelegateImplMethod = delegateMethods.get(methodKey);
        WeaklyTypeReferencingMethod<?, ?> weakPublicImplMethod = publicViewImplMethods.get(methodKey);
        if (weakDelegateImplMethod != null && weakPublicImplMethod != null) {
            extractionContext.add(weakImplementedMethod,
                    String.format("it is both implemented by the view '%s' and the delegate type '%s'",
                            extractionContext.getPublicSchema().getType().getDisplayName(),
                            extractionContext.getDelegateSchema().getType().getDisplayName()));
        }/*  w  ww  . j a v a 2 s .  c  o  m*/

        String propertyName = accessorType == null ? null : accessorType.propertyNameFor(implementedMethod);

        StructMethodBinding binding;
        if (!Modifier.isAbstract(implementedMethod.getModifiers())) {
            binding = new DirectMethodBinding(weakImplementedMethod, accessorType);
        } else if (weakPublicImplMethod != null) {
            binding = new BridgeMethodBinding(weakImplementedMethod, weakPublicImplMethod, accessorType);
        } else if (weakDelegateImplMethod != null) {
            binding = new DelegateMethodBinding(weakImplementedMethod, weakDelegateImplMethod, accessorType);
        } else if (propertyName != null) {
            binding = new ManagedPropertyMethodBinding(weakImplementedMethod, propertyName, accessorType);
        } else {
            handleNoMethodImplementation(extractionContext, weakImplementedMethod);
            continue;
        }
        methodBindingsBuilder.add(binding);

        if (accessorType != null) {
            Multimap<PropertyAccessorType, StructMethodBinding> accessorBindings = propertyBindings
                    .get(propertyName);
            if (accessorBindings == null) {
                accessorBindings = ArrayListMultimap.create();
                propertyBindings.put(propertyName, accessorBindings);
            }
            accessorBindings.put(accessorType, binding);
        }
    }
    return methodBindingsBuilder.build();
}

From source file:org.jetbrains.jet.grammar.GrammarGenerator.java

private static String generate(List<Token> tokens) throws IOException {
    StringWriter result = new StringWriter();

    Set<String> declaredSymbols = new HashSet<String>();
    Set<String> usedSymbols = new HashSet<String>();
    Multimap<String, String> usages = Multimaps.newSetMultimap(Maps.<String, Collection<String>>newHashMap(),
            new Supplier<Set<String>>() {
                @Override//from w  ww. j  av a2  s  .  c  o  m
                public Set<String> get() {
                    return Sets.newHashSet();
                }
            });

    Declaration lastDeclaration = null;
    for (Token advance : tokens) {
        if (advance instanceof Declaration) {
            Declaration declaration = (Declaration) advance;
            lastDeclaration = declaration;
            declaredSymbols.add(declaration.getName());
        } else if (advance instanceof Identifier) {
            Identifier identifier = (Identifier) advance;
            assert lastDeclaration != null;
            usages.put(identifier.getName(), lastDeclaration.getName());
            usedSymbols.add(identifier.getName());
        }
    }

    try {

        JAXBContext context = JAXBContext.newInstance(Annotation.class, Comment.class, Declaration.class,
                DocComment.class, Identifier.class, Other.class, StringToken.class, SymbolToken.class,
                Token.class, WhiteSpace.class, TokenList.class);
        Marshaller m = context.createMarshaller();
        TokenList list = new TokenList(tokens);
        list.updateUsages(usedSymbols, usages);
        m.marshal(list, result);

    } catch (PropertyException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    }

    result.flush();
    result.close();
    return result.toString();
}

From source file:org.apache.phoenix.hbase.index.write.IndexWriter.java

/**
 * Convert the passed index updates to {@link HTableInterfaceReference}s.
 * @param indexUpdates from the index builder
 * @return pairs that can then be written by an {@link IndexWriter}.
 *///from   w w w  .  jav  a 2 s . c o m
public static Multimap<HTableInterfaceReference, Mutation> resolveTableReferences(
        Collection<Pair<Mutation, byte[]>> indexUpdates) {
    Multimap<HTableInterfaceReference, Mutation> updates = ArrayListMultimap
            .<HTableInterfaceReference, Mutation>create();
    // simple map to make lookups easy while we build the map of tables to create
    Map<ImmutableBytesPtr, HTableInterfaceReference> tables = new HashMap<ImmutableBytesPtr, HTableInterfaceReference>(
            updates.size());
    for (Pair<Mutation, byte[]> entry : indexUpdates) {
        byte[] tableName = entry.getSecond();
        ImmutableBytesPtr ptr = new ImmutableBytesPtr(tableName);
        HTableInterfaceReference table = tables.get(ptr);
        if (table == null) {
            table = new HTableInterfaceReference(ptr);
            tables.put(ptr, table);
        }
        updates.put(table, entry.getFirst());
    }

    return updates;
}

From source file:cuchaz.enigma.convert.MappingsConverter.java

public static Mappings newMappings(ClassMatches matches, Mappings oldMappings, Deobfuscator sourceDeobfuscator,
        Deobfuscator destDeobfuscator) {

    // sort the unique matches by size of inner class chain
    Multimap<Integer, java.util.Map.Entry<ClassEntry, ClassEntry>> matchesByDestChainSize = HashMultimap
            .create();/*from w ww.  j  ava 2  s.c om*/
    for (java.util.Map.Entry<ClassEntry, ClassEntry> match : matches.getUniqueMatches().entrySet()) {
        int chainSize = destDeobfuscator.getJarIndex().getObfClassChain(match.getValue()).size();
        matchesByDestChainSize.put(chainSize, match);
    }

    // build the mappings (in order of small-to-large inner chains)
    Mappings newMappings = new Mappings();
    List<Integer> chainSizes = Lists.newArrayList(matchesByDestChainSize.keySet());
    Collections.sort(chainSizes);
    for (int chainSize : chainSizes) {
        for (java.util.Map.Entry<ClassEntry, ClassEntry> match : matchesByDestChainSize.get(chainSize)) {

            // get class info
            ClassEntry obfSourceClassEntry = match.getKey();
            ClassEntry obfDestClassEntry = match.getValue();
            List<ClassEntry> destClassChain = destDeobfuscator.getJarIndex()
                    .getObfClassChain(obfDestClassEntry);

            ClassMapping sourceMapping = sourceDeobfuscator.getMappings().getClassByObf(obfSourceClassEntry);
            if (sourceMapping == null) {
                // if this class was never deobfuscated, don't try to match it
                continue;
            }

            // find out where to make the dest class mapping
            if (destClassChain.size() == 1) {
                // not an inner class, add directly to mappings
                newMappings
                        .addClassMapping(migrateClassMapping(obfDestClassEntry, sourceMapping, matches, false));
            } else {
                // inner class, find the outer class mapping
                ClassMapping destMapping = null;
                for (int i = 0; i < destClassChain.size() - 1; i++) {
                    ClassEntry destChainClassEntry = destClassChain.get(i);
                    if (destMapping == null) {
                        destMapping = newMappings.getClassByObf(destChainClassEntry);
                        if (destMapping == null) {
                            destMapping = new ClassMapping(destChainClassEntry.getName());
                            newMappings.addClassMapping(destMapping);
                        }
                    } else {
                        destMapping = destMapping
                                .getInnerClassByObfSimple(destChainClassEntry.getInnermostClassName());
                        if (destMapping == null) {
                            destMapping = new ClassMapping(destChainClassEntry.getName());
                            destMapping.addInnerClassMapping(destMapping);
                        }
                    }
                }
                destMapping.addInnerClassMapping(
                        migrateClassMapping(obfDestClassEntry, sourceMapping, matches, true));
            }
        }
    }
    return newMappings;
}

From source file:com.opengamma.strata.loader.csv.CurveGroupDefinitionCsvLoader.java

/**
 * Builds a list of curve group definitions from the map of curves and their keys.
 * <p>// ww  w.  j  a  v  a2  s .  com
 * The keys specify which curve groups each curve belongs to and how it is used in the group, for example
 * as a discount curve for a particular currency or as a forward curve for an index.
 *
 * @param garMap  the map of name to keys
 * @return a map of curve group name to curve group definition built from the curves
 */
private static ImmutableList<CurveGroupDefinition> buildCurveGroups(
        Map<CurveName, Set<GroupAndReference>> garMap) {

    Multimap<CurveGroupName, CurveGroupEntry> groups = LinkedHashMultimap.create();

    for (Map.Entry<CurveName, Set<GroupAndReference>> entry : garMap.entrySet()) {
        CurveName curveName = entry.getKey();
        Set<GroupAndReference> curveIds = entry.getValue();
        Map<CurveGroupName, List<GroupAndReference>> idsByGroup = curveIds.stream()
                .collect(groupingBy(p -> p.groupName));

        for (Map.Entry<CurveGroupName, List<GroupAndReference>> groupEntry : idsByGroup.entrySet()) {
            CurveGroupName groupName = groupEntry.getKey();
            List<GroupAndReference> gars = groupEntry.getValue();
            groups.put(groupName, curveGroupEntry(curveName, gars));
        }
    }
    return MapStream.of(groups.asMap())
            .map((name, entry) -> CurveGroupDefinition.of(name, entry, ImmutableList.of()))
            .collect(toImmutableList());
}

From source file:net.minecraftforge.fml.common.discovery.json.JsonAnnotationLoader.java

public static Multimap<String, ASMData> loadJson(InputStream data, ModCandidate candidate, ASMDataTable table) {
    Map<String, ASMInfo> map = GSON.fromJson(new InputStreamReader(data, StandardCharsets.UTF_8), INFO_TABLE);
    Multimap<String, ASMData> ret = HashMultimap.create();

    for (Entry<String, ASMInfo> entry : map.entrySet()) {
        //TODO: Java9 Multi-Release Jars, picking the correct class for the current platform. For now we just ignore them.
        if (entry.getKey().startsWith("META-INF/"))
            continue;
        //TODO: Remove in 1.13, some older mods have these in the entries due to FG issue. Basically filter out scala synthetic class.
        if (entry.getKey().endsWith("$"))
            continue;

        ASMInfo asm_info = entry.getValue();
        if (asm_info.interfaces != null) {
            for (String type : asm_info.interfaces) {
                //Interfaces use internal name, but annotations use source names. See ASMModParser.sendToTable
                table.addASMData(candidate, type, asm_info.name, null, null);
                ret.put(type, new ASMData(candidate, type, asm_info.name, null, null));
            }/*w ww . j  av  a  2  s.  c o  m*/
        }

        String owner_name = asm_info.name.replace('/', '.');
        if (asm_info.annotations != null) {
            for (Annotation anno : asm_info.annotations) {
                String name = anno.name.indexOf(';') > 0 ? Type.getType(anno.name).getClassName() : anno.name;
                String target = anno.target != null
                        && (anno.type == TargetType.CLASS || anno.type == TargetType.SUBTYPE)
                                ? anno.target.replace('/', '.')
                                : anno.target;

                table.addASMData(candidate, name, owner_name, target, anno.getValues(asm_info));
                ret.put(name, new ASMData(candidate, name, owner_name, target, anno.getValues(asm_info)));
            }
        }
    }

    return ret;
}