Example usage for com.google.common.collect ImmutableMap keySet

List of usage examples for com.google.common.collect ImmutableMap keySet

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMap keySet.

Prototype

public ImmutableSet<K> keySet() 

Source Link

Usage

From source file:org.apache.cloudstack.outofbandmanagement.OutOfBandManagementServiceImpl.java

protected OutOfBandManagement updateConfig(final OutOfBandManagement outOfBandManagementConfig,
        final ImmutableMap<OutOfBandManagement.Option, String> options) {
    if (outOfBandManagementConfig == null) {
        throw new CloudRuntimeException("Out-of-band management is not configured for the host. Aborting.");
    }/*  w  ww .ja v a  2 s  . co  m*/
    if (options == null) {
        return outOfBandManagementConfig;
    }
    for (OutOfBandManagement.Option option : options.keySet()) {
        final String value = options.get(option);
        if (Strings.isNullOrEmpty(value)) {
            continue;
        }
        switch (option) {
        case DRIVER:
            outOfBandManagementConfig.setDriver(value);
            break;
        case ADDRESS:
            outOfBandManagementConfig.setAddress(value);
            break;
        case PORT:
            outOfBandManagementConfig.setPort(Integer.parseInt(value));
            break;
        case USERNAME:
            outOfBandManagementConfig.setUsername(value);
            break;
        case PASSWORD:
            outOfBandManagementConfig.setPassword(value);
            break;
        }
    }
    return outOfBandManagementConfig;
}

From source file:org.elasticsearch.index.gateway.blobstore.BlobStoreIndexShardGateway.java

private long findLatestFileNameGeneration(ImmutableMap<String, BlobMetaData> blobs) {
    long generation = -1;
    for (String name : blobs.keySet()) {
        if (!name.startsWith("__")) {
            continue;
        }//  w ww .j  av a 2s  . c  o m
        if (name.contains(".part")) {
            name = name.substring(0, name.indexOf(".part"));
        }

        try {
            long currentGen = Long.parseLong(name.substring(2) /*__*/, Character.MAX_RADIX);
            if (currentGen > generation) {
                generation = currentGen;
            }
        } catch (NumberFormatException e) {
            logger.warn("file [{}] does not conform to the '__' schema");
        }
    }
    return generation;
}

From source file:com.facebook.buck.core.cell.AbstractCellConfig.java

/**
 * Translates the 'cell name'->override map into a 'Path'->override map.
 *
 * @param pathMapping a map containing paths to all of the cells we want to query.
 * @return 'Path'->override map//w w  w  .j  a va 2  s .c  om
 */
public ImmutableMap<Path, RawConfig> getOverridesByPath(ImmutableMap<CellName, Path> pathMapping)
        throws InvalidCellOverrideException {

    ImmutableSet<CellName> relativeNamesOfCellsWithOverrides = FluentIterable.from(getValues().keySet())
            .filter(Predicates.not(CellName.ALL_CELLS_SPECIAL_NAME::equals)).toSet();
    ImmutableSet.Builder<Path> pathsWithOverrides = ImmutableSet.builder();
    for (CellName cellWithOverride : relativeNamesOfCellsWithOverrides) {
        if (!pathMapping.containsKey(cellWithOverride)) {
            throw new InvalidCellOverrideException(
                    String.format("Trying to override settings for unknown cell %s", cellWithOverride));
        }
        pathsWithOverrides.add(pathMapping.get(cellWithOverride));
    }

    ImmutableMultimap<Path, CellName> pathToRelativeName = Multimaps.index(pathMapping.keySet(),
            Functions.forMap(pathMapping));

    for (Path pathWithOverrides : pathsWithOverrides.build()) {
        ImmutableList<CellName> namesForPath = RichStream.from(pathToRelativeName.get(pathWithOverrides))
                .filter(name -> name.getLegacyName().isPresent()).toImmutableList();
        if (namesForPath.size() > 1) {
            throw new InvalidCellOverrideException(
                    String.format("Configuration override is ambiguous: cell rooted at %s is reachable "
                            + "as [%s]. Please override the config by placing a .buckconfig.local file in the "
                            + "cell's root folder.", pathWithOverrides, Joiner.on(',').join(namesForPath)));
        }
    }

    Map<Path, RawConfig> overridesByPath = new HashMap<>();
    for (Map.Entry<CellName, Path> entry : pathMapping.entrySet()) {
        CellName cellRelativeName = entry.getKey();
        Path cellPath = entry.getValue();
        RawConfig configFromOtherRelativeName = overridesByPath.get(cellPath);
        RawConfig config = getForCell(cellRelativeName);
        if (configFromOtherRelativeName != null) {
            // Merge configs
            RawConfig mergedConfig = RawConfig.builder().putAll(configFromOtherRelativeName).putAll(config)
                    .build();
            overridesByPath.put(cellPath, mergedConfig);
        } else {
            overridesByPath.put(cellPath, config);
        }
    }

    return ImmutableMap.copyOf(overridesByPath);
}

From source file:org.elasticsearch.index.gateway.blobstore.BlobStoreIndexShardGateway.java

private CommitPoints buildCommitPoints(ImmutableMap<String, BlobMetaData> blobs) {
    List<CommitPoint> commitPoints = Lists.newArrayList();
    for (String name : blobs.keySet()) {
        if (name.startsWith("commit-")) {
            try {
                commitPoints.add(CommitPoints.fromXContent(blobContainer.readBlobFully(name)));
            } catch (Exception e) {
                logger.warn("failed to read commit point [{}]", e, name);
            }/* www  .  j  a v  a2  s. c  om*/
        }
    }
    return new CommitPoints(commitPoints);
}

From source file:com.facebook.buck.python.PythonTestDescription.java

@Override
public <A extends Arg> PythonTest createBuildRule(TargetGraph targetGraph, final BuildRuleParams params,
        final BuildRuleResolver resolver, final A args)
        throws HumanReadableException, NoSuchBuildTargetException {

    PythonPlatform pythonPlatform = pythonPlatforms.getValue(params.getBuildTarget())
            .orElse(pythonPlatforms.getValue(args.platform.<Flavor>map(ImmutableFlavor::of)
                    .orElse(pythonPlatforms.getFlavors().iterator().next())));
    CxxPlatform cxxPlatform = cxxPlatforms.getValue(params.getBuildTarget()).orElse(defaultCxxPlatform);
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
    Path baseModule = PythonUtil.getBasePath(params.getBuildTarget(), args.baseModule);
    Optional<ImmutableMap<BuildTarget, Version>> selectedVersions = targetGraph.get(params.getBuildTarget())
            .getSelectedVersions();//from  w  ww  .jav a  2  s .c om

    ImmutableMap<Path, SourcePath> srcs = PythonUtil.getModules(params.getBuildTarget(), pathResolver, "srcs",
            baseModule, args.srcs, args.platformSrcs, pythonPlatform, args.versionedSrcs, selectedVersions);

    ImmutableMap<Path, SourcePath> resources = PythonUtil.getModules(params.getBuildTarget(), pathResolver,
            "resources", baseModule, args.resources, args.platformResources, pythonPlatform,
            args.versionedResources, selectedVersions);

    // Convert the passed in module paths into test module names.
    ImmutableSet.Builder<String> testModulesBuilder = ImmutableSet.builder();
    for (Path name : srcs.keySet()) {
        testModulesBuilder.add(PythonUtil.toModuleName(params.getBuildTarget(), name.toString()));
    }
    ImmutableSet<String> testModules = testModulesBuilder.build();

    // Construct a build rule to generate the test modules list source file and
    // add it to the build.
    BuildRule testModulesBuildRule = createTestModulesSourceBuildRule(params,
            getTestModulesListPath(params.getBuildTarget(), params.getProjectFilesystem()), testModules);
    resolver.addToIndex(testModulesBuildRule);

    String mainModule;
    if (args.mainModule.isPresent()) {
        mainModule = args.mainModule.get();
    } else {
        mainModule = PythonUtil.toModuleName(params.getBuildTarget(), getTestMainName().toString());
    }

    // Build up the list of everything going into the python test.
    PythonPackageComponents testComponents = PythonPackageComponents.of(ImmutableMap.<Path, SourcePath>builder()
            .put(getTestModulesListName(), new BuildTargetSourcePath(testModulesBuildRule.getBuildTarget()))
            .put(getTestMainName(), pythonBuckConfig.getPathToTestMain(params.getProjectFilesystem()))
            .putAll(srcs).build(), resources, ImmutableMap.of(), ImmutableSet.of(), args.zipSafe);
    PythonPackageComponents allComponents = PythonUtil.getAllComponents(params, resolver, pathResolver,
            ruleFinder, testComponents, pythonPlatform, cxxBuckConfig, cxxPlatform,
            args.linkerFlags.stream()
                    .map(MacroArg.toMacroArgFunction(PythonUtil.MACRO_HANDLER, params.getBuildTarget(),
                            params.getCellRoots(), resolver)::apply)
                    .collect(MoreCollectors.toImmutableList()),
            pythonBuckConfig.getNativeLinkStrategy(), args.preloadDeps);

    // Build the PEX using a python binary rule with the minimum dependencies.
    BuildRuleParams binaryParams = params.copyWithChanges(getBinaryBuildTarget(params.getBuildTarget()),
            Suppliers.ofInstance(PythonUtil.getDepsFromComponents(ruleFinder, allComponents)),
            Suppliers.ofInstance(ImmutableSortedSet.of()));
    PythonBinary binary = binaryDescription.createPackageRule(binaryParams, resolver, pathResolver, ruleFinder,
            pythonPlatform, cxxPlatform, mainModule, args.extension, allComponents, args.buildArgs,
            args.packageStyle.orElse(pythonBuckConfig.getPackageStyle()),
            PythonUtil.getPreloadNames(resolver, cxxPlatform, args.preloadDeps));
    resolver.addToIndex(binary);

    ImmutableList.Builder<Pair<Float, ImmutableSet<Path>>> neededCoverageBuilder = ImmutableList.builder();
    for (NeededCoverageSpec coverageSpec : args.neededCoverage) {
        BuildRule buildRule = resolver.getRule(coverageSpec.getBuildTarget());
        if (params.getDeps().contains(buildRule) && buildRule instanceof PythonLibrary) {
            PythonLibrary pythonLibrary = (PythonLibrary) buildRule;
            ImmutableSortedSet<Path> paths;
            if (coverageSpec.getPathName().isPresent()) {
                Path path = coverageSpec.getBuildTarget().getBasePath()
                        .resolve(coverageSpec.getPathName().get());
                if (!pythonLibrary.getSrcs(pythonPlatform).keySet().contains(path)) {
                    throw new HumanReadableException(
                            "%s: path %s specified in needed_coverage not found in target %s",
                            params.getBuildTarget(), path, buildRule.getBuildTarget());
                }
                paths = ImmutableSortedSet.of(path);
            } else {
                paths = ImmutableSortedSet.copyOf(pythonLibrary.getSrcs(pythonPlatform).keySet());
            }
            neededCoverageBuilder
                    .add(new Pair<Float, ImmutableSet<Path>>(coverageSpec.getNeededCoverageRatio(), paths));
        } else {
            throw new HumanReadableException(
                    "%s: needed_coverage requires a python library dependency. Found %s instead",
                    params.getBuildTarget(), buildRule);
        }
    }

    // Supplier which expands macros in the passed in test environment.
    Supplier<ImmutableMap<String, String>> testEnv = () -> ImmutableMap.copyOf(Maps.transformValues(args.env,
            MACRO_HANDLER.getExpander(params.getBuildTarget(), params.getCellRoots(), resolver)));

    // Generate and return the python test rule, which depends on the python binary rule above.
    return new PythonTest(
            params.copyWithDeps(
                    Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder()
                            .addAll(params.getDeclaredDeps().get()).add(binary).build()),
                    params.getExtraDeps()),
            pathResolver, ruleFinder, testEnv, binary, args.labels, neededCoverageBuilder.build(),
            args.testRuleTimeoutMs.map(Optional::of).orElse(defaultTestRuleTimeoutMs), args.contacts);
}

From source file:com.facebook.buck.config.AbstractCellConfig.java

/**
 * Translates the 'cell name'->override map into a 'Path'->override map.
 * @param pathMapping a map containing paths to all of the cells we want to query.
 * @return 'Path'->override map//from  w  w w .  ja  va 2s  .  co m
 */
public ImmutableMap<Path, RawConfig> getOverridesByPath(ImmutableMap<RelativeCellName, Path> pathMapping)
        throws MalformedOverridesException {

    ImmutableSet<RelativeCellName> relativeNamesOfCellsWithOverrides = FluentIterable.from(getValues().keySet())
            .filter(Predicates.not(ALL_CELLS_OVERRIDE::equals)).toSet();
    ImmutableSet.Builder<Path> pathsWithOverrides = ImmutableSet.builder();
    for (RelativeCellName cellWithOverride : relativeNamesOfCellsWithOverrides) {
        if (!pathMapping.containsKey(cellWithOverride)) {
            throw new MalformedOverridesException(
                    String.format("Trying to override settings for unknown cell %s", cellWithOverride));
        }
        pathsWithOverrides.add(pathMapping.get(cellWithOverride));
    }

    ImmutableMultimap<Path, RelativeCellName> pathToRelativeName = Multimaps.index(pathMapping.keySet(),
            Functions.forMap(pathMapping));

    for (Path pathWithOverrides : pathsWithOverrides.build()) {
        ImmutableCollection<RelativeCellName> namesForPath = pathToRelativeName.get(pathWithOverrides);
        if (namesForPath.size() > 1) {
            throw new MalformedOverridesException(
                    String.format("Configuration override is ambiguous: cell rooted at %s is reachable "
                            + "as [%s]. Please override the config by placing a .buckconfig.local file in the "
                            + "cell's root folder.", pathWithOverrides, Joiner.on(',').join(namesForPath)));
        }
    }

    Map<Path, RawConfig> overridesByPath = new HashMap<>();
    for (Map.Entry<RelativeCellName, Path> entry : pathMapping.entrySet()) {
        RelativeCellName cellRelativeName = entry.getKey();
        Path cellPath = entry.getValue();
        RawConfig configFromOtherRelativeName = overridesByPath.get(cellPath);
        RawConfig config = getForCell(cellRelativeName);
        if (configFromOtherRelativeName != null) {
            Preconditions.checkState(configFromOtherRelativeName.equals(config),
                    "Attempting to create cell %s at %s with conflicting overrides [%s] vs [%s].",
                    cellRelativeName, cellPath, configFromOtherRelativeName, config);
        } else {
            overridesByPath.put(cellPath, config);
        }
    }

    return ImmutableMap.copyOf(overridesByPath);
}

From source file:org.elasticsearch.search.query.sortbydoc.SortByDocQueryParser.java

@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
    XContentParser parser = parseContext.parser();

    String currentFieldName = null;

    String lookupIndex = parseContext.index().name();
    String lookupType = null;/*from   www.  j a v  a2 s.co  m*/
    String lookupId = null;
    String rootPath = null;
    String idField = null;
    String scoreField = null;
    String lookupRouting = null;
    SortOrder sortOrder = SortOrder.DESC;
    Query subQuery = null;

    XContentParser.Token token;

    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.START_OBJECT) {
            if ("query".equals(parser.currentName())) {
                subQuery = parseContext.parseInnerQuery();
                continue;
            }
        } else if (token.isValue()) {
            if (false) {
            } else if ("index".equals(currentFieldName)) {
                lookupIndex = parser.text();
            } else if ("type".equals(currentFieldName)) {
                lookupType = parser.text();
            } else if ("doc_id".equals(currentFieldName)) {
                lookupId = parser.text();
            } else if ("root".equals(currentFieldName)) {
                rootPath = parser.text();
            } else if ("id".equals(currentFieldName)) {
                idField = parser.text();
            } else if ("score".equals(currentFieldName)) {
                scoreField = parser.text();
            } else if ("routing".equals(currentFieldName)) {
                lookupRouting = parser.textOrNull();
            } else if ("sort_order".equals(currentFieldName)) {
                try {
                    sortOrder = SortOrder.valueOf(parser.text());
                } catch (IllegalArgumentException e) {
                    throw new QueryParsingException(parseContext,
                            "[sort_by_doc] sort_order should be one of " + Arrays.toString(SortOrder.values()));
                }
            } else {
                throw new QueryParsingException(parseContext, "[sort_by_doc] query does not support ["
                        + currentFieldName + "] within lookup element");
            }
        }
    }
    if (lookupType == null) {
        throw new QueryParsingException(parseContext,
                "[sort_by_doc] query lookup element requires specifying the type");
    }
    if (lookupId == null) {
        throw new QueryParsingException(parseContext,
                "[sort_by_doc] query lookup element requires specifying the doc_id");
    }
    if (rootPath == null) {
        throw new QueryParsingException(parseContext,
                "[sort_by_doc] query lookup element requires specifying the path");
    }
    if (idField == null) {
        throw new QueryParsingException(parseContext,
                "[sort_by_doc] query lookup element requires specifying the id");
    }
    if (scoreField == null) {
        throw new QueryParsingException(parseContext,
                "[sort_by_doc] query lookup element requires specifying the score");
    }

    if (subQuery == null) {
        throw new QueryParsingException(parseContext, "[sort_by_doc] query requires a subquery");
    }

    String fieldName = "_id";
    MappedFieldType _idType = parseContext.mapperService().smartNameFieldType(fieldName);

    /*
    FieldMapper fieldMapper = null;
    smartNameFieldMappers = parseContext.mapperService().smartFieldMappers(fieldName);
    if (smartNameFieldMappers != null) {
    if (smartNameFieldMappers.hasMapper()) {
        fieldMapper = smartNameFieldMappers.mapper();
        fieldName = fieldMapper.names().indexName();
    }
    }
    */

    /*
    if (fieldMapper == null || !(fieldMapper instanceof IdFieldMapper))
    throw new QueryParsingException(parseContext.index(), "[sort_by_doc] the _id field must be a defaultly indexed UID field");
    */

    if (_idType == null)
        throw new QueryParsingException(parseContext,
                "[sort_by_doc] the _id field must be a defaultly indexed UID field");

    // external lookup, use it
    ScoresLookup scoresLookup = new ScoresLookup(lookupIndex, lookupType, lookupId, lookupRouting, rootPath,
            idField, scoreField, parseContext, SearchContext.current());
    ImmutableMap<String, Float> scores = scoringDocumentCache.getScores(scoresLookup);
    Map<Term, Float> termsScores = new HashMap<>();
    for (Map.Entry<String, Float> score : scores.entrySet()) {
        Uid.createUidsForTypesAndId(parseContext.queryTypes(), score.getKey());
        BytesRef[] keyUids = Uid.createUidsForTypesAndId(parseContext.queryTypes(), score.getKey());
        for (BytesRef keyUid : keyUids) {
            Term t = new Term(UidFieldMapper.NAME, keyUid);
            termsScores.put(t, sortOrder.equals(SortOrder.DESC) ? score.getValue() : -score.getValue());
        }
    }

    if (scores.isEmpty()) {
        return subQuery;
    }

    Query filter = _idType.termsQuery(scores.keySet().asList(), parseContext);

    return new SortByDocQuery(fieldName, subQuery, filter, termsScores);
}

From source file:com.isotrol.impe3.pms.core.obj.PortalObject.java

List<SetFilterDTO> getSetFilterDTOs() {
    ImmutableMap<String, SetFilterValue> filters = setFilters.get();
    final List<SetFilterDTO> list = Lists.newArrayListWithCapacity(filters.size());
    if (filters.isEmpty()) {
        return list;
    }/*from   ww  w.  j a v  a2s .c  o m*/
    for (String set : Ordering.natural().sortedCopy(filters.keySet())) {
        SetFilterValue v = filters.get(set);
        SetFilterDTO dto = new SetFilterDTO();
        dto.setName(set);
        dto.setType(v.getType());
        dto.setDescription(v.getDescription());
        list.add(dto);
    }
    return list;
}

From source file:org.commoncrawl.mapred.pipelineV3.domainmeta.fuzzydedupe.HostBlacklistByDupesStep.java

@Override
public void runStep(Path outputPathLocation) throws IOException {

    LOG.info("Task Identity Path is:" + getTaskIdentityPath());
    LOG.info("Final Temp Path is:" + outputPathLocation);

    // join/*w ww  .j av  a 2s  .  c o  m*/
    // ip to host mapping
    // ip to bad host mapping
    // ip to quantcast domain (whitelist)

    Path temp = JobBuilder.tempDir(getConf(), OUTPUT_DIR_NAME + " phase-1");

    ImmutableMap<Path, String> step1InputMapping = new ImmutableMap.Builder<Path, String>()
            .put(makeUniqueFullyQualifiedOutputDirPath(getConf(),
                    _task.getOutputDirForStep(IPAddressToHostMappingStep.OUTPUT_DIR_NAME), getTaskIdentityId()),
                    TAG_IP_TO_HOST_MAPPING)
            .put(makeUniqueFullyQualifiedOutputDirPath(getConf(),
                    _task.getOutputDirForStep(FindBadIPsFromDupes.OUTPUT_DIR_NAME), getTaskIdentityId()),
                    TAG_BAD_IP_MAPPING)
            .put(makeUniqueFullyQualifiedOutputDirPath(getConf(),
                    _task.getOutputDirForStep(QuantcastIPListStep.OUTPUT_DIR_NAME), getTaskIdentityId()),
                    TAG_QUANTCAST_MAPPING)
            .build();

    JobConf job = new JobBuilder(getPipelineStepName() + " - step 1", getConf()).inputIsSeqFile()
            .inputs(ImmutableList.copyOf(step1InputMapping.keySet()))
            .mapperKeyValue(TextBytes.class, JoinValue.class).outputKeyValue(TextBytes.class, TextBytes.class)
            .mapper(JoinByTextSortByTagMapper.class).reducer(HostBlacklistByIPReducer.class, false)
            .partition(JoinByTextSortByTagMapper.Partitioner.class)
            .numReducers(CrawlEnvironment.NUM_DB_SHARDS / 2).outputIsSeqFile().output(temp)
            .jarByClass(HostBlacklistByDupesStep.class).build();

    JoinMapper.setPathToTagMapping(step1InputMapping, job);

    LOG.info("Running Step 1");
    JobClient.runJob(job);
    LOG.info("Done Running Step 1");

    // ok now reduce to a single file ...
    job = new JobBuilder(getPipelineStepName() + " - step 2", getConf()).inputIsSeqFile().input(temp)
            .keyValue(TextBytes.class, TextBytes.class).numReducers(1).outputIsSeqFile()
            .output(outputPathLocation).jarByClass(HostBlacklistByDupesStep.class).build();

    JobClient.runJob(job);

}

From source file:org.jclouds.s3.filters.Aws4SignerForAuthorizationHeader.java

protected HttpRequest sign(HttpRequest request) throws HttpException {
    checkNotNull(request, "request is not ready to sign");
    checkNotNull(request.getEndpoint(), "request is not ready to sign, request.endpoint not present.");

    Payload payload = request.getPayload();

    // get host from request endpoint.
    String host = request.getEndpoint().getHost();

    Date date = timestampProvider.get();
    String timestamp = timestampFormat.format(date);
    String datestamp = dateFormat.format(date);

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

    HttpRequest.Builder<?> requestBuilder = request.toBuilder() //
            .removeHeader(AUTHORIZATION) // remove Authorization
            .removeHeader(DATE); // remove date

    ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableSortedMap
            .<String, String>naturalOrder();

    // Content Type
    // content-type is not a required signing param. However, examples use this, so we include it to ease testing.
    String contentType = getContentType(request);
    if (!Strings.isNullOrEmpty(contentType)) {
        requestBuilder.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType);
        signedHeadersBuilder.put(HttpHeaders.CONTENT_TYPE.toLowerCase(), contentType);
    }//  w  w  w  . j  av  a 2  s  . c om

    // Content-Length for PUT or POST request http method
    String contentLength = getContentLength(request);
    if (!Strings.isNullOrEmpty(contentLength)) {
        requestBuilder.replaceHeader(HttpHeaders.CONTENT_LENGTH, contentLength);
        signedHeadersBuilder.put(HttpHeaders.CONTENT_LENGTH.toLowerCase(), contentLength);
    }

    // Content MD5
    String contentMD5 = request.getFirstHeaderOrNull(CONTENT_MD5);
    if (payload != null) {
        HashCode md5 = payload.getContentMetadata().getContentMD5AsHashCode();
        if (md5 != null) {
            contentMD5 = BaseEncoding.base64().encode(md5.asBytes());
        }
    }
    if (contentMD5 != null) {
        requestBuilder.replaceHeader(CONTENT_MD5, contentMD5);
        signedHeadersBuilder.put(CONTENT_MD5.toLowerCase(), contentMD5);
    }

    // host
    requestBuilder.replaceHeader(HttpHeaders.HOST, host);
    signedHeadersBuilder.put(HttpHeaders.HOST.toLowerCase(), host);

    // user-agent
    if (request.getHeaders().containsKey(HttpHeaders.USER_AGENT)) {
        signedHeadersBuilder.put(HttpHeaders.USER_AGENT.toLowerCase(),
                request.getFirstHeaderOrNull(HttpHeaders.USER_AGENT));
    }

    // all x-amz-* headers
    appendAmzHeaders(request, signedHeadersBuilder);

    // x-amz-security-token
    Credentials credentials = creds.get();
    if (credentials instanceof SessionCredentials) {
        String token = SessionCredentials.class.cast(credentials).getSessionToken();
        requestBuilder.replaceHeader(AMZ_SECURITY_TOKEN_HEADER, token);
        signedHeadersBuilder.put(AMZ_SECURITY_TOKEN_HEADER.toLowerCase(), token);
    }

    // x-amz-content-sha256
    String contentSha256 = getPayloadHash(request);
    requestBuilder.replaceHeader(AMZ_CONTENT_SHA256_HEADER, contentSha256);
    signedHeadersBuilder.put(AMZ_CONTENT_SHA256_HEADER.toLowerCase(), contentSha256);

    // put x-amz-date
    requestBuilder.replaceHeader(AMZ_DATE_HEADER, timestamp);
    signedHeadersBuilder.put(AMZ_DATE_HEADER.toLowerCase(), timestamp);

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

    String stringToSign = createStringToSign(request.getMethod(), request.getEndpoint(), signedHeaders,
            timestamp, credentialScope, contentSha256);
    signatureWire.getWireLog().debug("<< " + stringToSign);

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

    StringBuilder authorization = new StringBuilder(AMZ_ALGORITHM_HMAC_SHA256).append(" ");
    authorization.append("Credential=").append(Joiner.on("/").join(credentials.identity, credentialScope))
            .append(", ");
    authorization.append("SignedHeaders=").append(Joiner.on(";").join(signedHeaders.keySet())).append(", ");
    authorization.append("Signature=").append(signature);
    return requestBuilder.replaceHeader(HttpHeaders.AUTHORIZATION, authorization.toString()).build();
}