protected URI getURI(String headerValue) { if (headerValue == null) return null; URI toReturn = URI.create(headerValue); if (!"127.0.0.1".equals(toReturn.getHost())) return toReturn; return uriBuilder(toReturn).host(hostToReplace).build(); }
private HttpRequest sign(String method, String path, long timeInSeconds) { Date now = dateService.rfc1123DateParse(timeStampProvider.get()); String expires = String.valueOf(now.getTime() / 1000 + timeInSeconds); String stringToSign = method + "\n" + path + "\n" + identity + "\n" + expires; return HttpRequest.builder() .method(method) .endpoint(Uris.uriBuilder(endpoint.getScheme() + "://" + endpoint.getHost()).appendPath(path).build()) .addQueryParam("uid", identity) .addQueryParam("expires", expires) .addQueryParam("signature", signer.calculateSignature(stringToSign)) .build(); } }
@Override public URI apply(String path) throws HttpException { String requestedResource = new StringBuilder().append("/rest/namespace/").append(path).toString(); String expires = timeStampProvider.get().toString(); String signature = signString(createStringToSign(requestedResource, expires)); return uriBuilder(provider.get()) .replaceQuery(ImmutableMap.of("uid", creds.get().identity, "expires", expires, "signature", signature)) .appendPath(requestedResource).build(); }
public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { closeClientButKeepContentStream(response); if (!command.isReplayable()) { logger.error("Cannot retry after redirect, command is not replayable: %s", command); URI redirect = URI.create(location); if (!redirect.isAbsolute()) { if (redirect.getPath() == null) { logger.error("Cannot retry after redirect, no path in location header %s", command); return false; redirect = uriBuilder(current.getEndpoint()).path(redirect.getPath()).query(redirect.getQuery()).build(); if (redirect.equals(current.getEndpoint())) { backoffHandler.imposeBackoffExponentialDelay(command.getRedirectCount(), "redirect: " + command.toString()); } else if (current.getFirstHeaderOrNull(HOST) != null && redirect.getHost() != null) { String host = redirect.getPort() > 0 ? redirect.getHost() + ":" + redirect.getPort() : redirect.getHost(); command.setCurrentRequest(current.toBuilder().replaceHeader(HOST, host).endpoint(redirect).build()); } else { command.setCurrentRequest(current.toBuilder().endpoint(redirect).build());
private UriBuilder(URI uri) { checkNotNull(uri, "uri"); this.scheme = uri.getScheme(); this.host = uri.getHost(); this.port = uri.getPort() == -1 ? null : uri.getPort(); if (uri.getPath() != null) path(unescapeSpecialChars(uri.getPath())); if (uri.getQuery() != null) query(queryParser().apply(unescapeSpecialChars(uri.getQuery()))); }
if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toString(from.getPayload()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); releasePayload(from); String location = from.getFirstHeaderOrNull(LOCATION); if (location == null) location = from.getFirstHeaderOrNull("location"); if (location != null) { URI locationUri = URI.create(location); if (locationUri.getHost() != null) return locationUri; checkState(request != null, "request should have been initialized"); location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { throw new HttpResponseException("no uri in headers or content", null, from);
@Test(dataProvider = "strings") public void testPath(String path) { assertEquals(uriBuilder("https://foo.com:8080").path(path).toString(), "https://foo.com:8080/" + path); assertEquals(uriBuilder("https://foo.com:8080").path(path).build().toString(), "https://foo.com:8080/" + urlEncode(path, '/', ':', ';', '=')); assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").path(path).toString(), "https://api.github.com/" + path + "?foo=bar&kung=fu"); assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").path(path).build().toString(), "https://api.github.com/" + urlEncode(path, '/', ':', ';', '=') + "?foo=bar&kung=fu"); assertEquals(uriBuilder("https://api.github.com/repos/{user}").path(path).toString(), "https://api.github.com/" + path); assertEquals(uriBuilder("https://api.github.com/repos/{user}").path(path).build(templateParams).toASCIIString(), "https://api.github.com/" + urlEncode(path, '/', ':', ';', '=')); }
public void testAddQuery() { assertEquals(uriBuilder("http://localhost:8080/client/api").addQuery("response", "json").toString(), "http://localhost:8080/client/api?response=json"); assertEquals( uriBuilder(URI.create("http://localhost:8080/client/api")).addQuery("response", "json") .addQuery("command", "queryAsyncJobResult").build().toString(), "http://localhost:8080/client/api?response=json&command=queryAsyncJobResult"); } }
private UriBuilder(URI uri) { checkNotNull(uri, "uri"); this.scheme = uri.getScheme(); this.host = uri.getHost(); this.port = uri.getPort() == -1 ? null : uri.getPort(); if (uri.getRawPath() != null) // path decodes the string, so we need to get at the raw (encoded) string path(unescapeSpecialChars(uri.getRawPath())); if (uri.getRawQuery() != null) // The query parser decodes the strings that are passed to it; we should pass raw (encoded) queries query(queryParser().apply(unescapeSpecialChars(uri.getRawQuery()))); }
@Override @SuppressWarnings("unchecked") public <R extends HttpRequest> R bindToRequest(R request, Object payload) { checkNotNull(payload, "hostprefix"); checkArgument(isValid(request.getEndpoint().getHost()), "this is only valid for hostnames: " + request); InternetDomainName name = from(request.getEndpoint().getHost()).child(payload.toString()); return (R) request.toBuilder().endpoint(uriBuilder(request.getEndpoint()).host(name.name()).build()).build(); } }
public void testHost() { assertEquals(uriBuilder("https://foo.com:8080").host("robots").toString(), "https://robots:8080"); assertEquals(uriBuilder("https://foo.com:8080").host("robots").build().toString(), "https://robots:8080"); assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").host("robots").toString(), "https://robots/repos/user?foo=bar&kung=fu"); assertEquals(uriBuilder("https://api.github.com/repos/user?foo=bar&kung=fu").host("robots").build().toString(), "https://robots/repos/user?foo=bar&kung=fu"); assertEquals(uriBuilder("https://api.github.com/repos/{user}").host("robots").toString(), "https://robots/repos/{user}"); assertEquals(uriBuilder("https://api.github.com/repos/{user}").host("robots").build(templateParams) .toASCIIString(), "https://robots/repos/bob"); }
@Test(dataProvider = "strings") public void testReplaceQueryIsEncoded(String key) { assertThat(uriBuilder("/redirect").addQuery("foo", key).build().getQuery()).isEqualTo("foo=" + key); assertThat(uriBuilder("/redirect").addQuery("foo", key).build().getRawQuery()) .isEqualTo("foo=" + urlEncode(key, '/', ',')); }
@Test(dataProvider = "strings") public void testReplaceQueryIsEncoded(String key) { assertEquals(uriBuilder("/redirect").addQuery("foo", key).toString(), "/redirect?foo=" + key); assertEquals(uriBuilder("/redirect").addQuery("foo", key).build().toString(), "/redirect?foo=" + urlEncode(key, '/', ',')); }
private HttpRequest sign(String method, String container, String name, GetOptions options, long expires) { checkNotNull(container, "container"); checkNotNull(name, "name"); URI url = Uris.uriBuilder(storageUrl).appendPath(container).appendPath(name).build(); String signature = signer.sign(method, url.getPath(), expires); return HttpRequest.builder() .method(method) .endpoint(url) .addQueryParams(options.buildQueryParameters()) .addQueryParam("temp_url_sig", signature) .addQueryParam("temp_url_expires", String.valueOf(expires)) .headers(options.buildRequestHeaders()).build(); } }
@Test public void testWhenMatrixOnPath() { assertEquals( uriBuilder("https://api.rimuhosting.com/r").appendPath("orders;include_inactive=N").build(templateParams) .toASCIIString(), "https://api.rimuhosting.com/r/orders;include_inactive=N"); }
@SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(input instanceof Multimap<?, ?>, "this binder is only valid for Multimaps!"); Multimap<String, String> pairs = (Multimap<String, String>) checkNotNull(input, "account group pairs"); checkArgument(pairs.size() > 0, "you must specify at least one account, group pair"); Multimap<String, String> existingParams = queryParser().apply(request.getEndpoint().getQuery()); Builder<String, String> map = ImmutableMultimap.<String, String> builder().putAll(existingParams); int i = 0; for (Entry<String, String> entry : pairs.entries()) map.put(String.format("usersecuritygrouplist[%d].account", i), entry.getKey()).put( String.format("usersecuritygrouplist[%d].group", i++), entry.getValue()); URI endpoint = uriBuilder(request.getEndpoint()).query(map.build()).build(); return (R) request.toBuilder().endpoint(endpoint).build(); } }
public HttpRequest filter(HttpRequest request) throws HttpException { checkNotNull(request, "request must be present"); Multimap<String, String> decodedParams = queryParser().apply(request.getEndpoint().getRawQuery()); addSigningParams(decodedParams); String stringToSign = createStringToSign(request, decodedParams); String signature = sign(stringToSign); addSignature(decodedParams, signature); request = request.toBuilder().endpoint(uriBuilder(request.getEndpoint()).query(decodedParams).build()).build(); utils.logRequest(signatureLog, request, "<<"); return request; }
@SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object recordId) { RecordId valueToAppend = RecordId.class.cast(checkNotNull(recordId, "recordId")); URI path = uriBuilder(request.getEndpoint()).appendPath("/{type}Record/{zone}/{fqdn}/{id}").build( ImmutableMap.<String, Object> builder() .put("type", valueToAppend.getType()) .put("zone", valueToAppend.getZone()) .put("fqdn", valueToAppend.getFQDN()) .put("id", valueToAppend.getId()).build()); return (R) request.toBuilder().endpoint(path).build(); } }
@Override public SwiftObject apply(InternalObject input) { if (input.subdir != null) { return SwiftObject.builder() .uri(uriBuilder(containerUri).clearQuery().appendPath(urlEncode(input.subdir)).build()) .name(input.subdir) .etag(SUBDIR_ETAG) .payload(payload(input.bytes, input.hash, "application/directory", input.expires)) .lastModified(new Date(0)).build(); } String name = Strings.nullToEmpty(input.name); String etag = Strings.nullToEmpty(input.hash); Date lastModified = input.last_modified == null ? new Date() : input.last_modified; return SwiftObject.builder() .uri(uriBuilder(containerUri).clearQuery().appendPath(urlEncode(input.name)).build()) .name(name) .etag(etag) .payload(payload(input.bytes, etag, input.content_type, input.expires)) .lastModified(lastModified).build(); } }