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

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

Introduction

In this page you can find the example usage for com.google.common.collect SortedSetMultimap 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:org.terasology.documentation.ApiScraper.java

/**
 * @param args (ignored)//from w  w  w.j a  va  2s  .co m
 * @throws Exception if the module environment cannot be loaded
 */
public static void main(String[] args) throws Exception {
    ModuleManager moduleManager = ModuleManagerFactory.create();
    ModuleEnvironment environment = moduleManager.getEnvironment();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    SortedSetMultimap<String, String> sortedApi = Multimaps.newSortedSetMultimap(new HashMap<>(), TreeSet::new);

    for (Class<?> apiClass : environment.getTypesAnnotatedWith(API.class)) {
        //System.out.println("Processing: " + apiClass);
        boolean isPackage = apiClass.isSynthetic();
        URL location;
        String category;
        String apiPackage = "";
        if (isPackage) {
            apiPackage = apiClass.getPackage().getName();
            location = classLoader.getResource(apiPackage.replace('.', '/'));
        } else {

            location = apiClass.getResource('/' + apiClass.getName().replace('.', '/') + ".class");
        }

        if (location == null) {
            System.out.println("Failed to get a class/package location, skipping " + apiClass);
            continue;
        }

        switch (location.getProtocol()) {
        case "jar":

            // Find out what jar it came from and consider that the category
            String categoryFragment = location.getPath();
            //System.out.println("category fragment as path: " + categoryFragment);
            int bang = categoryFragment.lastIndexOf("!");
            int hyphen = categoryFragment.lastIndexOf("-", bang);
            int slash = categoryFragment.lastIndexOf("/", hyphen);
            category = categoryFragment.substring(slash + 1, hyphen);
            //System.out.println("category fragment pared down: " + category);

            if (isPackage) {
                //System.out.println("Jar-based Package: " + apiPackage + ", came from " + location);
                sortedApi.put(category, apiPackage + " (PACKAGE)");
            } else {
                //System.out.println("Jar-based Class: " + apiClass + ", came from " + location);
                sortedApi.put(category,
                        apiClass.getName() + (apiClass.isInterface() ? " (INTERFACE)" : " (CLASS)"));
            }

            break;

        case "file":

            // If file based we know it is local so organize it like that
            category = "terasology engine";

            if (isPackage) {
                //System.out.println("Local Package: " + apiPackage + ", came from " + location);
                sortedApi.put(category, apiPackage + " (PACKAGE)");
            } else {
                //System.out.println("Local Class: " + apiClass + ", came from " + location);
                sortedApi.put(category,
                        apiClass.getName() + (apiClass.isInterface() ? " (INTERFACE)" : " (CLASS)"));
            }

            break;

        default:
            System.out.println("Unknown protocol for: " + apiClass + ", came from " + location);
        }
    }
    sortedApi.putAll("external", ExternalApiWhitelist.CLASSES.stream()
            .map(clazz -> clazz.getName() + " (CLASS)").collect(Collectors.toSet()));
    sortedApi.putAll("external", ExternalApiWhitelist.PACKAGES.stream().map(packagee -> packagee + " (PACKAGE)")
            .collect(Collectors.toSet()));

    System.out.println("# Modding API:\n");
    for (String key : sortedApi.keySet()) {
        System.out.println("## " + key + "\n");
        for (String value : sortedApi.get(key)) {
            System.out.println("* " + value);
        }
        System.out.println("");
    }
}

From source file:org.eclipse.osee.orcs.script.dsl.OsFieldEnum.java

public static SortedSet<? extends OsField> getFieldsFor(Family family) {
    if (FAMILY_TO_FIELDS == null) {
        SortedSetMultimap<Family, OsField> familyToFields = newSetMultimap(FIELD_COMPARATOR);
        for (OsFieldEnum field : OsFieldEnum.values()) {
            familyToFields.put(field.getFamily(), field);
        }//from  w ww. j a va2s .c o m
        OsFieldEnum.FAMILY_TO_FIELDS = familyToFields;
    }
    return FAMILY_TO_FIELDS.get(family);
}

From source file:com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator.java

/**
 * Validates that the passed {@link PipelineOptions} conforms to all the validation criteria from
 * the passed in interface./*  w  ww .j  a  v a 2s  .co m*/
 *
 * <p>Note that the interface requested must conform to the validation criteria specified on
 * {@link PipelineOptions#as(Class)}.
 *
 * @param klass The interface to fetch validation criteria from.
 * @param options The {@link PipelineOptions} to validate.
 * @return The type
 */
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) {
    checkNotNull(klass);
    checkNotNull(options);
    checkArgument(Proxy.isProxyClass(options.getClass()));
    checkArgument(Proxy.getInvocationHandler(options) instanceof ProxyInvocationHandler);

    // Ensure the methods for T are registered on the ProxyInvocationHandler
    T asClassOptions = options.as(klass);

    ProxyInvocationHandler handler = (ProxyInvocationHandler) Proxy.getInvocationHandler(asClassOptions);

    SortedSetMultimap<String, Method> requiredGroups = TreeMultimap.create(Ordering.natural(),
            PipelineOptionsFactory.MethodNameComparator.INSTANCE);
    for (Method method : ReflectHelpers.getClosureOfMethodsOnInterface(klass)) {
        Required requiredAnnotation = method.getAnnotation(Validation.Required.class);
        if (requiredAnnotation != null) {
            if (requiredAnnotation.groups().length > 0) {
                for (String requiredGroup : requiredAnnotation.groups()) {
                    requiredGroups.put(requiredGroup, method);
                }
            } else {
                checkArgument(handler.invoke(asClassOptions, method, null) != null,
                        "Missing required value for [" + method + ", \"" + getDescription(method) + "\"]. ");
            }
        }
    }

    for (String requiredGroup : requiredGroups.keySet()) {
        if (!verifyGroup(handler, asClassOptions, requiredGroups.get(requiredGroup))) {
            throw new IllegalArgumentException("Missing required value for group [" + requiredGroup
                    + "]. At least one of the following properties "
                    + Collections2.transform(requiredGroups.get(requiredGroup), ReflectHelpers.METHOD_FORMATTER)
                    + " required. Run with --help=" + klass.getSimpleName() + " for more information.");
        }
    }

    return asClassOptions;
}

From source file:org.apache.beam.sdk.options.PipelineOptionsValidator.java

/**
 * Validates that the passed {@link PipelineOptions} conforms to all the validation criteria from
 * the passed in interface./*  w w w  . j a v  a2 s .  co m*/
 *
 * <p>Note that the interface requested must conform to the validation criteria specified on
 * {@link PipelineOptions#as(Class)}.
 *
 * @param klass The interface to fetch validation criteria from.
 * @param options The {@link PipelineOptions} to validate.
 * @return The type
 */
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) {
    checkNotNull(klass);
    checkNotNull(options);
    checkArgument(Proxy.isProxyClass(options.getClass()));
    checkArgument(Proxy.getInvocationHandler(options) instanceof ProxyInvocationHandler);

    // Ensure the methods for T are registered on the ProxyInvocationHandler
    T asClassOptions = options.as(klass);

    ProxyInvocationHandler handler = (ProxyInvocationHandler) Proxy.getInvocationHandler(asClassOptions);

    SortedSetMultimap<String, Method> requiredGroups = TreeMultimap.create(Ordering.natural(),
            PipelineOptionsFactory.MethodNameComparator.INSTANCE);
    for (Method method : ReflectHelpers.getClosureOfMethodsOnInterface(klass)) {
        Required requiredAnnotation = method.getAnnotation(Validation.Required.class);
        if (requiredAnnotation != null) {
            if (requiredAnnotation.groups().length > 0) {
                for (String requiredGroup : requiredAnnotation.groups()) {
                    requiredGroups.put(requiredGroup, method);
                }
            } else {
                checkArgument(handler.invoke(asClassOptions, method, null) != null,
                        "Missing required value for [%s, \"%s\"]. ", method, getDescription(method));
            }
        }
    }

    for (String requiredGroup : requiredGroups.keySet()) {
        if (!verifyGroup(handler, asClassOptions, requiredGroups.get(requiredGroup))) {
            throw new IllegalArgumentException("Missing required value for group [" + requiredGroup
                    + "]. At least one of the following properties "
                    + Collections2.transform(requiredGroups.get(requiredGroup), ReflectHelpers.METHOD_FORMATTER)
                    + " required. Run with --help=" + klass.getSimpleName() + " for more information.");
        }
    }

    return asClassOptions;
}

From source file:de.rkl.tools.tzconv.model.ApplicationModel.java

private static SetMultimap<ZoneOffset, ZoneId> sortAvailableZoneIds() {
    final SortedSetMultimap<ZoneOffset, ZoneId> zoneIdMap = TreeMultimap.create(Ordering.natural().reverse(),
            new Ordering<ZoneId>() {
                @Override/*  w  w  w. j a  va2s .  c  o  m*/
                public int compare(final ZoneId zoneId1, final ZoneId zoneId2) {
                    return ComparisonChain.start().compare(zoneId1.toString(), zoneId2.toString()).result();
                }
            }.nullsFirst());
    ZoneId.getAvailableZoneIds().stream().forEach(zoneId -> {
        final ZoneId zoneIdObject = ZoneId.of(zoneId);
        zoneIdMap.put(zoneIdObject.getRules().getStandardOffset(Instant.now()), zoneIdObject);
    });
    return ImmutableSetMultimap.copyOf(zoneIdMap);
}

From source file:org.ambraproject.wombat.model.TaxonomyGraph.java

/**
 * @param categoryPaths a list of all slash-delimited category paths in the taxonomy
 * @return a parsed graph representation of the taxonomy
 *//*from   w w w.  j  ava2  s.c  om*/
public static TaxonomyGraph create(Collection<String> categoryPaths) {
    Set<String> names = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
    SortedSetMultimap<String, String> parentsToChildren = caseInsensitiveSetMultimap();
    SortedSetMultimap<String, String> childrenToParents = caseInsensitiveSetMultimap();
    for (String categoryPath : categoryPaths) {
        List<String> categories = parseTerms(categoryPath);
        for (int i = 0; i < categories.size(); i++) {
            String node = categories.get(i);
            names.add(node);
            if (i > 0) {
                String parent = categories.get(i - 1);
                parentsToChildren.put(parent, node);
                childrenToParents.put(node, parent);
            }
        }
    }

    ImmutableSortedMap.Builder<String, CategoryInfo> categoryMap = ImmutableSortedMap
            .orderedBy(String.CASE_INSENSITIVE_ORDER);
    for (String name : names) {
        categoryMap.put(name, new CategoryInfo(name, childrenToParents.get(name), parentsToChildren.get(name)));
    }

    return new TaxonomyGraph(categoryMap.build());
}

From source file:org.gaul.s3proxy.AwsSignature.java

/**
 * Create Amazon V2 signature.  Reference:
 * http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html
 *///from w w w.  j a  va2  s .  c  o  m
static String createAuthorizationSignature(HttpServletRequest request, String uri, String credential) {
    // sort Amazon headers
    SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create();
    for (String headerName : Collections.list(request.getHeaderNames())) {
        Collection<String> headerValues = Collections.list(request.getHeaders(headerName));
        headerName = headerName.toLowerCase();
        if (!headerName.startsWith("x-amz-")) {
            continue;
        }
        if (headerValues.isEmpty()) {
            canonicalizedHeaders.put(headerName, "");
        }
        for (String headerValue : headerValues) {
            canonicalizedHeaders.put(headerName, Strings.nullToEmpty(headerValue));
        }
    }

    // build string to sign
    StringBuilder builder = new StringBuilder().append(request.getMethod()).append('\n')
            .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_MD5))).append('\n')
            .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_TYPE))).append('\n');
    String expires = request.getParameter("Expires");
    if (expires != null) {
        builder.append(expires);
    } else if (!canonicalizedHeaders.containsKey("x-amz-date")) {
        builder.append(request.getHeader(HttpHeaders.DATE));
    }
    builder.append('\n');
    for (Map.Entry<String, String> entry : canonicalizedHeaders.entries()) {
        builder.append(entry.getKey()).append(':').append(entry.getValue()).append('\n');
    }
    builder.append(uri);

    char separator = '?';
    List<String> subresources = Collections.list(request.getParameterNames());
    Collections.sort(subresources);
    for (String subresource : subresources) {
        if (SIGNED_SUBRESOURCES.contains(subresource)) {
            builder.append(separator).append(subresource);

            String value = request.getParameter(subresource);
            if (!"".equals(value)) {
                builder.append('=').append(value);
            }
            separator = '&';
        }
    }

    String stringToSign = builder.toString();
    logger.trace("stringToSign: {}", stringToSign);

    // sign string
    Mac mac;
    try {
        mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1"));
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    return BaseEncoding.base64().encode(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)));
}

From source file:org.jclouds.glacier.util.AWSRequestSignerV4.java

private static Multimap<String, String> buildCanonicalizedHeadersMap(HttpRequest request) {
    Multimap<String, String> headers = request.getHeaders();
    SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create();
    for (Entry<String, String> header : headers.entries()) {
        if (header.getKey() == null)
            continue;
        String key = header.getKey().toString().toLowerCase(Locale.getDefault());
        // Ignore any headers that are not particularly interesting.
        if (key.equalsIgnoreCase(HttpHeaders.CONTENT_TYPE) || key.equalsIgnoreCase(HttpHeaders.CONTENT_MD5)
                || key.equalsIgnoreCase(HttpHeaders.HOST) || key.startsWith(HEADER_TAG)) {
            canonicalizedHeaders.put(key, header.getValue());
        }/*  w w  w. j  a v a 2 s .c om*/
    }
    return canonicalizedHeaders;
}

From source file:de.anycook.recommendation.Recommendation.java

public static List<Recipe> recommend(int userId) throws SQLException {
    try (DBRecommend dbrecommend = new DBRecommend()) {
        Map<String, Integer> tasteTags = dbrecommend.getTastyTags(userId);
        Map<String, Collection<String>> recipes = dbrecommend.getRecipesByTags(userId);
        //logger.debug("tagRecipes: "+tagRecipes);

        // cos(a,b) = a*b/|a|*|b|
        SortedSetMultimap<Double, String> recommendMap = TreeMultimap.create(new InvertedComparator<Double>(),
                new StandardComparator<String>());
        double schmecktAmount = 0;
        for (String tag : tasteTags.keySet())
            schmecktAmount += Math.pow(tasteTags.get(tag), 2);
        schmecktAmount = Math.sqrt(schmecktAmount);

        for (String tagRecipe : recipes.keySet()) {
            double enumerator = 0;
            Collection<String> tags = recipes.get(tagRecipe);
            for (String tag : tags) {
                if (!tasteTags.containsKey(tag))
                    continue;
                enumerator += tasteTags.get(tag);
            }/*from   w  w w  .j a va  2  s  . co m*/

            double denominator = schmecktAmount * Math.sqrt(tags.size());
            double result = enumerator / denominator;
            recommendMap.put(result, tagRecipe);
        }

        List<Recipe> finalRecipes = new ArrayList<>();
        for (String name : recommendMap.values()) {
            try {
                finalRecipes.add(Recipe.init(name));
            } catch (DBRecipe.RecipeNotFoundException e) {
                //will never happen
            }
        }

        return finalRecipes;
    }
}

From source file:uk.ac.ebi.spot.rdf.model.baseline.ExperimentalFactorsBuilder.java

SortedSetMultimap<String, Factor> buildFactorsByType() {

    SortedSetMultimap<String, Factor> factorsByType = TreeMultimap.create();

    for (FactorGroup factorGroup : orderedFactorGroups) {

        for (Factor factor : factorGroup) {

            factorsByType.put(factor.getType(), factor);

        }//w w w.  j a  v a 2 s  .  co m
    }
    return factorsByType;
}