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

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

Introduction

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

Prototype

Collection<V> get(@Nullable K key);

Source Link

Document

Returns a view collection of the values associated with key in this multimap, if any.

Usage

From source file:com.google.gerrit.httpd.restapi.RestApiServlet.java

private static void enablePartialGetFields(GsonBuilder gb, Multimap<String, String> config) {
    final Set<String> want = Sets.newHashSet();
    for (String p : config.get("fields")) {
        Iterables.addAll(want, OptionUtil.splitOptionValue(p));
    }//  w ww  . j a  v a  2 s.  com
    if (!want.isEmpty()) {
        gb.addSerializationExclusionStrategy(new ExclusionStrategy() {
            private final Map<String, String> names = Maps.newHashMap();

            @Override
            public boolean shouldSkipField(FieldAttributes field) {
                String name = names.get(field.getName());
                if (name == null) {
                    // Names are supplied by Gson in terms of Java source.
                    // Translate and cache the JSON lower_case_style used.
                    try {
                        name = FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES.translateName(//
                                field.getDeclaringClass().getDeclaredField(field.getName()));
                        names.put(field.getName(), name);
                    } catch (SecurityException e) {
                        return true;
                    } catch (NoSuchFieldException e) {
                        return true;
                    }
                }
                return !want.contains(name);
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }
        });
    }
}

From source file:net.sourcedestination.sai.comparison.matching.MatchingGenerator.java

/** given a matching of nodes, extends the matching to pair up all edges which
 * have isomorphically matched incident nodes. In the case of a multigraph, 
 * edges are matched arbitrarily./*from  w  ww .j av a 2 s. co  m*/
 * 
 * @param nodeMatching
 * @param fscc
 * @return
 */
public static GraphMatching induceEdgeMatching(GraphMatching nodeMatching,
        FeatureSetCompatibilityChecker fscc) {

    // if they're not directed, we need to treat edge compatibility differently:
    if (nodeMatching.getGraph1().getFeatures().anyMatch(f -> f.equals(DIRECTED))
            && nodeMatching.getGraph2().getFeatures().anyMatch(f -> f.equals(DIRECTED)))
        return induceEdgeMatchingUndirected(nodeMatching, fscc);

    final Graph g1 = nodeMatching.getGraph1();
    final Graph g2 = nodeMatching.getGraph2();
    BiMap<Integer, Integer> edgeMatch = HashBiMap.create();

    Multimap<Pair<Integer>, Integer> g2Edges = HashMultimap.create();
    g2.getEdgeIDs().forEach(
            g2e -> g2Edges.put(Pair.makePair(g2.getEdgeSourceNodeID(g2e), g2.getEdgeTargetNodeID(g2e)), g2e));

    g1.getEdgeIDs().forEach(eid -> {
        int g1n1 = g1.getEdgeSourceNodeID(eid);
        int g1n2 = g1.getEdgeTargetNodeID(eid);
        int g2n1 = nodeMatching.getMatchedNodeInGraph2(g1n1);
        int g2n2 = nodeMatching.getMatchedNodeInGraph2(g1n2);
        if (g2n1 == -1 || g2n2 == -1)
            return; //skip edges with unmapped nodes in graph 2      

        if (g2Edges.get(Pair.makePair(g2n1, g2n2)).size() == 0)
            return; //skip if it can't be matched to a graph 2 edge

        int g2MatchedEdge = -1; // make sure the edges are compatible
        for (int g2e : g2Edges.get(Pair.makePair(g2n1, g2n2)))
            if (fscc.apply(g1.getEdgeFeatures(eid).collect(toSet()), g2.getEdgeFeatures(g2e).collect(toSet())))
                g2MatchedEdge = g2e;

        if (g2MatchedEdge != -1) //if we found a match, record it
            edgeMatch.put(eid, g2MatchedEdge);
    });
    return includeEdgeMatching(nodeMatching, edgeMatch);
}

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

/**
 * @param extensionMap//from   w ww. jav a  2  s.  com
 * @param extension
 * @param id
 * @return
 */
private static boolean isExtensionInMap(Multimap<String, IPluginExtension> extensionMap,
        final IPluginExtension extension, String id) {
    boolean extensionToCreateFound = false;
    if (extensionMap.containsKey(id)) {
        extensionToCreateFound = Iterables.any(extensionMap.get(id), new Predicate<IPluginExtension>() {
            @Override
            public boolean apply(IPluginExtension ex) {
                return ex.getPoint().equals(extension.getPoint());
            }
        });
    }
    return extensionToCreateFound;
}

From source file:com.facebook.buck.cli.MissingSymbolsHandler.java

/**
 * Instantiate a MissingSymbolsHandler and wrap it in a listener that calls it on the appropriate
 * events. This is done as part of the global listener setup in Main, and it's the entry point
 * into most of the dependency autodetection code.
 */// w w  w .j  a va2 s.  c  o  m
public static BuckEventListener createListener(ProjectFilesystem projectFilesystem,
        ImmutableSet<Description<?>> descriptions, BuckConfig config, BuckEventBus buckEventBus,
        Console console, JavacOptions javacOptions, ImmutableMap<String, String> environment) {
    final MissingSymbolsHandler missingSymbolsHandler = create(projectFilesystem, descriptions, config,
            buckEventBus, console, javacOptions, environment);

    final Multimap<BuildId, MissingSymbolEvent> missingSymbolEvents = HashMultimap.create();

    BuckEventListener missingSymbolsListener = new BuckEventListener() {
        @Override
        public void outputTrace(BuildId buildId) {
            // If we put {@link #printNeededDependencies} here, it's output won't be visible in buckd.
            // Instead, we listen for BuildEvent.Finished, below.
        }

        @Subscribe
        public void onMissingSymbol(MissingSymbolEvent event) {
            missingSymbolEvents.put(event.getBuildId(), event);
        }

        @Subscribe
        public void onBuildFinished(BuildEvent.Finished event) {
            // Shortcircuit if there aren't any failures.
            if (missingSymbolEvents.get(event.getBuildId()).isEmpty()) {
                return;
            }
            try {
                missingSymbolsHandler.printNeededDependencies(missingSymbolEvents.get(event.getBuildId()));
            } catch (InterruptedException e) {
                LOG.debug(e, "Missing symbols handler did not complete in time.");
            } catch (RuntimeException e) {
                if (e.getCause() instanceof ClosedByInterruptException) {
                    LOG.debug(e.getCause(), "Missing symbols handler did not complete in time.");
                } else {
                    throw e;
                }
            }
            missingSymbolEvents.removeAll(event.getBuildId());
        }
    };

    return missingSymbolsListener;
}

From source file:org.prebake.service.tools.JarProcess.java

static byte extractJar(Path cwd, String... argv) throws IOException {
    int pos = 0;/*from www  . j  a v  a  2s .com*/
    int last = argv.length - 1;

    Path root = cwd.getRoot();

    String jarFile = argv[++pos];

    MutableGlobSet globs = new MutableGlobSet();
    Multimap<Glob, Path> outRoots = Multimaps.newListMultimap(Maps.<Glob, Collection<Path>>newHashMap(),
            new Supplier<List<Path>>() {
                public List<Path> get() {
                    return Lists.newArrayList();
                }
            });
    while (pos < last) {
        String globStr = argv[++pos];
        Glob g = Glob.fromString(globStr);
        String treeRoot = g.getTreeRoot();
        if (!"".equals(treeRoot)) {
            globStr = globStr.substring(treeRoot.length());
            if (globStr.startsWith("///")) {
                globStr = globStr.substring(3);
            }
            g = Glob.fromString(globStr);
        }
        if (outRoots.get(g).isEmpty()) {
            globs.add(g);
        }
        outRoots.put(g, cwd.resolve(FsUtil.denormalizePath(root, treeRoot)));
    }

    ZipInputStream in = new ZipInputStream(cwd.resolve(jarFile).newInputStream());
    try {
        Set<Path> dests = Sets.newLinkedHashSet();
        for (ZipEntry e; (e = in.getNextEntry()) != null;) {
            Path path = root.getFileSystem().getPath(FsUtil.denormalizePath(root, e.getName()));
            dests.clear();
            for (Glob g : globs.matching(path)) {
                dests.addAll(outRoots.get(g));
            }
            if (e.isDirectory()) {
                for (Path dest : dests) {
                    mkdirs(dest.resolve(path));
                }
            } else {
                if (!dests.isEmpty()) {
                    OutputStream[] outs = new OutputStream[dests.size()];
                    try {
                        Iterator<Path> it = dests.iterator();
                        for (int i = 0; i < outs.length; ++i) {
                            Path outFile = it.next().resolve(path);
                            mkdirs(outFile.getParent());
                            outs[i] = outFile.newOutputStream(StandardOpenOption.CREATE_NEW,
                                    StandardOpenOption.TRUNCATE_EXISTING);
                        }
                        byte[] buf = new byte[4096];
                        for (int nRead; (nRead = in.read(buf)) > 0;) {
                            for (OutputStream os : outs) {
                                os.write(buf, 0, nRead);
                            }
                        }
                    } finally {
                        for (OutputStream os : outs) {
                            if (os != null) {
                                Closeables.closeQuietly(os);
                            }
                        }
                    }
                }
                in.closeEntry();
            }
        }
    } finally {
        in.close();
    }
    return 0;
}

From source file:com.lithium.flow.matcher.StringMatchers.java

@Nonnull
public static StringMatcher fromList(@Nonnull List<String> list) {
    Multimap<String, String> multimap = HashMultimap.create();
    for (String value : list) {
        int index = value.indexOf(':');
        if (index == -1 || index >= value.length() - 1) {
            multimap.put("exact", value);
        } else {// w  w  w  .  j  a v  a2  s . c o m
            int index2 = value.indexOf("?[");
            int index3 = value.indexOf("]:", index2);
            if (index2 > -1 && index3 > -1 && index2 < index) {
                index = index2 + 1;
            }

            String type = value.substring(0, index);
            String param = value.substring(index + 1);
            multimap.put(type, param);
        }
    }

    List<StringMatcher> quickMatchers = Lists.newArrayList();
    quickMatchers.addAll(buildList(multimap, "len", LenStringMatcher::new));
    Collection<String> exacts = multimap.get("exact");
    if (exacts.size() == 1) {
        quickMatchers.add(new ExactStringMatcher(exacts.iterator().next()));
    } else if (exacts.size() > 1) {
        quickMatchers.add(new ExactSetStringMatcher(Sets.newHashSet(exacts)));
    }
    quickMatchers.addAll(buildList(multimap, "prefix", PrefixStringMatcher::new));
    quickMatchers.addAll(buildList(multimap, "suffix", SuffixStringMatcher::new));
    quickMatchers.addAll(buildList(multimap, "contains", ContainsStringMatcher::new));

    List<StringMatcher> lowerMatchers = Lists.newArrayList();
    lowerMatchers.addAll(buildList(multimap, "lower.prefix", PrefixStringMatcher::new));
    lowerMatchers.addAll(buildList(multimap, "lower.suffix", SuffixStringMatcher::new));
    lowerMatchers.addAll(buildList(multimap, "lower.contains", ContainsStringMatcher::new));

    List<StringMatcher> regexMatchers = Lists.newArrayList();
    regexMatchers.addAll(buildList(multimap, "regex", RegexStringMatcher::new));
    regexMatchers.addAll(buildList(multimap, "lower.regex", LowerRegexStringMatcher::new));

    List<StringMatcher> allMatchers = Lists.newArrayList();
    allMatchers.add(buildComposite(quickMatchers, false));
    allMatchers.add(buildComposite(lowerMatchers, true));
    allMatchers.add(buildComposite(regexMatchers, false));
    return buildComposite(allMatchers, false);
}

From source file:grakn.core.graql.gremlin.RelationTypeInference.java

private static Multimap<Variable, Variable> getRelationRolePlayerMap(Set<Fragment> allFragments,
        Multimap<Variable, Type> instanceVarTypeMap) {
    // get all relation vars and its role player vars
    Multimap<Variable, Variable> relationRolePlayerMap = HashMultimap.create();
    allFragments.stream().filter(OutRolePlayerFragment.class::isInstance)
            .forEach(fragment -> relationRolePlayerMap.put(fragment.start(), fragment.end()));

    Multimap<Variable, Variable> inferrableRelationsRolePlayerMap = HashMultimap.create();

    allFragments.stream().filter(OutRolePlayerFragment.class::isInstance)
            .filter(fragment -> !instanceVarTypeMap.containsKey(fragment.start())) // filter out known rel types
            .forEach(fragment -> {//from   w w w .  ja  v a2s .  co  m
                Variable relation = fragment.start();

                // the relation should have at least 2 known role players so we can infer something useful
                int numRolePlayersHaveType = 0;
                for (Variable rolePlayer : relationRolePlayerMap.get(relation)) {
                    if (instanceVarTypeMap.containsKey(rolePlayer)) {
                        numRolePlayersHaveType++;
                    }
                }

                if (numRolePlayersHaveType >= 2) {
                    inferrableRelationsRolePlayerMap.put(relation, fragment.end());
                }
            });

    return inferrableRelationsRolePlayerMap;
}

From source file:org.apache.brooklyn.core.typereg.BundleUpgradeParser.java

private static Multimap<VersionedName, VersionRangedName> parseUpgradeForTypesHeader(String input,
        Bundle bundle, Supplier<? extends Iterable<? extends RegisteredType>> typeSupplier,
        Multimap<VersionedName, VersionRangedName> upgradesForBundles) {
    List<String> sourceVersions = null;
    if (upgradesForBundles != null) {
        Collection<VersionRangedName> acceptableRanges = upgradesForBundles.get(new VersionedName(bundle));
        if (acceptableRanges != null && !acceptableRanges.isEmpty()) {
            for (VersionRangedName n : acceptableRanges) {
                if (n.getSymbolicName().equals(bundle.getSymbolicName())) {
                    if (sourceVersions == null) {
                        sourceVersions = MutableList.of();
                    }/*from ww w.  j  av  a 2  s. co m*/
                    sourceVersions.add(n.getOsgiVersionRange().toString());
                }
            }
        }
    }
    Set<VersionedName> typeSupplierNames = MutableList.copyOf(typeSupplier.get()).stream()
            .map((t) -> VersionedName.toOsgiVersionedName(t.getVersionedName())).collect(Collectors.toSet());
    if (input == null && sourceVersions != null && !sourceVersions.isEmpty()) {
        input = "*";
    }
    return parseVersionRangedNameEqualsVersionedNameList(input, false,
            // wildcard means all types, all versions of this bundle this bundle replaces
            getTypeNamesInBundle(typeSupplier), sourceVersions,
            // default target is same type at version of this bundle
            (i) -> {
                VersionedName targetTypeAtBundleVersion = new VersionedName(i.getSymbolicName(),
                        bundle.getVersion());
                if (!typeSupplierNames.contains(VersionedName.toOsgiVersionedName(targetTypeAtBundleVersion))) {
                    throw new IllegalStateException("Bundle manifest declares it upgrades " + i + " "
                            + "but does not declare an explicit target and does not contain inferred target "
                            + targetTypeAtBundleVersion);
                }
                return targetTypeAtBundleVersion;
            });
}

From source file:com.google.devtools.build.lib.collect.ImmutableSortedKeyListMultimap.java

@SuppressWarnings("unchecked")
public static <K extends Comparable<K>, V> ImmutableSortedKeyListMultimap<K, V> copyOf(Multimap<K, V> data) {
    if (data.isEmpty()) {
        return EMPTY_MULTIMAP;
    }/*from ww  w. j  a va2  s  . c o  m*/
    if (data instanceof ImmutableSortedKeyListMultimap) {
        return (ImmutableSortedKeyListMultimap<K, V>) data;
    }
    Set<K> keySet = data.keySet();
    int size = keySet.size();
    K[] sortedKeys = (K[]) new Comparable<?>[size];
    int index = 0;
    for (K key : keySet) {
        sortedKeys[index++] = Preconditions.checkNotNull(key);
    }
    Arrays.sort(sortedKeys);
    List<V>[] values = (List<V>[]) new List<?>[size];
    for (int i = 0; i < size; i++) {
        values[i] = ImmutableList.copyOf(data.get(sortedKeys[i]));
    }
    return new ImmutableSortedKeyListMultimap<>(sortedKeys, values);
}

From source file:org.crypto.sse.RR2Lev.java

public static List<String> query(byte[][] keys, Multimap<String, byte[]> dictionary, byte[][] array)
        throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, NoSuchPaddingException, IOException {

    byte[] l = CryptoPrimitives.generateCmac(keys[0], Integer.toString(0));

    List<byte[]> tempList = new ArrayList<byte[]>(dictionary.get(new String(l)));

    if (!(tempList.size() == 0)) {
        String temp = (new String(CryptoPrimitives.decryptAES_CTR_String(tempList.get(0), keys[1])))
                .split("\t\t\t")[0];
        temp = temp.replaceAll("\\s", "");
        temp = temp.replace('[', ',');
        temp = temp.replace("]", "");

        String[] result = temp.split(",");

        List<String> resultFinal = new ArrayList<String>(Arrays.asList(result));
        // We remove the flag that identifies the size of the dataset

        if (result[0].equals("1")) {

            resultFinal.remove(0);//from w  ww.  j a  v  a  2  s .  c  o m
            return resultFinal;
        }

        else if (result[0].equals("2")) {
            resultFinal.remove(0);

            List<String> resultFinal2 = new ArrayList<String>();

            for (String key : resultFinal) {

                boolean flag = true;
                int counter = 0;
                while (flag) {

                    if (counter < key.length() && Character.isDigit(key.charAt(counter))) {

                        counter++;
                    }

                    else {
                        flag = false;
                    }
                }

                String temp2 = "";
                if (!(array[Integer.parseInt((String) key.subSequence(0, counter))] == null)) {
                    temp2 = (new String(CryptoPrimitives.decryptAES_CTR_String(
                            array[Integer.parseInt((String) key.subSequence(0, counter))], keys[1])))
                                    .split("\t\t\t")[0];
                }
                temp2 = temp2.replaceAll("\\s", "");

                temp2 = temp2.replaceAll(",XX", "");

                temp2 = temp2.replace("[", "");
                temp2 = temp2.replace("]", "");

                String[] result3 = temp2.split(",");

                List<String> tmp = new ArrayList<String>(Arrays.asList(result3));

                resultFinal2.addAll(tmp);
            }

            return resultFinal2;
        }

        else if (result[0].equals("3")) {
            resultFinal.remove(0);
            List<String> resultFinal2 = new ArrayList<String>();
            for (String key : resultFinal) {

                boolean flag = true;
                int counter = 0;
                while (flag) {

                    if (counter < key.length() && Character.isDigit(key.charAt(counter))) {

                        counter++;
                    }

                    else {
                        flag = false;
                    }
                }
                String temp2 = (new String(CryptoPrimitives.decryptAES_CTR_String(
                        array[Integer.parseInt((String) key.subSequence(0, counter))], keys[1])))
                                .split("\t\t\t")[0];
                temp2 = temp2.replaceAll("\\s", "");

                temp2 = temp2.replaceAll(",XX", "");
                temp2 = temp2.replace("[", "");
                temp2 = temp2.replace("]", "");

                String[] result3 = temp2.split(",");
                List<String> tmp = new ArrayList<String>(Arrays.asList(result3));
                resultFinal2.addAll(tmp);
            }
            List<String> resultFinal3 = new ArrayList<String>();

            for (String key : resultFinal2) {

                boolean flag = true;
                int counter = 0;
                while (flag) {

                    if (counter < key.length() && Character.isDigit(key.charAt(counter))) {

                        counter++;
                    }

                    else {
                        flag = false;
                    }
                }
                String temp2 = (new String(CryptoPrimitives.decryptAES_CTR_String(
                        array[Integer.parseInt((String) key.subSequence(0, counter))], keys[1])))
                                .split("\t\t\t")[0];
                temp2 = temp2.replaceAll("\\s", "");
                temp2 = temp2.replaceAll(",XX", "");

                temp2 = temp2.replace("[", "");
                temp2 = temp2.replace("]", "");
                String[] result3 = temp2.split(",");

                List<String> tmp = new ArrayList<String>(Arrays.asList(result3));

                resultFinal3.addAll(tmp);
            }

            return resultFinal3;
        }
    }
    return new ArrayList<String>();
}