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:de.cosmocode.lucene.IndexHelper.java

/**
 * <p> Creates a lucene document with the given mapping as fields.
 * </p>//  w w  w.j av a 2s  .c  o m
 * 
 * @param fieldNameToValues the mapping of fieldname to values
 * @return a new document with a field set to the given values
 */
public static Document createDocument(final Multimap<String, ?> fieldNameToValues) {
    final Document doc = new Document();
    for (final Map.Entry<String, ?> mapping : fieldNameToValues.entries()) {
        if (mapping.getKey() == null || mapping.getValue() == null) {
            // ignore null key or value
            continue;
        }

        final String key = mapping.getKey();
        final String value = mapping.getValue().toString();
        final Field field = new Field(key, value, Store.YES, INDEX_METHOD);
        doc.add(field);
    }

    // add empty field, so that every search returns at least one document
    final Field emptyField = new Field("empty", "empty", Store.NO, INDEX_METHOD);
    doc.add(emptyField);

    return doc;
}

From source file:co.cask.cdap.common.http.HttpRequests.java

/**
 * Executes an HTTP request to the url provided.
 *
 * @param request HTTP request to execute
 * @param requestConfig configuration for the HTTP request to execute
 * @return HTTP response/*from   w  w  w .j ava2  s . c o  m*/
 */
public static HttpResponse execute(HttpRequest request, HttpRequestConfig requestConfig) throws IOException {
    String requestMethod = request.getMethod().name();
    URL url = request.getURL();

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(requestMethod);
    conn.setReadTimeout(requestConfig.getReadTimeout());
    conn.setConnectTimeout(requestConfig.getConnectTimeout());

    Multimap<String, String> headers = request.getHeaders();
    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entries()) {
            conn.setRequestProperty(header.getKey(), header.getValue());
        }
    }

    InputSupplier<? extends InputStream> bodySrc = request.getBody();
    if (bodySrc != null) {
        conn.setDoOutput(true);
    }

    if (conn instanceof HttpsURLConnection && !requestConfig.isVerifySSLCert()) {
        // Certificate checks are disabled for HTTPS connection.
        LOG.debug("Disabling SSL certificate check for {}", request.getURL());
        try {
            disableCertCheck((HttpsURLConnection) conn);
        } catch (Exception e) {
            LOG.error("Got exception while disabling SSL certificate check for {}", request.getURL());
        }
    }

    conn.connect();

    try {
        if (bodySrc != null) {
            OutputStream os = conn.getOutputStream();
            try {
                ByteStreams.copy(bodySrc, os);
            } finally {
                os.close();
            }
        }

        try {
            if (isSuccessful(conn.getResponseCode())) {
                return new HttpResponse(conn.getResponseCode(), conn.getResponseMessage(),
                        ByteStreams.toByteArray(conn.getInputStream()));
            }
        } catch (FileNotFoundException e) {
            // Server returns 404. Hence handle as error flow below. Intentional having empty catch block.
        }

        // Non 2xx response
        InputStream es = conn.getErrorStream();
        byte[] content = (es == null) ? new byte[0] : ByteStreams.toByteArray(es);
        return new HttpResponse(conn.getResponseCode(), conn.getResponseMessage(), content);
    } finally {
        conn.disconnect();
    }
}

From source file:com.googlecode.blaisemath.graph.SparseGraph.java

/**
 * Construct graph with a sparse adjacency representation.
 * @param <V> graph node type/*from w  w  w .j  a v a2 s  .co  m*/
 * @param directed if graph is directed
 * @param adjacencies map with adjacency info
 * @return graph
 */
public static <V> SparseGraph<V> createFromAdjacencies(boolean directed, Multimap<V, V> adjacencies) {
    SparseGraph<V> res = new SparseGraph<V>(directed, GraphUtils.nodes(adjacencies));
    for (Entry<V, V> en : adjacencies.entries()) {
        res.addEdge(en.getKey(), en.getValue());
    }
    res.components = new GraphComponents(res, GraphUtils.components(res.edgeTable));
    return res;
}

From source file:org.jclouds.http.utils.ModifyRequest.java

public static String makeQueryLine(Multimap<String, String> params,
        @Nullable Comparator<Map.Entry<String, String>> sorter, char... skips) {
    Iterator<Map.Entry<String, String>> pairs = ((sorter == null) ? params.entries()
            : ImmutableSortedSet.copyOf(sorter, params.entries())).iterator();
    StringBuilder formBuilder = new StringBuilder();
    while (pairs.hasNext()) {
        Map.Entry<String, String> pair = pairs.next();
        formBuilder.append(Strings2.urlEncode(pair.getKey(), skips));
        if (pair.getValue() != null && !pair.getValue().equals("")) {
            formBuilder.append("=");
            formBuilder.append(Strings2.urlEncode(pair.getValue(), skips));
        }/*from  w  w w .  jav  a  2  s . c  o  m*/
        if (pairs.hasNext())
            formBuilder.append("&");
    }
    return formBuilder.toString();
}

From source file:com.zimbra.cs.mailbox.acl.AclPushTask.java

/**
 * @param mailboxIdUnderProcess//from w w w . j  a  v a2s  . c  om
 * @param currentItemIdsProcessed
 * @throws ServiceException
 */
private static void deleteDbAclEntryForProcessedItems(Multimap<Integer, List<Integer>> currentItemIdsProcessed)
        throws ServiceException {
    if (currentItemIdsProcessed.size() != 0) {
        Collection<Entry<Integer, List<Integer>>> mailboxIds = currentItemIdsProcessed.entries();
        for (Entry<Integer, List<Integer>> entry : mailboxIds) {
            int mboxId = entry.getKey();
            List<Integer> itemIds = entry.getValue();
            for (int itemId : itemIds)
                DbPendingAclPush.deleteEntry(mboxId, itemId);
        }
    }
}

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());
        }/*ww  w . j av  a  2s  . c  om*/
    }
    return canonicalizedHeaders;
}

From source file:de.iteratec.iteraplan.elasticeam.derived.DerivedMetamodelFactory.java

@SuppressWarnings("boxing")
private static void collectPaths(SubstantialTypeExpression startClass, int length,
        Collection<List<RelationshipEndExpression>> result) {
    Multimap<Integer, List<RelationshipEndExpression>> pathsAndPrefixes = collectPathCandidates(startClass,
            length);/*from   w  w w  . jav  a  2  s .c  om*/
    for (Entry<Integer, List<RelationshipEndExpression>> pathCandidate : pathsAndPrefixes.entries()) {
        if (!endsInRelationshipType(pathCandidate.getValue())
                && !isSelfReferentialPath(startClass, pathCandidate.getValue())) {
            result.add(pathCandidate.getValue());
        } else if (pathCandidate.getKey() == length) {
            for (List<RelationshipEndExpression> expandedPathCandidate : expandByOneStep(
                    pathCandidate.getValue())) {
                if (!endsInRelationshipType(expandedPathCandidate)
                        && !isSelfReferentialPath(startClass, pathCandidate.getValue())) {
                    result.add(expandedPathCandidate);
                }
            }
        }
    }
}

From source file:co.cask.common.http.HttpRequests.java

/**
 * Executes an HTTP request to the url provided.
 *
 * @param request HTTP request to execute
 * @param requestConfig configuration for the HTTP request to execute
 * @return HTTP response/* w  ww  .j a v a  2 s. co  m*/
 */
public static HttpResponse execute(HttpRequest request, HttpRequestConfig requestConfig) throws IOException {
    String requestMethod = request.getMethod().name();
    URL url = request.getURL();

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(requestMethod);
    conn.setReadTimeout(requestConfig.getReadTimeout());
    conn.setConnectTimeout(requestConfig.getConnectTimeout());

    Multimap<String, String> headers = request.getHeaders();
    if (headers != null && !headers.isEmpty()) {
        for (Map.Entry<String, String> header : headers.entries()) {
            conn.setRequestProperty(header.getKey(), header.getValue());
        }
    }

    InputSupplier<? extends InputStream> bodySrc = request.getBody();
    if (bodySrc != null) {
        conn.setDoOutput(true);
        Long bodyLength = request.getBodyLength();
        if (bodyLength != null) {
            // use intValue to support 1.6
            if (bodyLength > requestConfig.getFixedLengthStreamingThreshold()) {
                conn.setFixedLengthStreamingMode(bodyLength.intValue());
            }
        } else {
            conn.setChunkedStreamingMode(0);
        }
    }

    if (conn instanceof HttpsURLConnection && !requestConfig.isVerifySSLCert()) {
        // Certificate checks are disabled for HTTPS connection.
        LOG.debug("Disabling SSL certificate check for {}", request.getURL());
        try {
            disableCertCheck((HttpsURLConnection) conn);
        } catch (Exception e) {
            LOG.error("Got exception while disabling SSL certificate check for {}", request.getURL());
        }
    }

    conn.connect();

    try {
        if (bodySrc != null) {
            OutputStream os = conn.getOutputStream();
            try {
                ByteStreams.copy(bodySrc, os);
            } finally {
                os.close();
            }
        }

        try {
            if (isSuccessful(conn.getResponseCode())) {
                return new HttpResponse(conn.getResponseCode(), conn.getResponseMessage(),
                        ByteStreams.toByteArray(conn.getInputStream()), conn.getHeaderFields());
            }
        } catch (FileNotFoundException e) {
            // Server returns 404. Hence handle as error flow below. Intentional having empty catch block.
        }

        // Non 2xx response
        InputStream es = conn.getErrorStream();
        byte[] content = (es == null) ? new byte[0] : ByteStreams.toByteArray(es);
        return new HttpResponse(conn.getResponseCode(), conn.getResponseMessage(), content,
                conn.getHeaderFields());
    } finally {
        conn.disconnect();
    }
}

From source file:com.liveramp.cascading_ext.CascadingUtil.java

public static FlowConnector buildFlowConnector(JobConf jobConf, JobPersister persister,
        Map<Object, Object> properties, List<FlowStepStrategy<JobConf>> flowStepStrategies,
        Multimap<String, String> invalidPropertyValues) {

    //  check required against stuff loaded from app-site.xml
    for (Map.Entry<String, String> entry : invalidPropertyValues.entries()) {
        String property = entry.getKey();
        String value = entry.getValue();

        if (ObjectUtils.equals(resolveProperty(property, properties, jobConf), value)) {
            LOG.error("Property " + property + " set to invalid value " + value + " with properties map: "
                    + properties);// w  w w  .  j a va 2s.c o m
            throw new RuntimeException("Cannot build flow without setting property: " + property
                    + " to a value which is not " + value);
        }
    }

    return new LoggingFlowConnector(properties, new MultiFlowStepStrategy(flowStepStrategies), persister,
            OperationStatsUtils.formatStackPosition(OperationStatsUtils.getStackPosition(2)));
}

From source file:com.outerspacecat.openid.rp.Assertion.java

/**
 * Creates a new assertion.//  www .  j a va  2s .  co  m
 * 
 * @param association the association to use to validate the assertion. Must
 *        be non {@code null}.
 * @param fields the assertion fields. Must be non {@code null}.
 * @param receivingUrl the url that is processing this assertion. Must be non
 *        {@code null}.
 * @param nonceStore a nonce store. Must be non {@code null};
 * @return a new assertion. Never {@code null}.
 * @throws InvalidAssertionException if an assertion cannot be created
 */
public static Assertion create(final Association association, final Map<String, String> fields,
        final URI receivingUrl, final NonceStore nonceStore) throws InvalidAssertionException {
    Preconditions.checkNotNull(association, "association required");
    Preconditions.checkNotNull(fields, "fields required");
    Preconditions.checkNotNull(receivingUrl, "receivingUrl required");
    Preconditions.checkNotNull(nonceStore, "nonceStore required");

    String nsParam = fields.get("openid.ns");
    if (!"http://specs.openid.net/auth/2.0".equals(nsParam))
        throw new InvalidAssertionException("invalid ns: " + nsParam);

    String modeParam = fields.get("openid.mode");
    if (!"id_res".equals(modeParam))
        throw new InvalidAssertionException("invalid openid.mode: " + modeParam);

    String claimedIdParam = fields.get("openid.claimed_id");
    String identityParam = fields.get("openid.identity");
    if ((claimedIdParam == null) != (identityParam == null))
        throw new InvalidAssertionException(
                "invalid openid.claimed_id and openid.identity: " + claimedIdParam + ", " + identityParam);

    String returnToParam = fields.get("openid.return_to");
    if (returnToParam == null)
        throw new InvalidAssertionException("missing openid.return_to");

    try {
        URI returnToUri = new URI(returnToParam);

        if (!(receivingUrl.getScheme() + "://" + receivingUrl.getRawAuthority() + receivingUrl.getRawPath())
                .equals((returnToUri.getScheme() + "://" + returnToUri.getRawAuthority()
                        + returnToUri.getRawPath())))
            throw new InvalidAssertionException(null);

        Multimap<String, String> returnToParams = Utils.parseHttpQueryString(returnToUri.getRawQuery(),
                Charset.forName("UTF-8"));

        for (Map.Entry<String, String> e : returnToParams.entries()) {
            if (!e.getValue().equals(fields.get(e.getKey())))
                throw new InvalidAssertionException(
                        "missing return_to parameter, key=" + e.getKey() + ", return_to value=" + e.getValue()
                                + ", recievingUrl value=" + fields.get(e.getKey()));
        }
    } catch (URISyntaxException e) {
        throw new InvalidAssertionException(
                "invalid openid.return_to parameter, openid.return_to=" + returnToParam);
    }

    // openid.invalidate_handle is not checked because associations are never
    // reused

    String assocHandleParam = fields.get("openid.assoc_handle");
    if (!association.getHandle().equals(assocHandleParam))
        throw new InvalidAssertionException("invalid openid.assoc_handle, expected " + association.getHandle()
                + ", got " + assocHandleParam);

    String responseSignedParam = fields.get("openid.signed");
    if (responseSignedParam == null)
        throw new InvalidAssertionException("missing openid.signed");

    String responseSigParam = fields.get("openid.sig");
    if (responseSigParam == null)
        throw new InvalidAssertionException("missing openid.sig");

    String responseNonceParam = fields.get("openid.response_nonce");
    if (responseNonceParam == null || !NoncePattern.matcher(responseNonceParam).matches())
        throw new InvalidAssertionException("invalid openid.response_nonce: " + responseNonceParam);

    // discovery information is not verified because none is ever gathered

    nonceStore.store(association.getEndpoint().getUri(), responseNonceParam);

    ImmutableSet<String> signedFields = ImmutableSet.copyOf(responseSignedParam.split(","));

    if (!signedFields.contains("op_endpoint"))
        throw new InvalidAssertionException("openid.signed must contain \"op_endpoint\"");
    if (!signedFields.contains("return_to"))
        throw new InvalidAssertionException("openid.signed must contain \"return_to\"");
    if (!signedFields.contains("response_nonce"))
        throw new InvalidAssertionException("openid.signed must contain \"response_nonce\"");
    if (!signedFields.contains("assoc_handle"))
        throw new InvalidAssertionException("openid.signed must contain \"assoc_handle\"");
    if (claimedIdParam != null && !signedFields.contains("claimed_id"))
        throw new InvalidAssertionException(
                "openid.signed must contain \"claimed_id\" when claimed_id is in response");
    if (identityParam != null && !signedFields.contains("identity"))
        throw new InvalidAssertionException(
                "openid.signed must contain \"identity\" when identity is in response");

    StringBuilder sb = new StringBuilder();
    for (String field : signedFields) {
        if (fields.containsKey("openid." + field)) {
            sb.append(field).append(":").append(fields.get("openid." + field)).append("\n");
        }
    }

    try {
        Mac mac = Mac.getInstance(association.getAssociationType().getAlgorithm());
        mac.init(new SecretKeySpec(association.getMacKey(), association.getAssociationType().getValue()));
        mac.update(sb.toString().getBytes(Charset.forName("UTF-8")));
        String calculatedSig = new String(Base64.encode(mac.doFinal()));

        if (!Utils.constantEquals(responseSigParam, calculatedSig))
            throw new InvalidAssertionException(
                    "invalid sig, expected " + calculatedSig + ", got " + responseSigParam);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    }

    return new Assertion(claimedIdParam);
}