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:com.redprairie.moca.components.mocatest.ClusterTestComponent.java

/**
 * Gets a result set of node|roles which is each
 * node URL to a comma separated list of roles
 * @return/*from ww  w. j a v a  2  s. c o m*/
 */
public static MocaResults getNodesToRoles() {
    SimpleResults res = new SimpleResults();
    res.addColumn("node", MocaType.STRING);
    res.addColumn("roles", MocaType.STRING);

    ClusterRoleManager manager = ServerUtils.globalAttribute(ClusterRoleManager.class);
    MocaClusterAdministration admin = (MocaClusterAdministration) ServerUtils.globalContext()
            .getAttribute(MocaClusterAdministration.class.getName());
    if (manager != null && admin != null) {
        Multimap<Node, RoleDefinition> multiMap = manager.getClusterRoles();
        Map<Node, InstanceUrl> urls = admin.getKnownNodes();
        _logger.info("Cluster URLs: " + urls.entrySet());
        _logger.info("Node to Roles: " + multiMap.asMap().entrySet());

        Multimap<InstanceUrl, RoleDefinition> urlRoleMap = HashMultimap.create();

        for (Entry<Node, Collection<RoleDefinition>> entry : multiMap.asMap().entrySet()) {
            InstanceUrl url = urls.get(entry.getKey());
            // TODO: trying to handle that cluster URLs is wrong and doesn't contain the entry
            if (url == null) {
                url = new InstanceUrl(false, entry.getKey().toString(), 0);
            }
            urlRoleMap.putAll(url, entry.getValue());
        }

        for (Entry<Node, InstanceUrl> url : urls.entrySet()) {
            if (!urlRoleMap.containsKey(url.getValue())) {
                urlRoleMap.put(url.getValue(), EMPTY_ROLE);
            }
        }

        // Sort by the node url
        Map<InstanceUrl, Collection<RoleDefinition>> sortedMap = new TreeMap<InstanceUrl, Collection<RoleDefinition>>(
                new Comparator<InstanceUrl>() {

                    @Override
                    public int compare(InstanceUrl o1, InstanceUrl o2) {
                        return o1.toString().compareTo(o2.toString());
                    }
                });

        sortedMap.putAll(urlRoleMap.asMap());
        for (Map.Entry<InstanceUrl, Collection<RoleDefinition>> entry : sortedMap.entrySet()) {
            res.addRow();
            res.setStringValue("node", entry.getKey().toString());
            res.setStringValue("roles", Joiner.on(',').join(entry.getValue()));
        }
    } else {
        _logger.info("Cluster manager and/or admin not set");
    }

    return res;
}

From source file:org.eclipse.packagedrone.repo.importer.aether.web.AetherResolver.java

private static void markExisting(final AetherResult result, final ReadableChannel channel) {
    // build version map

    final Multimap<String, String> existing = HashMultimap.create();

    for (final ArtifactInformation ai : channel.getArtifacts()) {
        final String groupId = ai.getMetaData().get(KEY_GROUP_ID);
        final String artifactId = ai.getMetaData().get(KEY_ARTIFACT_ID);
        final String classifier = ai.getMetaData().get(KEY_CLASSIFIER);
        final String extension = ai.getMetaData().get(KEY_EXTENSION);

        final String version = ai.getMetaData().get(KEY_VERSION);

        if (groupId != null && artifactId != null && version != null) {
            final String key = makeExistingKey(groupId, artifactId, classifier, extension);
            existing.put(key, version);
        }//from   www  . j  av a  2 s.c  o  m
    }

    // match

    for (final AetherResult.Entry entry : result.getArtifacts()) {
        final String key = makeExistingKey(entry.getCoordinates().getGroupId(),
                entry.getCoordinates().getArtifactId(), entry.getCoordinates().getClassifier(),
                entry.getCoordinates().getExtension());
        entry.getExistingVersions().addAll(existing.get(key));
    }
}

From source file:org.jetbrains.kotlin.types.SubstitutionUtils.java

private static void fillInDeepSubstitutor(@NotNull KotlinType context, @NotNull TypeSubstitutor substitutor,
        @NotNull Map<TypeConstructor, TypeProjection> substitution,
        @Nullable Multimap<TypeConstructor, TypeProjection> fullSubstitution) {
    List<TypeParameterDescriptor> parameters = context.getConstructor().getParameters();
    List<TypeProjection> arguments = context.getArguments();

    if (parameters.size() != arguments.size()) {
        throw new IllegalStateException();
    }//from w ww.j a v  a  2 s . c  om

    for (int i = 0; i < arguments.size(); i++) {
        TypeProjection argument = arguments.get(i);
        TypeParameterDescriptor parameter = parameters.get(i);

        TypeProjection substitute = substitutor.substitute(argument);
        assert substitute != null;
        substitution.put(parameter.getTypeConstructor(), substitute);
        if (fullSubstitution != null) {
            fullSubstitution.put(parameter.getTypeConstructor(), substitute);
        }
    }
    if (KotlinBuiltIns.isNothingOrNullableNothing(context))
        return;
    for (KotlinType supertype : context.getConstructor().getSupertypes()) {
        fillInDeepSubstitutor(supertype, substitutor, substitution, fullSubstitution);
    }
}

From source file:org.jfrog.build.util.PublishedItemsHelper.java

/**
 * Building a multi map of target paths mapped to their files.
 *
 * @param checkoutDir the base directory of which to calculate the given source ant pattern
 * @param pattern     the Ant pattern to calculate the files from
 * @param targetPath  the target path for deployment of a file
 * @return a Multimap containing the targets as keys and the files as values
 * @throws IOException in case of any file system exception
 */// w ww  .  j  a  va 2 s .c  o  m
public static Multimap<String, File> buildPublishingData(File checkoutDir, String pattern, String targetPath)
        throws IOException {
    final Multimap<String, File> filePathsMap = HashMultimap.create();
    File patternAbsolutePath = getAbsolutePath(checkoutDir, pattern);
    if (patternAbsolutePath.isFile()) {
        // The given pattern is an absolute path of just one file, let's add it to our result map
        filePathsMap.put(targetPath, patternAbsolutePath);
    } else {
        Pattern filePattern = null;
        File patternDir = null;
        if (patternAbsolutePath.isDirectory()) {
            // The given pattern is a path to a directory, we need to return all it's content
            filePattern = Pattern.compile(".*");
            patternDir = patternAbsolutePath;
        } else if (pattern.indexOf('*') >= 0 || pattern.indexOf('?') >= 0) {
            // We are dealing with complex Ant pattern, need to analyze it
            File baseTruncationDir = getBaseTruncationDir(patternAbsolutePath);
            patternDir = baseTruncationDir != null ? baseTruncationDir : checkoutDir;

            // If the checkout dir is an ancestor of the pattern path then
            // we cut the checkout dir from the pattern
            boolean isCheckoutDirAncestor = isAncestor(checkoutDir, patternAbsolutePath);
            if (isCheckoutDirAncestor) {
                pattern = pattern.substring(
                        patternDir.getAbsolutePath().length() - checkoutDir.getAbsolutePath().length());
            }

            // If the pattern absolute path starts with the pattern directory path
            // then we need to cut the pattern to be only the relative path
            String patternAbsolutePathUrl = patternAbsolutePath.getAbsolutePath();
            if (!StringUtils.isBlank(patternAbsolutePathUrl)
                    && patternAbsolutePathUrl.startsWith(patternDir.getAbsolutePath())) {
                pattern = getRelativePath(patternDir, patternAbsolutePath);
            }

            // All done, we can now convert and compile from Ant pattern to regular expression
            filePattern = Pattern.compile(convertAntToRegexp(pattern));
        }

        // If we successfully converted from Ant pattern to a regular expression
        // then it's time to collect all our artifacts according to this regular expression
        if (filePattern != null) {
            List<File> files = new ArrayList<File>();
            collectMatchedFiles(patternDir, patternDir, filePattern, files);
            for (File file : files) {
                String fileTargetPath = calculateFileTargetPath(patternDir, file, targetPath);
                filePathsMap.put(fileTargetPath, file);
            }
        }
    }

    return filePathsMap;
}

From source file:org.opentripplanner.routing.edgetype.TripPattern.java

/**
 * Static method that creates unique human-readable names for a collection of TableTripPatterns.
 * Perhaps this should be in TripPattern, and apply to Frequency patterns as well. TODO: resolve
 * this question: can a frequency and table pattern have the same stoppattern? If so should they
 * have the same "unique" name?//from ww w . j av  a 2  s. co m
 * 
 * The names should be dataset unique, not just route-unique?
 * 
 * A TripPattern groups all trips visiting a particular pattern of stops on a particular route.
 * GFTS Route names are intended for very general customer information, but sometimes there is a
 * need to know where a particular trip actually goes. For example, the New York City N train
 * has at least four different variants: express (over the Manhattan bridge) and local (via
 * lower Manhattan and the tunnel), in two directions (to Astoria or to Coney Island). During
 * construction, a fifth variant sometimes appears: trains use the D line to Coney Island after
 * 59th St (or from Coney Island to 59th in the opposite direction).
 * 
 * TripPattern names are machine-generated on a best-effort basis. They are guaranteed to be
 * unique (among TripPatterns for a single Route) but not stable across graph builds, especially
 * when different versions of GTFS inputs are used. For instance, if a variant is the only
 * variant of the N that ends at Coney Island, the name will be "N to Coney Island". But if
 * multiple variants end at Coney Island (but have different stops elsewhere), that name would
 * not be chosen. OTP also tries start and intermediate stations ("from Coney Island", or "via
 * Whitehall", or even combinations ("from Coney Island via Whitehall"). But if there is no way
 * to create a unique name from start/end/intermediate stops, then the best we can do is to
 * create a "like [trip id]" name, which at least tells you where in the GTFS you can find a
 * related trip.
 */
// TODO: pass in a transit index that contains a Multimap<Route, TripPattern> and derive all TableTripPatterns
// TODO: use headsigns before attempting to machine-generate names
// TODO: combine from/to and via in a single name. this could be accomplished by grouping the trips by destination,
// then disambiguating in groups of size greater than 1.
/*
 * Another possible approach: for each route, determine the necessity of each field (which
 * combination will create unique names). from, to, via, express. Then concatenate all necessary
 * fields. Express should really be determined from number of stops and/or run time of trips.
 */
public static void generateUniqueNames(Collection<TripPattern> tableTripPatterns) {
    LOG.info("Generating unique names for stop patterns on each route.");
    Set<String> usedRouteNames = Sets.newHashSet();
    Map<Route, String> uniqueRouteNames = Maps.newHashMap();

    /* Group TripPatterns by Route */
    Multimap<Route, TripPattern> patternsByRoute = ArrayListMultimap.create();
    for (TripPattern ttp : tableTripPatterns) {
        patternsByRoute.put(ttp.route, ttp);
    }

    /* Ensure we have a unique name for every Route */
    for (Route route : patternsByRoute.keySet()) {
        String routeName = GtfsLibrary.getRouteName(route);
        if (usedRouteNames.contains(routeName)) {
            int i = 2;
            String generatedRouteName;
            do
                generatedRouteName = routeName + " " + (i++);
            while (usedRouteNames.contains(generatedRouteName));
            LOG.warn("Route had non-unique name. Generated one to ensure uniqueness of TripPattern names: {}",
                    generatedRouteName);
            routeName = generatedRouteName;
        }
        usedRouteNames.add(routeName);
        uniqueRouteNames.put(route, routeName);
    }

    /* Iterate over all routes, giving the patterns within each route unique names. */
    ROUTE: for (Route route : patternsByRoute.keySet()) {
        Collection<TripPattern> routeTripPatterns = patternsByRoute.get(route);
        String routeName = uniqueRouteNames.get(route);

        /* Simplest case: there's only one route variant, so we'll just give it the route's name. */
        if (routeTripPatterns.size() == 1) {
            routeTripPatterns.iterator().next().name = routeName;
            continue;
        }

        /* Do the patterns within this Route have a unique start, end, or via Stop? */
        Multimap<String, TripPattern> signs = ArrayListMultimap.create(); // prefer headsigns
        Multimap<Stop, TripPattern> starts = ArrayListMultimap.create();
        Multimap<Stop, TripPattern> ends = ArrayListMultimap.create();
        Multimap<Stop, TripPattern> vias = ArrayListMultimap.create();
        for (TripPattern pattern : routeTripPatterns) {
            List<Stop> stops = pattern.getStops();
            Stop start = stops.get(0);
            Stop end = stops.get(stops.size() - 1);
            starts.put(start, pattern);
            ends.put(end, pattern);
            for (Stop stop : stops)
                vias.put(stop, pattern);
        }
        PATTERN: for (TripPattern pattern : routeTripPatterns) {
            List<Stop> stops = pattern.getStops();
            StringBuilder sb = new StringBuilder(routeName);

            /* First try to name with destination. */
            Stop end = stops.get(stops.size() - 1);
            sb.append(" to " + stopNameAndId(end));
            if (ends.get(end).size() == 1) {
                pattern.name = sb.toString();
                continue PATTERN; // only pattern with this last stop
            }

            /* Then try to name with origin. */
            Stop start = stops.get(0);
            sb.append(" from " + stopNameAndId(start));
            if (starts.get(start).size() == 1) {
                pattern.name = (sb.toString());
                continue PATTERN; // only pattern with this first stop
            }

            /* Check whether (end, start) is unique. */
            Set<TripPattern> remainingPatterns = Sets.newHashSet();
            remainingPatterns.addAll(starts.get(start));
            remainingPatterns.retainAll(ends.get(end)); // set intersection
            if (remainingPatterns.size() == 1) {
                pattern.name = (sb.toString());
                continue PATTERN;
            }

            /* Still not unique; try (end, start, via) for each via. */
            for (Stop via : stops) {
                if (via.equals(start) || via.equals(end))
                    continue;
                Set<TripPattern> intersection = Sets.newHashSet();
                intersection.addAll(remainingPatterns);
                intersection.retainAll(vias.get(via));
                if (intersection.size() == 1) {
                    sb.append(" via " + stopNameAndId(via));
                    pattern.name = (sb.toString());
                    continue PATTERN;
                }
            }

            /* Still not unique; check for express. */
            if (remainingPatterns.size() == 2) {
                // There are exactly two patterns sharing this start/end.
                // The current one must be a subset of the other, because it has no unique via. 
                // Therefore we call it the express.
                sb.append(" express");
            } else {
                // The final fallback: reference a specific trip ID.
                sb.append(" like trip " + pattern.getTrips().get(0).getId());
            }
            pattern.name = (sb.toString());
        } // END foreach PATTERN
    } // END foreach ROUTE

    if (LOG.isDebugEnabled()) {
        LOG.debug("Done generating unique names for stop patterns on each route.");
        for (Route route : patternsByRoute.keySet()) {
            Collection<TripPattern> routeTripPatterns = patternsByRoute.get(route);
            LOG.debug("Named {} patterns in route {}", routeTripPatterns.size(), uniqueRouteNames.get(route));
            for (TripPattern pattern : routeTripPatterns) {
                LOG.debug("    {} ({} stops)", pattern.name, pattern.stopPattern.size);
            }
        }
    }

}

From source file:org.glowroot.local.ui.ClasspathCache.java

private static void loadClassNamesFromDirectory(File dir, String prefix, File location,
        Multimap<String, File> newClassNameLocations) throws MalformedURLException {
    File[] files = dir.listFiles();
    if (files == null) {
        return;/*www . j  a v  a  2s  . c o  m*/
    }
    for (File file : files) {
        String name = file.getName();
        if (file.isFile() && name.endsWith(".class")) {
            String className = prefix + name.substring(0, name.lastIndexOf('.'));
            newClassNameLocations.put(className, location);
        } else if (file.isDirectory()) {
            loadClassNamesFromDirectory(file, prefix + name + ".", location, newClassNameLocations);
        }
    }
}

From source file:com.outerspacecat.util.Utils.java

/**
 * Parses the provided HTTP query string using the specified encoding.
 * /*from  ww  w  . jav  a  2  s.c  om*/
 * @param query the query string to parse. Must be non {@code null}.
 * @param enc the encoding to use. Must be non {@code null}.
 * @return parsed parameters. Never {@code null}.
 */
public static Multimap<String, String> parseHttpQueryString(final String query, final Charset enc) {
    Preconditions.checkNotNull(query, "query required");
    Preconditions.checkNotNull(enc, "enc required");

    Multimap<String, String> ret = LinkedHashMultimap.create();

    try {
        for (String entry : query.split("&")) {
            String[] kv = entry.split("=");
            String key = URLDecoder.decode(kv[0], enc.name());
            String value = "";
            if (kv.length > 1)
                value = URLDecoder.decode(kv[1], enc.name());
            ret.put(key, value);
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    return ret;
}

From source file:com.opengamma.strata.collect.io.PropertiesFile.java

private static PropertySet parse(ImmutableList<String> lines) {
    Multimap<String, String> parsed = ArrayListMultimap.create();
    int lineNum = 0;
    for (String line : lines) {
        lineNum++;//  www.j a  v  a2 s.  c  om
        line = line.trim();
        if (line.length() == 0 || line.startsWith("#") || line.startsWith(";")) {
            continue;
        }
        int equalsPosition = line.indexOf('=');
        String key = (equalsPosition < 0 ? line.trim() : line.substring(0, equalsPosition).trim());
        String value = (equalsPosition < 0 ? "" : line.substring(equalsPosition + 1).trim());
        if (key.length() == 0) {
            throw new IllegalArgumentException("Invalid properties file, empty key, line " + lineNum);
        }
        parsed.put(key, value);
    }
    return PropertySet.of(parsed);
}

From source file:org.eclipse.ocl.examples.codegen.cse.HashedAnalyses.java

public static @Nullable HashedAnalyses intersection(@NonNull HashedAnalyses iHash2Analyses,
        @NonNull HashedAnalyses jHash2Analyses) {
    Multimap<Integer, AbstractAnalysis> intersection = null;
    for (int hash : iHash2Analyses.map.keySet()) {
        Collection<AbstractAnalysis> jAnalyses = jHash2Analyses.map.get(hash);
        if (jAnalyses != null) {
            for (@SuppressWarnings("null")
            @NonNull//from   w  w w. ja  v a  2  s .  c  om
            AbstractAnalysis iAnalysis : iHash2Analyses.map.get(hash)) {
                for (@NonNull
                AbstractAnalysis jAnalysis : jAnalyses) {
                    if (iAnalysis.isStructurallyEqualTo(jAnalysis)) {
                        if (intersection == null) {
                            intersection = HashMultimap.create();
                        }
                        intersection.put(hash, iAnalysis);
                        intersection.put(hash, jAnalysis);
                    }
                }
            }
        }
    }
    return intersection != null ? new HashedAnalyses(intersection) : null;
}

From source file:org.jboss.errai.ioc.rebind.ioc.bootstrapper.AbstractBodyGenerator.java

protected static Multimap<DependencyType, Dependency> separateByType(
        final Collection<Dependency> dependencies) {
    final Multimap<DependencyType, Dependency> separated = HashMultimap.create();

    for (final Dependency dep : dependencies) {
        separated.put(dep.getDependencyType(), dep);
    }// w  w w .ja  v a2s  .c o  m

    return separated;
}