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

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

Introduction

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

Prototype

Collection<Map.Entry<K, V>> entries();

Source Link

Document

Returns a view collection of all key-value pairs contained in this multimap, as Map.Entry instances.

Usage

From source file:org.opendaylight.protocol.bgp.linkstate.impl.attribute.PrefixAttributesParser.java

/**
 * Parse prefix attributes.//  w w  w.  j  ava2 s . co m
 *
 * @param attributes key is the tlv type and value are the value bytes of the tlv
 * @param protocolId to differentiate parsing methods
 * @return {@link LinkStateAttribute}
 */
static LinkStateAttribute parsePrefixAttributes(final Multimap<Integer, ByteBuf> attributes,
        final ProtocolId protocolId) {
    final PrefixAttributesBuilder builder = new PrefixAttributesBuilder();
    final List<RouteTag> routeTags = new ArrayList<>();
    final List<ExtendedRouteTag> exRouteTags = new ArrayList<>();
    for (final Entry<Integer, ByteBuf> entry : attributes.entries()) {
        final int key = entry.getKey();
        final ByteBuf value = entry.getValue();
        LOG.trace("Prefix attribute TLV {}", key);
        parseAttribute(key, value, protocolId, builder, routeTags, exRouteTags);
    }
    LOG.trace("Finished parsing Prefix Attributes.");
    builder.setRouteTags(routeTags);
    builder.setExtendedTags(exRouteTags);
    return new PrefixAttributesCaseBuilder().setPrefixAttributes(builder.build()).build();
}

From source file:org.ambraproject.wombat.config.site.url.Link.java

private static String appendQueryParameters(Multimap<String, ?> queryParameters, String path) {
    if (!queryParameters.isEmpty()) {
        UrlParamBuilder paramBuilder = UrlParamBuilder.params();
        for (Map.Entry<String, ?> paramEntry : queryParameters.entries()) {
            paramBuilder.add(paramEntry.getKey(), paramEntry.getValue().toString());
        }/*from w ww .  ja  v a2s  . c om*/
        path = path + "?" + paramBuilder.format();
    }
    return path;
}

From source file:com.torodb.torod.db.backends.meta.routines.DeleteDocuments.java

public static int execute(Configuration configuration, CollectionSchema colSchema,
        Multimap<DocStructure, Integer> didsByStructure, boolean justOne,
        @Nonnull DatabaseInterface databaseInterface) throws RetryTransactionException {
    Multimap<DocStructure, Integer> didsByStructureToDelete;
    if (didsByStructure.isEmpty()) {
        return 0;
    }/*from  ww w .  j a  v  a 2  s .  co m*/

    if (justOne) {
        didsByStructureToDelete = MultimapBuilder.hashKeys(1).arrayListValues(1).build();

        Map.Entry<DocStructure, Integer> aEntry = didsByStructure.entries().iterator().next();

        didsByStructureToDelete.put(aEntry.getKey(), aEntry.getValue());
    } else {
        didsByStructureToDelete = didsByStructure;
    }

    try {
        return execute(configuration, colSchema, didsByStructureToDelete, databaseInterface);
    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.android.tools.idea.gradle.editor.parser.GradleEditorModelParserFacade.java

/**
 * Processes given PSI file and fills given context
 * by {@link GradleEditorModelParseContext#getAssignments(Variable) corresponding assignments}.
 *
 * @param context  context to fill/* w  w  w.j ava  2 s  .  co m*/
 * @param psiFile  psi file to parse
 */
private static void fillContext(@NotNull final GradleEditorModelParseContext context,
        @NotNull PsiFile psiFile) {
    psiFile.acceptChildren(new GroovyPsiElementVisitor(new GroovyRecursiveElementVisitor() {
        @Override
        public void visitMethodCallExpression(GrMethodCallExpression methodCallExpression) {
            Pair<String, TextRange> pair = GradleEditorValueExtractor.extractMethodName(methodCallExpression);
            GrClosableBlock[] closureArguments = methodCallExpression.getClosureArguments();
            if (pair == null || closureArguments.length > 1) {
                super.visitMethodCallExpression(methodCallExpression);
                return;
            }
            if (closureArguments.length == 0) {
                if (methodCallExpression.getArgumentList().getAllArguments().length == 0) {
                    // This is a no-args method, so, we just register it for cases like 'mavenCentral()' or 'jcenter()'.
                    context.addCachedValue(NO_ARGS_METHOD_ASSIGNMENT_VALUE, TextRange.create(
                            pair.second.getEndOffset(), methodCallExpression.getTextRange().getEndOffset()));
                    context.registerAssignmentFromCachedData(pair.first, pair.second, methodCallExpression);
                }
                return;
            }

            context.onMethodEnter(pair.getFirst());
            try {
                super.visitClosure(closureArguments[0]);
            } finally {
                context.onMethodExit();
            }
        }

        @Override
        public void visitApplicationStatement(GrApplicationStatement applicationStatement) {
            Pair<String, TextRange> methodName = GradleEditorValueExtractor
                    .extractMethodName(applicationStatement);
            if (methodName == null) {
                return;
            }
            GroovyPsiElement[] allArguments = applicationStatement.getArgumentList().getAllArguments();
            if (allArguments.length == 1) {
                context.resetCaches();
                extractValueOrVariable(allArguments[0], context);
                context.registerAssignmentFromCachedData(methodName.getFirst(), methodName.getSecond(),
                        applicationStatement.getArgumentList());
            }
        }

        @Override
        public void visitAssignmentExpression(GrAssignmentExpression expression) {
            // General idea is to try to extract variable from the given expression and, in case of success, try to extract rvalue and
            // register corresponding assignment with them.
            context.resetCaches();
            extractValueOrVariable(expression.getLValue(), context);
            Multimap<Variable, Location> vars = context.getCachedVariables();
            if (vars.size() != 1) {
                context.resetCaches();
                return;
            }
            Map.Entry<Variable, Location> entry = vars.entries().iterator().next();
            Variable lVariable = entry.getKey();
            Location lVariableLocation = entry.getValue();
            context.resetCaches();

            GrExpression rValue = expression.getRValue();
            if (rValue == null) {
                return;
            }
            extractValueOrVariable(rValue, context);
            if (context.getCachedValues().size() > 1) {
                Value value = new Value("",
                        new Location(context.getCurrentFile(), GradleEditorModelUtil.interestedRange(rValue)));
                context.setCachedValues(Collections.singletonList(value));
            }
            context.registerAssignmentFromCachedData(lVariable, lVariableLocation, rValue);
            context.resetCaches();
        }

        @Override
        public void visitVariable(GrVariable variable) {
            TextRange nameRange = null;
            boolean lookForInitializer = false;
            ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE
                    .findSingle(GroovyLanguage.INSTANCE);
            for (PsiElement e = variable.getFirstChild(); e != null; e = e.getNextSibling()) {
                ASTNode node = e.getNode();
                if (node == null) {
                    continue;
                }
                if (!lookForInitializer) {
                    if (node.getElementType() == GroovyTokenTypes.mIDENT) {
                        nameRange = e.getTextRange();
                    } else if (node.getElementType() == GroovyTokenTypes.mASSIGN) {
                        if (nameRange == null) {
                            return;
                        }
                        lookForInitializer = true;
                    }
                    continue;
                }
                if (node.getElementType() == GroovyTokenTypes.mNLS
                        || node.getElementType() == GroovyTokenTypes.mSEMI) {
                    break;
                }
                if (parserDefinition.getWhitespaceTokens().contains(node.getElementType())) {
                    continue;
                }
                extractValueOrVariable(e, context);
                if (context.getCachedValues().size() > 1) {
                    Value value = new Value("",
                            new Location(context.getCurrentFile(), GradleEditorModelUtil.interestedRange(e)));
                    context.setCachedValues(Collections.singletonList(value));
                }
                if (context.registerAssignmentFromCachedData(variable.getName(), nameRange, e)) {
                    return;
                }
            }
        }
    }));
}

From source file:com.facebook.presto.server.ResourceUtil.java

public static Session createSessionForRequest(HttpServletRequest servletRequest, AccessControl accessControl,
        SessionPropertyManager sessionPropertyManager, QueryId queryId) {
    String catalog = trimEmptyToNull(servletRequest.getHeader(PRESTO_CATALOG));
    String schema = trimEmptyToNull(servletRequest.getHeader(PRESTO_SCHEMA));
    assertRequest((catalog != null) || (schema == null), "Schema is set but catalog is not");

    String user = trimEmptyToNull(servletRequest.getHeader(PRESTO_USER));
    assertRequest(user != null, "User must be set");

    Principal principal = servletRequest.getUserPrincipal();
    try {/*from w  ww . j av  a 2 s .com*/
        accessControl.checkCanSetUser(principal, user);
    } catch (AccessDeniedException e) {
        throw new WebApplicationException(e.getMessage(), Status.FORBIDDEN);
    }

    Identity identity = new Identity(user, Optional.ofNullable(principal));
    SessionBuilder sessionBuilder = Session.builder(sessionPropertyManager).setQueryId(queryId)
            .setIdentity(identity).setSource(servletRequest.getHeader(PRESTO_SOURCE)).setCatalog(catalog)
            .setSchema(schema).setRemoteUserAddress(servletRequest.getRemoteAddr())
            .setUserAgent(servletRequest.getHeader(USER_AGENT));

    String timeZoneId = servletRequest.getHeader(PRESTO_TIME_ZONE);
    if (timeZoneId != null) {
        sessionBuilder.setTimeZoneKey(getTimeZoneKey(timeZoneId));
    }

    String language = servletRequest.getHeader(PRESTO_LANGUAGE);
    if (language != null) {
        sessionBuilder.setLocale(Locale.forLanguageTag(language));
    }

    // parse session properties
    Multimap<String, Entry<String, String>> sessionPropertiesByCatalog = HashMultimap.create();
    for (String sessionHeader : splitSessionHeader(servletRequest.getHeaders(PRESTO_SESSION))) {
        parseSessionHeader(sessionHeader, sessionPropertiesByCatalog, sessionPropertyManager);
    }

    // verify user can set the session properties
    try {
        for (Entry<String, Entry<String, String>> property : sessionPropertiesByCatalog.entries()) {
            String catalogName = property.getKey();
            String propertyName = property.getValue().getKey();
            if (catalogName == null) {
                accessControl.checkCanSetSystemSessionProperty(identity, propertyName);
            } else {
                accessControl.checkCanSetCatalogSessionProperty(identity, catalogName, propertyName);
            }
        }
    } catch (AccessDeniedException e) {
        throw new WebApplicationException(e.getMessage(), Status.BAD_REQUEST);
    }
    sessionBuilder.setSystemProperties(toMap(sessionPropertiesByCatalog.get(null)));
    for (Entry<String, Collection<Entry<String, String>>> entry : sessionPropertiesByCatalog.asMap()
            .entrySet()) {
        if (entry.getKey() != null) {
            sessionBuilder.setCatalogProperties(entry.getKey(), toMap(entry.getValue()));
        }
    }

    return sessionBuilder.build();
}

From source file:ai.grakn.graql.internal.reasoner.utils.ReasonerUtils.java

/**
 * calculates map intersection by doing an intersection on key sets and accumulating the keys
 * @param m1 first operand// w  w w  .  j av  a2 s  .  co  m
 * @param m2 second operand
 * @param <K> map key type
 * @param <V> map value type
 * @return map intersection
 */
public static <K, V> Multimap<K, V> multimapIntersection(Multimap<K, V> m1, Multimap<K, V> m2) {
    Multimap<K, V> intersection = HashMultimap.create();
    Sets.SetView<K> keyIntersection = Sets.intersection(m1.keySet(), m2.keySet());
    Stream.concat(m1.entries().stream(), m2.entries().stream())
            .filter(e -> keyIntersection.contains(e.getKey()))
            .forEach(e -> intersection.put(e.getKey(), e.getValue()));
    return intersection;
}

From source file:com.google.publicalerts.cap.testing.CapTestUtil.java

/**
 * Asserts that the {@code expected} matches {@code actual}, where equality
 * between {@link Reason} objects is guaranteed if two objects have same:
 * <ul>/*w  w w. j  a va 2 s  .c  o m*/
 * <li>reason type,
 * <li>XPath.
 * </ul>
 */
public static void assertReasons(Reasons actual, Reason... expected) {
    Multimap<Reason.Type, String> expectedReasonTypeToXPath = HashMultimap.create();

    for (Reason reason : expected) {
        expectedReasonTypeToXPath.put(reason.getType(), reason.getXPath());
    }

    String msg = "";
    boolean failed = false;

    for (Reason reason : actual) {
        if (!expectedReasonTypeToXPath.remove(reason.getType(), reason.getXPath())) {
            msg += " Unexpected reason: " + reason;
            failed = true;
        }
    }

    for (Entry<Reason.Type, String> expectedEntry : expectedReasonTypeToXPath.entries()) {
        msg += " Expected reason with type: " + expectedEntry.getKey() + " and XPath: "
                + expectedEntry.getValue();
        failed = true;
    }

    Assert.assertFalse(msg, failed);
}

From source file:org.sonatype.restsimple.sitebricks.impl.SitebricksServiceDefinitionGenerator.java

private static Map<String, Collection<String>> mapHeaders(Multimap<String, String> gMap) {
    Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
    for (Map.Entry<String, String> e : gMap.entries()) {
        if (map.get(e.getKey()) != null) {
            map.get(e.getKey()).add(e.getValue());
        } else {/*w w  w.j ava  2  s .c  o  m*/
            ArrayList<String> list = new ArrayList<String>();
            list.add(e.getValue());
            map.put(e.getKey(), list);
        }
    }
    return Collections.unmodifiableMap(map);
}

From source file:org.sonatype.restsimple.sitebricks.impl.SitebricksServiceDefinitionGenerator.java

private static Map<String, Collection<String>> mapFormParams(Multimap<String, String> formParams) {
    Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
    if (formParams != null) {
        for (Map.Entry<String, String> e : formParams.entries()) {
            ArrayList<String> list = new ArrayList<String>();
            list.add(e.getValue());/*from w  w w .  j a v a  2s  .c  o  m*/
            map.put(e.getKey(), list);
        }
    }
    return Collections.unmodifiableMap(map);
}

From source file:org.sonatype.restsimple.sitebricks.impl.SitebricksServiceDefinitionGenerator.java

private static Map<String, Collection<String>> mapMatrixParams(Multimap<String, String> matrixParams) {
    Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
    if (matrixParams != null) {
        for (Map.Entry<String, String> e : matrixParams.entries()) {
            ArrayList<String> list = new ArrayList<String>();
            list.add(e.getValue());//from w ww  .  j  av  a2  s .  c  o  m
            map.put(e.getKey(), list);
        }
    }
    return Collections.unmodifiableMap(map);
}