Example usage for com.google.common.collect Maps transformValues

List of usage examples for com.google.common.collect Maps transformValues

Introduction

In this page you can find the example usage for com.google.common.collect Maps transformValues.

Prototype

@GwtIncompatible("NavigableMap")
public static <K, V1, V2> NavigableMap<K, V2> transformValues(NavigableMap<K, V1> fromMap,
        Function<? super V1, V2> function) 

Source Link

Document

Returns a view of a navigable map where each value is transformed by a function.

Usage

From source file:com.google.devtools.build.lib.actions.ActionLookupValue.java

public static Map<Artifact, ActionAnalysisMetadata> getMapForConsistencyCheck(
        Map<Artifact, Integer> generatingActionIndex, final List<? extends ActionAnalysisMetadata> actions) {
    return Maps.transformValues(generatingActionIndex, new Function<Integer, ActionAnalysisMetadata>() {
        @Override//ww  w  .  java 2 s  .com
        public ActionAnalysisMetadata apply(Integer index) {
            return actions.get(index);
        }
    });
}

From source file:org.eclipse.incquery.runtime.matchers.context.surrogate.SurrogateQueryRegistry.java

/**
 * @return the map of features with registered surrogate query FQNs
 * @deprecated use {@link #getRegisteredSurrogateQueries()} instead
 *//*w w w. j  a  va 2  s  . c  o m*/
public Map<IInputKey, PQuery> getRegisteredSurrogateQueryFQNMap() {
    return Maps.transformValues(registeredSurrogateQueryMap, new ProvidedValueFunction());
}

From source file:com.eucalyptus.auth.policy.key.Keys.java

public static Map<String, Key> getKeyInstances(final EvaluationConstraint constraint) {
    return Maps.transformValues(
            Maps.filterValues(KEY_MAP,/*from ww w.jav  a 2  s.  c o  m*/
                    CollectionUtils.propertyContainsPredicate(constraint, Functions
                            .compose(PolicyKeyToEvaluationConstraints.INSTANCE, KeyClassToPolicyKey.INSTANCE))),
            KeyClassToKeyInstance.INSTANCE);
}

From source file:com.google.gerrit.server.update.RepoView.java

/**
 * Look up refs by prefix./*w  w  w .  ja v a2  s. c o  m*/
 *
 * <p>Takes into account any ref update commands added during the course of the update using
 * {@link RepoContext#addRefUpdate}, even if they have not yet been executed on the underlying
 * repo.
 *
 * <p>For any ref that has previously been accessed with {@link #getRef(String)}, the value in the
 * result map will be that same cached value. Any refs that have <em>not</em> been previously
 * accessed are re-scanned from the repo on each call.
 *
 * @param prefix ref prefix; must end in '/' or else be empty.
 * @return a map of ref suffixes to SHA-1s. The refs are all under {@code prefix} and have the
 *     prefix stripped; this matches the behavior of {@link
 *     org.eclipse.jgit.lib.RefDatabase#getRefs(String)}.
 * @throws IOException if an error occurred.
 */
public Map<String, ObjectId> getRefs(String prefix) throws IOException {
    Map<String, ObjectId> result = new HashMap<>(
            Maps.transformValues(repo.getRefDatabase().getRefs(prefix), Ref::getObjectId));

    // First, overwrite any cached reads from the underlying RepoRefCache. If any of these differ,
    // it's because a ref was updated after the RepoRefCache read it. It feels a little odd to
    // prefer the *old* value in this case, but it would be weirder to be inconsistent with getRef.
    //
    // Mostly this doesn't matter. If the caller was intending to write to the ref, they lost a
    // race, and they will get a lock failure. If they just want to read, well, the JGit interface
    // doesn't currently guarantee that any snapshot of multiple refs is consistent, so they were
    // probably out of luck anyway.
    commands.getRepoRefCache().getCachedRefs()
            .forEach((k, v) -> updateRefIfPrefixMatches(result, prefix, k, v));

    // Second, overwrite with any pending commands.
    commands.getCommands().values()
            .forEach(c -> updateRefIfPrefixMatches(result, prefix, c.getRefName(), toOptional(c.getNewId())));

    return result;
}

From source file:org.openengsb.core.services.internal.deployer.connector.ConnectorFile.java

private ImmutableMap<String, String> readProperties(File file) {
    FileReader reader = null;// ww  w  .j av a2 s . c om
    try {
        reader = new FileReader(file);
        Properties props = new Properties();
        props.load(reader);
        Map<String, String> map = Maps.fromProperties(props);
        Map<String, String> transformedMap = Maps.transformValues(map, new TrimFunction<String, String>());
        return ImmutableMap.copyOf(transformedMap);

    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:fr.dutra.confluence2wordpress.core.converter.processors.MacroToMacroProcessor.java

protected String getWordpressMacroParametersAsString(MacroDefinition macroDefinition) throws XhtmlException {
    Map<String, String> map = getWordpressMacroParameters(macroDefinition);
    return JOINER.join(Maps.transformValues(map, DOUBLE_ESCAPE_XML_THEN_QUOTE));
}

From source file:co.cask.cdap.data2.dataset2.lib.timeseries.FactTable.java

public void add(List<Fact> facts) {
    // Simply collecting all rows/cols/values that need to be put to the underlying table.
    NavigableMap<byte[], NavigableMap<byte[], byte[]>> gaugesTable = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
    NavigableMap<byte[], NavigableMap<byte[], byte[]>> incrementsTable = Maps
            .newTreeMap(Bytes.BYTES_COMPARATOR);
    for (Fact fact : facts) {
        for (Measurement measurement : fact.getMeasurements()) {
            byte[] rowKey = codec.createRowKey(fact.getDimensionValues(), measurement.getName(),
                    fact.getTimestamp());
            byte[] column = codec.createColumn(fact.getTimestamp());

            if (MeasureType.COUNTER == measurement.getType()) {
                inc(incrementsTable, rowKey, column, measurement.getValue());
            } else {
                set(gaugesTable, rowKey, column, Bytes.toBytes(measurement.getValue()));
            }//from   w w  w  . j ava 2s .  c  o  m
        }
    }

    NavigableMap<byte[], NavigableMap<byte[], Long>> convertedIncrementsTable = Maps
            .transformValues(incrementsTable, TRANSFORM_MAP_BYTE_ARRAY_TO_LONG);

    NavigableMap<byte[], NavigableMap<byte[], Long>> convertedGaugesTable = Maps.transformValues(gaugesTable,
            TRANSFORM_MAP_BYTE_ARRAY_TO_LONG);

    // todo: replace with single call, to be able to optimize rpcs in underlying table
    timeSeriesTable.put(convertedGaugesTable);
    timeSeriesTable.increment(convertedIncrementsTable);
    if (metrics != null) {
        metrics.increment(putCountMetric, convertedGaugesTable.size());
        metrics.increment(incrementCountMetric, convertedIncrementsTable.size());
    }
}

From source file:com.wadpam.guja.oauth2.web.Oauth2ClientAuthenticationFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    LOGGER.debug("Oauth2 client authentication");

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    if (serverEnvironment.isDevEnvironment()) {
        response.addHeader("Access-Control-Allow-Origin", "*");
    }/*from  w  w  w .  j a  va2 s.c  o  m*/
    // Either the Authorize header or json body is used to provide the client credentials
    String authHeader = request.getHeader(OAuth2Filter.HEADER_AUTHORIZATION);
    ClientCredentials credentials = null;
    if (request.getContentLength() > 0 && (request.getContentType().startsWith(MediaType.APPLICATION_JSON)
            || request.getContentType().startsWith(MediaType.APPLICATION_FORM_URLENCODED))) {

        HttpBodyRequestWrapper wrappedRequest = new HttpBodyRequestWrapper(request);

        if (request.getContentType().startsWith(MediaType.APPLICATION_JSON)) {

            // Parse JSON body
            credentials = objectMapper.readValue(wrappedRequest.getBody(), ClientCredentials.class);

        } else if (request.getContentType().startsWith(MediaType.APPLICATION_FORM_URLENCODED)) {

            // Parse the form encoded request body. Remember to URL decode the parameters
            Map<String, String> formParams = Splitter.on("&").trimResults().withKeyValueSeparator("=")
                    .split(wrappedRequest.getBody());
            formParams = Maps.transformValues(formParams, new Function<String, String>() {
                @Override
                public String apply(String value) {
                    try {
                        return URLDecoder.decode(value, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        LOGGER.error("Not possible to URL decode {}", e);
                        return value;
                    }
                }
            });

            LOGGER.debug("URL decoded form body {}", formParams);

            credentials = new ClientCredentials();
            credentials.setClient_id(formParams.get("client_id"));
            credentials.setClient_secret((formParams.get("client_secret")));

        }

        // Must wrap the request
        request = wrappedRequest;
    }

    // Check for duplicate authentication methods - invalid request
    if (null != authHeader && null != credentials && null != credentials.getClient_id()
            && null != credentials.getClient_secret()) {
        LOGGER.info("Bad request - duplicate client authentication credentials");
        // Multiple authentication credentials (400, "invalid_request")
        errorMessage(response, HttpServletResponse.SC_BAD_REQUEST, ERROR_INVALID_REQUEST);
        return;
    }

    // check for header
    if (null != authHeader) {

        LOGGER.debug("{}: {}", OAuth2Filter.HEADER_AUTHORIZATION, authHeader);
        int beginIndex = authHeader.indexOf(PREFIX_BASIC_AUTHENTICATION);
        if (-1 < beginIndex) {
            String baString = authHeader.substring(beginIndex + PREFIX_BASIC_AUTHENTICATION.length());
            String storedBaString = getBasicAuthenticationString();
            LOGGER.debug("{} equals? {}", baString, storedBaString);
            if (!baString.equals(storedBaString)) {
                LOGGER.info("Unauthorized - invalid client credentials");
                // Unauthorized (401, "invalid_client")
                response.setHeader(HEADER_WWW_AUTHENTICATE, PREFIX_BEARER); // TODO What should be returned
                errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT);
                return;
            }
        } else {
            // Unsupported client authentication method (401, "invalid_client")
            LOGGER.info("Unauthorized - client authentication method not supported");
            response.setHeader(HEADER_WWW_AUTHENTICATE, PREFIX_BEARER); // TODO What should be returned
            errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT);
            return;
        }

    } else if (null != credentials) {
        // Check JSON
        LOGGER.debug(String.format("%s: %s, %s", PREFIX_BASIC_AUTHENTICATION, credentials.getClient_id(),
                credentials.getClient_secret()));

        if (null == credentials.getClient_id() && null == credentials.getClient_secret()) {
            // No client authentication included (401, "invalid_client")
            LOGGER.info("Unauthorized - no client credentials found");
            errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT);
            return;
        } else if (null == credentials.getClient_id() ^ null == credentials.getClient_secret()) {
            LOGGER.info("Bad request - missing required parameter");
            // Missing client authentication parameter (400, "invalid_request")
            errorMessage(response, HttpServletResponse.SC_BAD_REQUEST, ERROR_INVALID_REQUEST);
            return;
        } else if (!isCredentialsValid(credentials.getClient_id(), credentials.getClient_secret())) {
            LOGGER.info("Unauthorized - invalid client credentials");
            // Unauthorized (401, "invalid_client")
            errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT);
            return;
        }

    } else {
        // No client authentication included (401, "invalid_client")
        LOGGER.info("Unauthorized - no client credentials found)");
        errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT);
        return;
    }

    chain.doFilter(request, response);

}

From source file:com.facebook.buck.distributed.DistBuildState.java

private static Config createConfig(BuildJobStateBuckConfig remoteBuckConfig) {
    ImmutableMap<String, ImmutableMap<String, String>> rawConfig = ImmutableMap
            .copyOf(Maps.transformValues(remoteBuckConfig.getRawBuckConfig(), input -> {
                ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
                for (OrderedStringMapEntry entry : input) {
                    builder.put(entry.getKey(), entry.getValue());
                }/*  w w w .j  a v  a2s .co m*/
                return builder.build();
            }));
    return new Config(RawConfig.of(rawConfig));
}

From source file:org.opendaylight.mdsal.dom.broker.ProducerLayout.java

Map<DOMDataTreeIdentifier, DOMDataTreeShardWriteTransaction> createTransactions() {
    Preconditions.checkState(!idToProducer.isEmpty(),
            "Cannot create transaction since the producer is not mapped to any shard");
    return Maps.transformValues(idToProducer, DOMDataTreeShardProducer::createTransaction);
}