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

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

Introduction

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

Prototype

boolean containsKey(@Nullable Object key);

Source Link

Document

Returns true if this multimap contains at least one key-value pair with the key key .

Usage

From source file:org.jclouds.rackspace.cloudidentity.v1_1.handlers.RetryOnRenew.java

@Override
public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {
    boolean retry = false; // default
    try {/* w  w w.ja v a  2  s .  c  o  m*/
        switch (response.getStatusCode()) {
        case 401:
            // Do not retry on 401 from authentication request
            Multimap<String, String> headers = command.getCurrentRequest().getHeaders();
            if (headers != null && headers.containsKey(AUTH_USER) && headers.containsKey(AUTH_KEY)
                    && !headers.containsKey(AUTH_TOKEN)) {
                retry = false;
            } else {
                closeClientButKeepContentStream(response);
                // This is not an authentication request returning 401
                // Check if we already had seen this request
                Integer count = retryCountMap.getIfPresent(command);

                if (count == null) {
                    // First time this non-authentication request failed
                    logger.debug("invalidating authentication token - first time for %s", command);
                    retryCountMap.put(command, 1);
                    authenticationResponseCache.invalidateAll();
                    retry = true;
                } else {
                    // This request has failed before
                    if (count + 1 >= NUM_RETRIES) {
                        logger.debug("too many 401s - giving up after: %s for %s", count, command);
                        retry = false;
                    } else {
                        // Retry just in case
                        logger.debug("invalidating authentication token - retry %s for %s", count, command);
                        retryCountMap.put(command, count + 1);
                        // Wait between retries
                        authenticationResponseCache.invalidateAll();
                        Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);
                        retry = true;
                    }
                }
            }
            break;
        case 408:
            return backoffHandler.shouldRetryRequest(command, response);
        }
        return retry;

    } finally {
        releasePayload(response);
    }
}

From source file:org.sonar.batch.issue.tracking.IssueTrackingResult.java

Collection<ServerIssue> unmatchedForRuleAndForLineAndForChecksum(RuleKey ruleKey, @Nullable Integer line,
        @Nullable String checksum) {
    if (!unmatchedByRuleAndLineAndChecksum.containsKey(ruleKey)) {
        return Collections.emptyList();
    }/* w ww . j  a  va 2  s . c  om*/
    Map<Integer, Multimap<String, ServerIssue>> unmatchedForRule = unmatchedByRuleAndLineAndChecksum
            .get(ruleKey);
    Integer lineNotNull = line != null ? line : 0;
    if (!unmatchedForRule.containsKey(lineNotNull)) {
        return Collections.emptyList();
    }
    Multimap<String, ServerIssue> unmatchedForRuleAndLine = unmatchedForRule.get(lineNotNull);
    String checksumNotNull = StringUtils.defaultString(checksum, "");
    if (!unmatchedForRuleAndLine.containsKey(checksumNotNull)) {
        return Collections.emptyList();
    }
    return unmatchedForRuleAndLine.get(checksumNotNull);
}

From source file:it.sayservice.platform.smartplanner.otp.schedule.sorter.BucketSet.java

private Bucket findBestBucket(Bucket nb, Multimap<String, Bucket> newMap, Multimap<String, Bucket> oldMap,
        int lastIndex) {
    if (oldMap.containsKey(nb.getId()) && newMap.get(nb.getId()).size() == oldMap.get(nb.getId()).size()) {
        for (Bucket ob : oldMap.get(nb.getId())) {
            if (ob.getDup() == nb.getDup()) {
                return ob;
            }//from   w  ww  .  j av  a 2  s .com
        }
    }
    List<Bucket> sameId = new ArrayList<Bucket>();
    for (Bucket ob : buckets) {
        if (ob.getId().equals(nb.getId())) {
            sameId.add(ob);
        }
    }
    Bucket best = null;
    int bestValue = Integer.MAX_VALUE;

    for (Bucket ob : sameId) {
        if (nb.getOrder() == null) {
            continue;
        }
        int d = Math.abs(buckets.indexOf(ob) - lastIndex);
        if (d < bestValue) {
            bestValue = d;
            best = ob;
        }
    }

    return best;

}

From source file:org.jclouds.aws.ec2.filters.FormSigner.java

@VisibleForTesting
void validateParams(Multimap<String, String> params) {
    for (String parameter : mandatoryParametersForSignature) {
        checkState(params.containsKey(parameter), "parameter " + parameter + " is required for signature");
    }/*from ww w  .ja va2 s.  c o m*/
}

From source file:foo.domaintest.http.HttpApiModule.java

@Provides
@Singleton//  www  . j  a  v a  2s.com
Multimap<String, String> provideParameterMap(@RequestData("queryString") String queryString,
        @RequestData("postBody") Lazy<String> lazyPostBody, @RequestData("charset") String requestCharset,
        FileItemIterator multipartIterator) {
    // Calling request.getParameter() or request.getParameterMap() etc. consumes the POST body. If
    // we got the "postpayload" param we don't want to parse the body, so use only the query params.
    // Note that specifying both "payload" and "postpayload" will result in the "payload" param
    // being honored and the POST body being completely ignored.
    ImmutableMultimap.Builder<String, String> params = new ImmutableMultimap.Builder<>();
    Multimap<String, String> getParams = parseQuery(queryString);
    params.putAll(getParams);
    if (getParams.containsKey("postpayload")) {
        // Treat the POST body as if it was the "payload" param.
        return params.put("payload", nullToEmpty(lazyPostBody.get())).build();
    }
    // No "postpayload" so it's safe to consume the POST body and look for params there.
    if (multipartIterator == null) { // Handle GETs and form-urlencoded POST requests.
        params.putAll(parseQuery(nullToEmpty(lazyPostBody.get())));
    } else { // Handle multipart/form-data requests.
        try {
            while (multipartIterator != null && multipartIterator.hasNext()) {
                FileItemStream item = multipartIterator.next();
                try (InputStream stream = item.openStream()) {
                    params.put(item.isFormField() ? item.getFieldName() : item.getName(),
                            CharStreams.toString(new InputStreamReader(stream, requestCharset)));
                }
            }
        } catch (FileUploadException | IOException e) {
            // Ignore the failure and fall through to return whatever params we managed to parse.
        }
    }
    return params.build();
}

From source file:fr.letroll.ttorrentandroid.common.protocol.http.HTTPAnnounceRequestMessage.java

@Nonnull
public static HTTPAnnounceRequestMessage fromParams(@Nonnull Multimap<String, String> params)
        throws MessageValidationException {

    byte[] infoHash = toBytes(params, "info_hash", ErrorMessage.FailureReason.MISSING_HASH);
    byte[] peerId = toBytes(params, "peer_id", ErrorMessage.FailureReason.MISSING_PEER_ID);

    // Default 'uploaded' and 'downloaded' to 0 if the client does
    // not provide it (although it should, according to the spec).
    long uploaded = toLong(params, "uploaded", 0, null);
    long downloaded = toLong(params, "downloaded", 0, null);
    // Default 'left' to -1 to avoid peers entering the COMPLETED
    // state when they don't provide the 'left' parameter.
    long left = toLong(params, "left", -1, null);

    boolean compact = toBoolean(params, "compact");
    boolean noPeerId = toBoolean(params, "no_peer_id");

    int numWant = toInt(params, "numwant", AnnounceRequestMessage.DEFAULT_NUM_WANT, null);

    AnnounceEvent event = AnnounceEvent.NONE;
    if (params.containsKey("event"))
        event = AnnounceEvent.getByName(toString(params, "event", null));

    List<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>();
    int port = toInt(params, "port", -1, ErrorMessage.FailureReason.MISSING_PORT);

    MAIN: {//from w ww .j  a v a 2 s .co m
        String ip = toString(params, "ip", null);
        if (ip != null)
            addresses.add(new InetSocketAddress(InetAddresses.forString(ip), port));
    }

    IP4: {
        Collection<String> ips = params.get("ipv4");
        if (ips != null)
            for (String ip : ips)
                addresses.add(toInetSocketAddress(ip, port));
    }

    IP6: {
        Collection<String> ips = params.get("ipv6");
        if (ips != null)
            for (String ip : ips)
                addresses.add(toInetSocketAddress(ip, port));
    }

    DEFAULT: {
        if (addresses.isEmpty())
            addresses.add(new InetSocketAddress(port));
    }

    return new HTTPAnnounceRequestMessage(infoHash, peerId, addresses, uploaded, downloaded, left, compact,
            noPeerId, event, numWant);
}

From source file:org.jclouds.aws.filters.FormSignerV4.java

@Override
public HttpRequest filter(HttpRequest request) throws HttpException {
    checkArgument(request.getHeaders().containsKey(HOST), "request is not ready to sign; host not present");
    String host = request.getFirstHeaderOrNull(HOST);
    String form = request.getPayload().getRawContent().toString();
    Multimap<String, String> decodedParams = queryParser().apply(form);
    checkArgument(decodedParams.containsKey(ACTION), "request is not ready to sign; Action not present %s",
            form);/*from   w  w w  .j a v a  2s  .  co  m*/

    String timestamp = iso8601Timestamp.get();
    String datestamp = timestamp.substring(0, 8);

    String service = serviceAndRegion.service();
    String region = serviceAndRegion.region(host);
    String credentialScope = Joiner.on('/').join(datestamp, region, service, "aws4_request");

    // content-type is not a required signing param. However, examples use this, so we include it to ease testing.
    ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableMap.<String, String>builder() //
            .put("content-type", request.getPayload().getContentMetadata().getContentType()) //
            .put("host", host) //
            .put("x-amz-date", timestamp);

    HttpRequest.Builder<?> requestBuilder = request.toBuilder() //
            .removeHeader(AUTHORIZATION) //
            .replaceHeader("X-Amz-Date", timestamp);

    if (!decodedParams.containsKey(VERSION)) {
        requestBuilder.addFormParam(VERSION, apiVersion);
    }

    Credentials credentials = creds.get();

    if (credentials instanceof SessionCredentials) {
        String token = SessionCredentials.class.cast(credentials).getSessionToken();
        requestBuilder.replaceHeader("X-Amz-Security-Token", token);
        signedHeadersBuilder.put("x-amz-security-token", token);
    }

    ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build();

    String stringToSign = createStringToSign(requestBuilder.build(), signedHeaders, credentialScope);
    byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service);
    String signature = base16().lowerCase().encode(hmacSHA256(stringToSign, signatureKey));

    StringBuilder authorization = new StringBuilder("AWS4-HMAC-SHA256 ");
    authorization.append("Credential=").append(credentials.identity).append('/').append(credentialScope)
            .append(", ");
    authorization.append("SignedHeaders=").append(Joiner.on(';').join(signedHeaders.keySet())).append(", ");
    authorization.append("Signature=").append(signature);

    return requestBuilder.addHeader(AUTHORIZATION, authorization.toString()).build();
}

From source file:org.summer.dsl.xbase.typesystem.override.ParameterizedResolvedFeatures.java

protected void computeAllFeatures(List<JvmFeature> unfiltered,
        Multimap<String, AbstractResolvedOperation> processedOperations, List<JvmFeature> result) {
    for (JvmFeature feature : unfiltered) {
        if (feature instanceof JvmOperation) {
            String simpleName = feature.getSimpleName();
            if (processedOperations.containsKey(simpleName)) {
                if (parent.isOverridden((JvmOperation) feature, processedOperations.get(simpleName))) {
                    continue;
                }/*from w  ww.j a va 2s  . co  m*/
            }
            BottomResolvedOperation resolvedOperation = parent.createResolvedOperation((JvmOperation) feature,
                    type);
            processedOperations.put(simpleName, resolvedOperation);
            result.add(feature);
        } else {
            result.add(feature);
        }
    }
}

From source file:org.codice.ddf.transformer.xml.streaming.lib.SaxEventToXmlElementConverter.java

private boolean checkNamespaceAdded(String uri, Map<String, String> scopedNamespaces) {
    Multimap<String, String> peek = scopeOfNamespacesAdded.peek();
    return peek != null && peek.containsKey(uri) && peek.get(uri).contains(scopedNamespaces.get(uri));
}

From source file:org.sosy_lab.cpachecker.cpa.constraints.refiner.precision.ConstraintBasedConstraintsPrecision.java

private boolean constraintWithSameMeaningExists(final String pFunctionName, final Constraint pConstraint,
        final Multimap<String, Constraint> pTrackedConstraints) {

    if (pTrackedConstraints.containsKey(pFunctionName)) {
        final Collection<Constraint> constraintsOnLocation = pTrackedConstraints.get(pFunctionName);

        for (Constraint c : constraintsOnLocation) {
            if (SymbolicValues.representSameCCodeExpression(c, pConstraint)) {
                return true;
            }//w ww  .  j  a v a 2 s.c o  m
        }
    }

    return false;
}