target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void testHostPrefix() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestVirtualHost.class, "getPrefix", String.class, String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("1", "holy"))); assertEquals(request.getEndpoint().getHost(), "holy.localhost"); assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 0); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testParseContentLengthWhenContentRangeSet() throws HttpException { ParseSystemAndUserMetadataFromHeaders metadataParser = createMock(ParseSystemAndUserMetadataFromHeaders.class); ParseBlobFromHeadersAndHttpContent callable = new ParseBlobFromHeadersAndHttpContent(metadataParser, blobProvider); HttpResponse response = HttpResponse.builder() .statusCode(200).message("ok") .payload("") .addHeader("Content-Range", "0-10485759/20232760").build(); response.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); response.getPayload().getContentMetadata().setContentLength(10485760L); MutableBlobMetadata meta = blobMetadataProvider.get(); expect(metadataParser.apply(response)).andReturn(meta); replay(metadataParser); Blob object = callable.apply(response); assertEquals(object.getPayload().getContentMetadata().getContentLength(), Long.valueOf(10485760)); assertEquals(object.getAllHeaders().get("Content-Range"), ImmutableList.of("0-10485759/20232760")); }
public Blob apply(HttpResponse from) { checkNotNull(from, "request"); MutableBlobMetadata metadata = metadataParser.apply(from); Blob blob = blobFactory.create(metadata); blob.getAllHeaders().putAll(from.getHeaders()); blob.setPayload(from.getPayload()); return blob; }
ParseBlobFromHeadersAndHttpContent implements Function<HttpResponse, Blob>, InvocationContext<ParseBlobFromHeadersAndHttpContent> { public Blob apply(HttpResponse from) { checkNotNull(from, "request"); MutableBlobMetadata metadata = metadataParser.apply(from); Blob blob = blobFactory.create(metadata); blob.getAllHeaders().putAll(from.getHeaders()); blob.setPayload(from.getPayload()); return blob; } }
ParseBlobFromHeadersAndHttpContent implements Function<HttpResponse, Blob>, InvocationContext<ParseBlobFromHeadersAndHttpContent> { public Blob apply(HttpResponse from) { checkNotNull(from, "request"); MutableBlobMetadata metadata = metadataParser.apply(from); Blob blob = blobFactory.create(metadata); blob.getAllHeaders().putAll(from.getHeaders()); blob.setPayload(from.getPayload()); return blob; } @Inject ParseBlobFromHeadersAndHttpContent(ParseSystemAndUserMetadataFromHeaders metadataParser, Blob.Factory blobFactory); }
ParseBlobFromHeadersAndHttpContent implements Function<HttpResponse, Blob>, InvocationContext<ParseBlobFromHeadersAndHttpContent> { public Blob apply(HttpResponse from) { checkNotNull(from, "request"); MutableBlobMetadata metadata = metadataParser.apply(from); Blob blob = blobFactory.create(metadata); blob.getAllHeaders().putAll(from.getHeaders()); blob.setPayload(from.getPayload()); return blob; } @Inject ParseBlobFromHeadersAndHttpContent(ParseSystemAndUserMetadataFromHeaders metadataParser, Blob.Factory blobFactory); Blob apply(HttpResponse from); @Override ParseBlobFromHeadersAndHttpContent setContext(HttpRequest request); }
ParseBlobFromHeadersAndHttpContent implements Function<HttpResponse, Blob>, InvocationContext<ParseBlobFromHeadersAndHttpContent> { public Blob apply(HttpResponse from) { checkNotNull(from, "request"); MutableBlobMetadata metadata = metadataParser.apply(from); Blob blob = blobFactory.create(metadata); blob.getAllHeaders().putAll(from.getHeaders()); blob.setPayload(from.getPayload()); return blob; } @Inject ParseBlobFromHeadersAndHttpContent(ParseSystemAndUserMetadataFromHeaders metadataParser, Blob.Factory blobFactory); Blob apply(HttpResponse from); @Override ParseBlobFromHeadersAndHttpContent setContext(HttpRequest request); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testHostPrefixEmpty() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestVirtualHost.class, "getPrefix", String.class, String.class); processor.apply(Invocation.create(method, ImmutableList.<Object> of("1", ""))); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testOneHeader() throws SecurityException, NoSuchMethodException, ExecutionException { Invokable<?, ?> method = method(TestHeaders.class, "oneHeader", String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("header"), ImmutableList.of("robot")); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testOneIntHeader() throws SecurityException, NoSuchMethodException, ExecutionException { Invokable<?, ?> method = method(TestHeaders.class, "oneIntHeader", int.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of(1))).getHeaders(); assertEquals(headers.size(), 1); assertEquals(headers.get("header"), ImmutableList.of("1")); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testTwoDifferentHeaders() throws SecurityException, NoSuchMethodException, ExecutionException { Invokable<?, ?> method = method(TestHeaders.class, "twoDifferentHeaders", String.class, String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot", "egg"))).getHeaders(); assertEquals(headers.size(), 2); assertEquals(headers.get("header1"), ImmutableList.of("robot")); assertEquals(headers.get("header2"), ImmutableList.of("egg")); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testTwoSameHeaders() throws SecurityException, NoSuchMethodException, ExecutionException { Invokable<?, ?> method = method(TestHeaders.class, "twoSameHeaders", String.class, String.class); Multimap<String, String> headers = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot", "egg"))).getHeaders(); assertEquals(headers.size(), 2); Collection<String> values = headers.get("header"); assert values.contains("robot"); assert values.contains("egg"); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testOneEndpointParam() throws SecurityException, NoSuchMethodException, ExecutionException { Invokable<?, ?> method = method(TestEndpointParams.class, "oneEndpointParam", String.class); URI uri = RestAnnotationProcessor.getEndpointInParametersOrNull( Invocation.create(method, ImmutableList.<Object> of("robot")), injector); assertEquals(uri, URI.create("robot")); }
@VisibleForTesting static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) { Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class); if (endpointParams.isEmpty()) return null; checkState(endpointParams.size() == 1, "invocation.getInvoked() %s has too many EndpointParam annotations", invocation.getInvokable()); Parameter endpointParam = get(endpointParams, 0); Function<Object, URI> parser = injector.getInstance(endpointParam.getAnnotation(EndpointParam.class).parser()); int position = endpointParam.hashCode(); try { URI returnVal = parser.apply(invocation.getArgs().get(position)); checkArgument(returnVal != null, "endpoint for [%s] not configured for %s", position, invocation.getInvokable()); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(format("argument at index %d on invocation.getInvoked() %s was null", position, invocation.getInvokable()), e); } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) { Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class); if (endpointParams.isEmpty()) return null; checkState(endpointParams.size() == 1, "invocation.getInvoked() %s has too many EndpointParam annotations", invocation.getInvokable()); Parameter endpointParam = get(endpointParams, 0); Function<Object, URI> parser = injector.getInstance(endpointParam.getAnnotation(EndpointParam.class).parser()); int position = endpointParam.hashCode(); try { URI returnVal = parser.apply(invocation.getArgs().get(position)); checkArgument(returnVal != null, "endpoint for [%s] not configured for %s", position, invocation.getInvokable()); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(format("argument at index %d on invocation.getInvoked() %s was null", position, invocation.getInvokable()), e); } } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) { Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class); if (endpointParams.isEmpty()) return null; checkState(endpointParams.size() == 1, "invocation.getInvoked() %s has too many EndpointParam annotations", invocation.getInvokable()); Parameter endpointParam = get(endpointParams, 0); Function<Object, URI> parser = injector.getInstance(endpointParam.getAnnotation(EndpointParam.class).parser()); int position = endpointParam.hashCode(); try { URI returnVal = parser.apply(invocation.getArgs().get(position)); checkArgument(returnVal != null, "endpoint for [%s] not configured for %s", position, invocation.getInvokable()); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(format("argument at index %d on invocation.getInvoked() %s was null", position, invocation.getInvokable()), e); } } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) { Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class); if (endpointParams.isEmpty()) return null; checkState(endpointParams.size() == 1, "invocation.getInvoked() %s has too many EndpointParam annotations", invocation.getInvokable()); Parameter endpointParam = get(endpointParams, 0); Function<Object, URI> parser = injector.getInstance(endpointParam.getAnnotation(EndpointParam.class).parser()); int position = endpointParam.hashCode(); try { URI returnVal = parser.apply(invocation.getArgs().get(position)); checkArgument(returnVal != null, "endpoint for [%s] not configured for %s", position, invocation.getInvokable()); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(format("argument at index %d on invocation.getInvoked() %s was null", position, invocation.getInvokable()), e); } } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) { Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class); if (endpointParams.isEmpty()) return null; checkState(endpointParams.size() == 1, "invocation.getInvoked() %s has too many EndpointParam annotations", invocation.getInvokable()); Parameter endpointParam = get(endpointParams, 0); Function<Object, URI> parser = injector.getInstance(endpointParam.getAnnotation(EndpointParam.class).parser()); int position = endpointParam.hashCode(); try { URI returnVal = parser.apply(invocation.getArgs().get(position)); checkArgument(returnVal != null, "endpoint for [%s] not configured for %s", position, invocation.getInvokable()); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(format("argument at index %d on invocation.getInvoked() %s was null", position, invocation.getInvokable()), e); } } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test(expectedExceptions = IllegalStateException.class) public void testTwoDifferentEndpointParams() throws SecurityException, NoSuchMethodException, ExecutionException { Invokable<?, ?> method = method(TestEndpointParams.class, "twoEndpointParams", String.class, String.class); RestAnnotationProcessor.getEndpointInParametersOrNull( Invocation.create(method, ImmutableList.<Object> of("robot", "egg")), injector); }
@VisibleForTesting static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) { Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class); if (endpointParams.isEmpty()) return null; checkState(endpointParams.size() == 1, "invocation.getInvoked() %s has too many EndpointParam annotations", invocation.getInvokable()); Parameter endpointParam = get(endpointParams, 0); Function<Object, URI> parser = injector.getInstance(endpointParam.getAnnotation(EndpointParam.class).parser()); int position = endpointParam.hashCode(); try { URI returnVal = parser.apply(invocation.getArgs().get(position)); checkArgument(returnVal != null, "endpoint for [%s] not configured for %s", position, invocation.getInvokable()); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(format("argument at index %d on invocation.getInvoked() %s was null", position, invocation.getInvokable()), e); } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) { Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class); if (endpointParams.isEmpty()) return null; checkState(endpointParams.size() == 1, "invocation.getInvoked() %s has too many EndpointParam annotations", invocation.getInvokable()); Parameter endpointParam = get(endpointParams, 0); Function<Object, URI> parser = injector.getInstance(endpointParam.getAnnotation(EndpointParam.class).parser()); int position = endpointParam.hashCode(); try { URI returnVal = parser.apply(invocation.getArgs().get(position)); checkArgument(returnVal != null, "endpoint for [%s] not configured for %s", position, invocation.getInvokable()); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(format("argument at index %d on invocation.getInvoked() %s was null", position, invocation.getInvokable()), e); } } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) { Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class); if (endpointParams.isEmpty()) return null; checkState(endpointParams.size() == 1, "invocation.getInvoked() %s has too many EndpointParam annotations", invocation.getInvokable()); Parameter endpointParam = get(endpointParams, 0); Function<Object, URI> parser = injector.getInstance(endpointParam.getAnnotation(EndpointParam.class).parser()); int position = endpointParam.hashCode(); try { URI returnVal = parser.apply(invocation.getArgs().get(position)); checkArgument(returnVal != null, "endpoint for [%s] not configured for %s", position, invocation.getInvokable()); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(format("argument at index %d on invocation.getInvoked() %s was null", position, invocation.getInvokable()), e); } } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) { Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class); if (endpointParams.isEmpty()) return null; checkState(endpointParams.size() == 1, "invocation.getInvoked() %s has too many EndpointParam annotations", invocation.getInvokable()); Parameter endpointParam = get(endpointParams, 0); Function<Object, URI> parser = injector.getInstance(endpointParam.getAnnotation(EndpointParam.class).parser()); int position = endpointParam.hashCode(); try { URI returnVal = parser.apply(invocation.getArgs().get(position)); checkArgument(returnVal != null, "endpoint for [%s] not configured for %s", position, invocation.getInvokable()); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(format("argument at index %d on invocation.getInvoked() %s was null", position, invocation.getInvokable()), e); } } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) { Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class); if (endpointParams.isEmpty()) return null; checkState(endpointParams.size() == 1, "invocation.getInvoked() %s has too many EndpointParam annotations", invocation.getInvokable()); Parameter endpointParam = get(endpointParams, 0); Function<Object, URI> parser = injector.getInstance(endpointParam.getAnnotation(EndpointParam.class).parser()); int position = endpointParam.hashCode(); try { URI returnVal = parser.apply(invocation.getArgs().get(position)); checkArgument(returnVal != null, "endpoint for [%s] not configured for %s", position, invocation.getInvokable()); return returnVal; } catch (NullPointerException e) { throw new IllegalArgumentException(format("argument at index %d on invocation.getInvoked() %s was null", position, invocation.getInvokable()), e); } } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testPut() throws Exception { Invokable<?, ?> method = method(TestPayload.class, "put", String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("test"))); assertRequestLineEquals(request, "PUT http: assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "test", "application/unknown", false); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void putWithPath() throws Exception { Invokable<?, ?> method = method(TestPayload.class, "putWithPath", String.class, String.class); GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of("rabble", "test"))); assertRequestLineEquals(request, "PUT http: assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "test", "application/unknown", false); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testBuildTwoForm() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestFormReplace.class, "twoForm", String.class); Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))) .getPayload().getRawContent(); assertEquals(form, "slash=/robot&hyphen=-robot"); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testApplySetsName() { HttpResponse from = HttpResponse.builder() .statusCode(200).message("ok") .payload("") .addHeader(HttpHeaders.LAST_MODIFIED, "Wed, 09 Sep 2009 19:50:23 GMT").build(); from.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON); from.getPayload().getContentMetadata().setContentLength(100L); BlobMetadata metadata = parser.apply(from); assertEquals(metadata.getName(), "key"); }
public MutableBlobMetadata apply(HttpResponse from) { checkNotNull(from, "request"); checkState(name != null, "name must be initialized by now"); MutableBlobMetadata to = metadataFactory.get(); to.setName(name); to.setUri(endpoint); if (from.getPayload() != null) HttpUtils.copy(from.getPayload().getContentMetadata(), to.getContentMetadata()); addETagTo(from, to); parseLastModifiedOrThrowException(from, to); addUserMetadataTo(from, to); return to; }
ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>, InvocationContext<ParseSystemAndUserMetadataFromHeaders> { public MutableBlobMetadata apply(HttpResponse from) { checkNotNull(from, "request"); checkState(name != null, "name must be initialized by now"); MutableBlobMetadata to = metadataFactory.get(); to.setName(name); to.setUri(endpoint); if (from.getPayload() != null) HttpUtils.copy(from.getPayload().getContentMetadata(), to.getContentMetadata()); addETagTo(from, to); parseLastModifiedOrThrowException(from, to); addUserMetadataTo(from, to); return to; } }
ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>, InvocationContext<ParseSystemAndUserMetadataFromHeaders> { public MutableBlobMetadata apply(HttpResponse from) { checkNotNull(from, "request"); checkState(name != null, "name must be initialized by now"); MutableBlobMetadata to = metadataFactory.get(); to.setName(name); to.setUri(endpoint); if (from.getPayload() != null) HttpUtils.copy(from.getPayload().getContentMetadata(), to.getContentMetadata()); addETagTo(from, to); parseLastModifiedOrThrowException(from, to); addUserMetadataTo(from, to); return to; } @Inject ParseSystemAndUserMetadataFromHeaders(Provider<MutableBlobMetadata> metadataFactory, DateService dateParser, @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); }
ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>, InvocationContext<ParseSystemAndUserMetadataFromHeaders> { public MutableBlobMetadata apply(HttpResponse from) { checkNotNull(from, "request"); checkState(name != null, "name must be initialized by now"); MutableBlobMetadata to = metadataFactory.get(); to.setName(name); to.setUri(endpoint); if (from.getPayload() != null) HttpUtils.copy(from.getPayload().getContentMetadata(), to.getContentMetadata()); addETagTo(from, to); parseLastModifiedOrThrowException(from, to); addUserMetadataTo(from, to); return to; } @Inject ParseSystemAndUserMetadataFromHeaders(Provider<MutableBlobMetadata> metadataFactory, DateService dateParser, @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); MutableBlobMetadata apply(HttpResponse from); ParseSystemAndUserMetadataFromHeaders setContext(HttpRequest request); ParseSystemAndUserMetadataFromHeaders setName(String name); }
ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>, InvocationContext<ParseSystemAndUserMetadataFromHeaders> { public MutableBlobMetadata apply(HttpResponse from) { checkNotNull(from, "request"); checkState(name != null, "name must be initialized by now"); MutableBlobMetadata to = metadataFactory.get(); to.setName(name); to.setUri(endpoint); if (from.getPayload() != null) HttpUtils.copy(from.getPayload().getContentMetadata(), to.getContentMetadata()); addETagTo(from, to); parseLastModifiedOrThrowException(from, to); addUserMetadataTo(from, to); return to; } @Inject ParseSystemAndUserMetadataFromHeaders(Provider<MutableBlobMetadata> metadataFactory, DateService dateParser, @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); MutableBlobMetadata apply(HttpResponse from); ParseSystemAndUserMetadataFromHeaders setContext(HttpRequest request); ParseSystemAndUserMetadataFromHeaders setName(String name); }
@Test public void testBuildOneClassForm() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestClassForm.class, "oneForm", String.class); Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))) .getPayload().getRawContent(); assertEquals(form, "x-amz-copy-source=/robot"); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testBuildOneForm() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestFormReplace.class, "oneForm", String.class); Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot"))) .getPayload().getRawContent(); assertEquals(form, "x-amz-copy-source=/robot"); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testBuildTwoForms() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestFormReplace.class, "twoForms", String.class, String.class); Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot", "eggs"))) .getPayload().getRawContent(); assertEquals(form, "x-amz-copy-source=/robot/eggs"); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testBuildTwoFormsOutOfOrder() throws SecurityException, NoSuchMethodException { Invokable<?, ?> method = method(TestFormReplace.class, "twoFormsOutOfOrder", String.class, String.class); Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot", "eggs"))) .getPayload().getRawContent(); assertEquals(form, "x-amz-copy-source=/eggs/robot"); }
@Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @Override public GeneratedHttpRequest apply(Invocation invocation) { checkNotNull(invocation, "invocation"); inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable())); Optional<URI> endpoint = Optional.absent(); HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class); if (r != null) { endpoint = Optional.fromNullable(r.getEndpoint()); if (endpoint.isPresent()) logger.trace("using endpoint %s from invocation.getArgs() for %s", endpoint, invocation); } else { endpoint = getEndpointFor(invocation); if (!endpoint.isPresent()) { if (caller != null) { endpoint = getEndpointFor(caller); if (endpoint.isPresent()) logger.trace("using endpoint %s from caller %s for %s", endpoint, caller, invocation); else endpoint = findEndpoint(invocation); } else { endpoint = findEndpoint(invocation); } } } if (!endpoint.isPresent()) throw new NoSuchElementException(format("no endpoint found for %s", invocation)); GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation) .caller(caller); String requestMethod = null; if (r != null) { requestMethod = r.getMethod(); requestBuilder.fromHttpRequest(r); } else { requestMethod = tryFindHttpMethod(invocation.getInvokable()).get(); requestBuilder.method(requestMethod); } requestBuilder.filters(getFiltersIfAnnotated(invocation)); if (stripExpectHeader) { requestBuilder.filter(new StripExpectHeader()); } if (connectionCloseHeader) { requestBuilder.filter(new ConnectionCloseHeader()); } Multimap<String, Object> tokenValues = LinkedHashMultimap.create(); tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity); tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion); tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion); UriBuilder uriBuilder = uriBuilder(endpoint.get().toString()); overridePathEncoding(uriBuilder, invocation); boolean encodeFullPath = !isEncodedUsed(invocation); if (caller != null) tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath)); tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath)); Multimap<String, Object> formParams; if (caller != null) { formParams = addFormParams(tokenValues, caller); formParams.putAll(addFormParams(tokenValues, invocation)); } else { formParams = addFormParams(tokenValues, invocation); } Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation); Multimap<String, String> headers; if (caller != null) { headers = buildHeaders(tokenValues, caller); headers.putAll(buildHeaders(tokenValues, invocation)); } else { headers = buildHeaders(tokenValues, invocation); } if (r != null) headers.putAll(r.getHeaders()); if (shouldAddHostHeader(invocation)) { StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost()); if (endpoint.get().getPort() != -1) hostHeader.append(":").append(endpoint.get().getPort()); headers.put(HOST, hostHeader.toString()); } Payload payload = null; for (HttpRequestOptions options : findOptionsIn(invocation)) { injector.injectMembers(options); for (Entry<String, String> header : options.buildRequestHeaders().entries()) { headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues)); } for (Entry<String, String> query : options.buildQueryParameters().entries()) { queryParams.put(urlEncode(query.getKey(), '/', ','), new QueryValue(replaceTokens(query.getValue(), tokenValues), false)); } for (Entry<String, String> form : options.buildFormParameters().entries()) { formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues)); } String pathSuffix = options.buildPathSuffix(); if (pathSuffix != null) { uriBuilder.appendPath(pathSuffix); } String stringPayload = options.buildStringPayload(); if (stringPayload != null) payload = Payloads.newStringPayload(stringPayload); } if (!queryParams.isEmpty()) { uriBuilder.query(queryParams); } requestBuilder.headers(filterOutContentHeaders(headers)); requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), encodeFullPath)); if (payload == null) { PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class); payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(), Payload.class); } List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder() .putAll(tokenValues).putAll(formParams).build()); if (!parts.isEmpty()) { if (!formParams.isEmpty()) { parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts)); } payload = new MultipartForm(MultipartForm.BOUNDARY, parts); } else if (!formParams.isEmpty()) { payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE)); } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) { if (payload == null) payload = Payloads.newByteArrayPayload(new byte[] {}); payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0)); } if (payload != null) { requestBuilder.payload(payload); } GeneratedHttpRequest request = requestBuilder.build(); org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation); if (mapBinder != null) { Map<String, Object> mapParams; if (caller != null) { mapParams = buildPayloadParams(caller); mapParams.putAll(buildPayloadParams(invocation)); } else { mapParams = buildPayloadParams(invocation); } if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) { PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class); addMapPayload(mapParams, params, headers, tokenValues); } request = mapBinder.bindToRequest(request, mapParams); } else { request = decorateRequest(request); } if (request.getPayload() != null) { contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers); } request = stripExpectHeaderIfContentZero(request); utils.checkRequestHasRequiredProperties(request); return request; } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test(expectedExceptions = NullPointerException.class) public void testAddHostNullWithHost() throws Exception { assertNull(RestAnnotationProcessor.addHostIfMissing(null, null)); }
@VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testAddHostWithHostHasNoHost() throws Exception { assertNull(RestAnnotationProcessor.addHostIfMissing(null, new URI("/no/host"))); }
@VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testAddHostNullOriginal() throws Exception { assertNull(RestAnnotationProcessor.addHostIfMissing(null, new URI("http: }
@VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testAddHostOriginalHasHost() throws Exception { URI original = new URI("http: URI result = RestAnnotationProcessor.addHostIfMissing(original, new URI("http: assertEquals(original, result); }
@VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testAddHostIfMissing() throws Exception { URI result = RestAnnotationProcessor.addHostIfMissing(new URI("/bar"), new URI("http: assertEquals(new URI("http: }
@VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test public void testComplexHost() throws Exception { URI result = RestAnnotationProcessor.addHostIfMissing(new URI("bar"), new URI("http: assertEquals(new URI("http: }
@VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
RestAnnotationProcessor implements Function<Invocation, HttpRequest> { @VisibleForTesting static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); } @Inject private RestAnnotationProcessor(Injector injector, @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator, GetAcceptHeaders getAcceptHeaders, @Nullable @Named("caller") Invocation caller, @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader, @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader); @Deprecated GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args); @Override GeneratedHttpRequest apply(Invocation invocation); @Override String toString(); }
@Test(expectedExceptions = ClassCastException.class) public void testWrongPredicateTypeLiteral() throws Exception { Invocation invocation = Invocation.create(method(WrongValidator.class, "method", Integer.class), ImmutableList.<Object> of(55)); new InputParamValidator(injector).validateMethodParametersOrThrow(invocation, invocation.getInvokable().getParameters()); }
public void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters) { try { performMethodValidation(checkNotNull(invocation, "invocation")); performParameterValidation(invocation, checkNotNull(parameters, "parameters")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("Validation on '%s' didn't pass:%n Reason: %s.", parameters, e.getMessage()), e); } }
InputParamValidator { public void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters) { try { performMethodValidation(checkNotNull(invocation, "invocation")); performParameterValidation(invocation, checkNotNull(parameters, "parameters")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("Validation on '%s' didn't pass:%n Reason: %s.", parameters, e.getMessage()), e); } } }
InputParamValidator { public void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters) { try { performMethodValidation(checkNotNull(invocation, "invocation")); performParameterValidation(invocation, checkNotNull(parameters, "parameters")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("Validation on '%s' didn't pass:%n Reason: %s.", parameters, e.getMessage()), e); } } @Inject InputParamValidator(Injector injector); InputParamValidator(); }
InputParamValidator { public void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters) { try { performMethodValidation(checkNotNull(invocation, "invocation")); performParameterValidation(invocation, checkNotNull(parameters, "parameters")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("Validation on '%s' didn't pass:%n Reason: %s.", parameters, e.getMessage()), e); } } @Inject InputParamValidator(Injector injector); InputParamValidator(); void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters); }
InputParamValidator { public void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters) { try { performMethodValidation(checkNotNull(invocation, "invocation")); performParameterValidation(invocation, checkNotNull(parameters, "parameters")); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("Validation on '%s' didn't pass:%n Reason: %s.", parameters, e.getMessage()), e); } } @Inject InputParamValidator(Injector injector); InputParamValidator(); void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters); }
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "^Invalid PEM: no parsers for marker -----BEGIN FOO PRIVATE KEY----- .*") public void testPrivateKeySpecFromPemWithInvalidMarker() throws IOException { Pems.privateKeySpec(ByteSource.wrap(INVALID_PRIVATE_KEY.getBytes(Charsets.UTF_8))); }
public static KeySpec privateKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of( PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public KeySpec parseResult(byte[] bytes) throws IOException { return new PKCS8EncodedKeySpec(bytes); } }))); }
Pems { public static KeySpec privateKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of( PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public KeySpec parseResult(byte[] bytes) throws IOException { return new PKCS8EncodedKeySpec(bytes); } }))); } }
Pems { public static KeySpec privateKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of( PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public KeySpec parseResult(byte[] bytes) throws IOException { return new PKCS8EncodedKeySpec(bytes); } }))); } }
Pems { public static KeySpec privateKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of( PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public KeySpec parseResult(byte[] bytes) throws IOException { return new PKCS8EncodedKeySpec(bytes); } }))); } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); }
Pems { public static KeySpec privateKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of( PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public KeySpec parseResult(byte[] bytes) throws IOException { return new PKCS8EncodedKeySpec(bytes); } }))); } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); static final String PRIVATE_PKCS1_MARKER; static final String PRIVATE_PKCS8_MARKER; static final String CERTIFICATE_X509_MARKER; static final String PUBLIC_X509_MARKER; static final String PUBLIC_PKCS1_MARKER; static final String PROC_TYPE_ENCRYPTED; }
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "^Invalid PEM: no parsers for marker -----BEGIN FOO PUBLIC KEY----- .*") public void testPublicKeySpecFromPemWithInvalidMarker() throws IOException { Pems.publicKeySpec(ByteSource.wrap(INVALID_PUBLIC_KEY.getBytes(Charsets.UTF_8))); }
public static KeySpec publicKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER, DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException { return new X509EncodedKeySpec(bytes); } }))); }
Pems { public static KeySpec publicKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER, DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException { return new X509EncodedKeySpec(bytes); } }))); } }
Pems { public static KeySpec publicKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER, DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException { return new X509EncodedKeySpec(bytes); } }))); } }
Pems { public static KeySpec publicKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER, DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException { return new X509EncodedKeySpec(bytes); } }))); } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); }
Pems { public static KeySpec publicKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER, DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException { return new X509EncodedKeySpec(bytes); } }))); } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); static final String PRIVATE_PKCS1_MARKER; static final String PRIVATE_PKCS8_MARKER; static final String CERTIFICATE_X509_MARKER; static final String PUBLIC_X509_MARKER; static final String PUBLIC_PKCS1_MARKER; static final String PROC_TYPE_ENCRYPTED; }
@Test public void testPrivateKeySpecFromPem() throws IOException { Pems.privateKeySpec(ByteSource.wrap(PRIVATE_KEY.getBytes(Charsets.UTF_8))); }
public static KeySpec privateKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of( PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public KeySpec parseResult(byte[] bytes) throws IOException { return new PKCS8EncodedKeySpec(bytes); } }))); }
Pems { public static KeySpec privateKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of( PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public KeySpec parseResult(byte[] bytes) throws IOException { return new PKCS8EncodedKeySpec(bytes); } }))); } }
Pems { public static KeySpec privateKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of( PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public KeySpec parseResult(byte[] bytes) throws IOException { return new PKCS8EncodedKeySpec(bytes); } }))); } }
Pems { public static KeySpec privateKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of( PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public KeySpec parseResult(byte[] bytes) throws IOException { return new PKCS8EncodedKeySpec(bytes); } }))); } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); }
Pems { public static KeySpec privateKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of( PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public KeySpec parseResult(byte[] bytes) throws IOException { return new PKCS8EncodedKeySpec(bytes); } }))); } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); static final String PRIVATE_PKCS1_MARKER; static final String PRIVATE_PKCS8_MARKER; static final String CERTIFICATE_X509_MARKER; static final String PUBLIC_X509_MARKER; static final String PUBLIC_PKCS1_MARKER; static final String PROC_TYPE_ENCRYPTED; }
@Test public void testPublicKeySpecFromPem() throws IOException { Pems.publicKeySpec(ByteSource.wrap(PUBLIC_KEY.getBytes(Charsets.UTF_8))); }
public static KeySpec publicKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER, DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException { return new X509EncodedKeySpec(bytes); } }))); }
Pems { public static KeySpec publicKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER, DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException { return new X509EncodedKeySpec(bytes); } }))); } }
Pems { public static KeySpec publicKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER, DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException { return new X509EncodedKeySpec(bytes); } }))); } }
Pems { public static KeySpec publicKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER, DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException { return new X509EncodedKeySpec(bytes); } }))); } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); }
Pems { public static KeySpec publicKeySpec(ByteSource supplier) throws IOException { return fromPem( supplier, new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER, DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() { @Override public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException { return new X509EncodedKeySpec(bytes); } }))); } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); static final String PRIVATE_PKCS1_MARKER; static final String PRIVATE_PKCS8_MARKER; static final String CERTIFICATE_X509_MARKER; static final String PUBLIC_X509_MARKER; static final String PUBLIC_PKCS1_MARKER; static final String PROC_TYPE_ENCRYPTED; }
@Test public void testX509CertificateFromPemDefault() throws IOException, CertificateException { Pems.x509Certificate(ByteSource.wrap(CERTIFICATE.getBytes(Charsets.UTF_8)), null); }
public static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory) throws IOException, CertificateException { final CertificateFactory certs = certFactory != null ? certFactory : CertificateFactory.getInstance("X.509"); try { return fromPem( supplier, new PemProcessor<X509Certificate>(ImmutableMap.<String, PemProcessor.ResultParser<X509Certificate>> of( CERTIFICATE_X509_MARKER, new PemProcessor.ResultParser<X509Certificate>() { @Override public X509Certificate parseResult(byte[] bytes) throws IOException { try { return (X509Certificate) certs.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new RuntimeException(e); } } }))); } catch (RuntimeException e) { propagateIfInstanceOf(e.getCause(), CertificateException.class); throw e; } }
Pems { public static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory) throws IOException, CertificateException { final CertificateFactory certs = certFactory != null ? certFactory : CertificateFactory.getInstance("X.509"); try { return fromPem( supplier, new PemProcessor<X509Certificate>(ImmutableMap.<String, PemProcessor.ResultParser<X509Certificate>> of( CERTIFICATE_X509_MARKER, new PemProcessor.ResultParser<X509Certificate>() { @Override public X509Certificate parseResult(byte[] bytes) throws IOException { try { return (X509Certificate) certs.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new RuntimeException(e); } } }))); } catch (RuntimeException e) { propagateIfInstanceOf(e.getCause(), CertificateException.class); throw e; } } }
Pems { public static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory) throws IOException, CertificateException { final CertificateFactory certs = certFactory != null ? certFactory : CertificateFactory.getInstance("X.509"); try { return fromPem( supplier, new PemProcessor<X509Certificate>(ImmutableMap.<String, PemProcessor.ResultParser<X509Certificate>> of( CERTIFICATE_X509_MARKER, new PemProcessor.ResultParser<X509Certificate>() { @Override public X509Certificate parseResult(byte[] bytes) throws IOException { try { return (X509Certificate) certs.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new RuntimeException(e); } } }))); } catch (RuntimeException e) { propagateIfInstanceOf(e.getCause(), CertificateException.class); throw e; } } }
Pems { public static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory) throws IOException, CertificateException { final CertificateFactory certs = certFactory != null ? certFactory : CertificateFactory.getInstance("X.509"); try { return fromPem( supplier, new PemProcessor<X509Certificate>(ImmutableMap.<String, PemProcessor.ResultParser<X509Certificate>> of( CERTIFICATE_X509_MARKER, new PemProcessor.ResultParser<X509Certificate>() { @Override public X509Certificate parseResult(byte[] bytes) throws IOException { try { return (X509Certificate) certs.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new RuntimeException(e); } } }))); } catch (RuntimeException e) { propagateIfInstanceOf(e.getCause(), CertificateException.class); throw e; } } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); }
Pems { public static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory) throws IOException, CertificateException { final CertificateFactory certs = certFactory != null ? certFactory : CertificateFactory.getInstance("X.509"); try { return fromPem( supplier, new PemProcessor<X509Certificate>(ImmutableMap.<String, PemProcessor.ResultParser<X509Certificate>> of( CERTIFICATE_X509_MARKER, new PemProcessor.ResultParser<X509Certificate>() { @Override public X509Certificate parseResult(byte[] bytes) throws IOException { try { return (X509Certificate) certs.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new RuntimeException(e); } } }))); } catch (RuntimeException e) { propagateIfInstanceOf(e.getCause(), CertificateException.class); throw e; } } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); static final String PRIVATE_PKCS1_MARKER; static final String PRIVATE_PKCS8_MARKER; static final String CERTIFICATE_X509_MARKER; static final String PUBLIC_X509_MARKER; static final String PUBLIC_PKCS1_MARKER; static final String PROC_TYPE_ENCRYPTED; }
@Test public void testX509CertificateFromPemSuppliedCertFactory() throws IOException, CertificateException { Pems.x509Certificate(ByteSource.wrap(CERTIFICATE.getBytes(Charsets.UTF_8)), CertificateFactory.getInstance("X.509")); }
public static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory) throws IOException, CertificateException { final CertificateFactory certs = certFactory != null ? certFactory : CertificateFactory.getInstance("X.509"); try { return fromPem( supplier, new PemProcessor<X509Certificate>(ImmutableMap.<String, PemProcessor.ResultParser<X509Certificate>> of( CERTIFICATE_X509_MARKER, new PemProcessor.ResultParser<X509Certificate>() { @Override public X509Certificate parseResult(byte[] bytes) throws IOException { try { return (X509Certificate) certs.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new RuntimeException(e); } } }))); } catch (RuntimeException e) { propagateIfInstanceOf(e.getCause(), CertificateException.class); throw e; } }
Pems { public static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory) throws IOException, CertificateException { final CertificateFactory certs = certFactory != null ? certFactory : CertificateFactory.getInstance("X.509"); try { return fromPem( supplier, new PemProcessor<X509Certificate>(ImmutableMap.<String, PemProcessor.ResultParser<X509Certificate>> of( CERTIFICATE_X509_MARKER, new PemProcessor.ResultParser<X509Certificate>() { @Override public X509Certificate parseResult(byte[] bytes) throws IOException { try { return (X509Certificate) certs.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new RuntimeException(e); } } }))); } catch (RuntimeException e) { propagateIfInstanceOf(e.getCause(), CertificateException.class); throw e; } } }
Pems { public static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory) throws IOException, CertificateException { final CertificateFactory certs = certFactory != null ? certFactory : CertificateFactory.getInstance("X.509"); try { return fromPem( supplier, new PemProcessor<X509Certificate>(ImmutableMap.<String, PemProcessor.ResultParser<X509Certificate>> of( CERTIFICATE_X509_MARKER, new PemProcessor.ResultParser<X509Certificate>() { @Override public X509Certificate parseResult(byte[] bytes) throws IOException { try { return (X509Certificate) certs.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new RuntimeException(e); } } }))); } catch (RuntimeException e) { propagateIfInstanceOf(e.getCause(), CertificateException.class); throw e; } } }
Pems { public static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory) throws IOException, CertificateException { final CertificateFactory certs = certFactory != null ? certFactory : CertificateFactory.getInstance("X.509"); try { return fromPem( supplier, new PemProcessor<X509Certificate>(ImmutableMap.<String, PemProcessor.ResultParser<X509Certificate>> of( CERTIFICATE_X509_MARKER, new PemProcessor.ResultParser<X509Certificate>() { @Override public X509Certificate parseResult(byte[] bytes) throws IOException { try { return (X509Certificate) certs.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new RuntimeException(e); } } }))); } catch (RuntimeException e) { propagateIfInstanceOf(e.getCause(), CertificateException.class); throw e; } } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); }
Pems { public static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory) throws IOException, CertificateException { final CertificateFactory certs = certFactory != null ? certFactory : CertificateFactory.getInstance("X.509"); try { return fromPem( supplier, new PemProcessor<X509Certificate>(ImmutableMap.<String, PemProcessor.ResultParser<X509Certificate>> of( CERTIFICATE_X509_MARKER, new PemProcessor.ResultParser<X509Certificate>() { @Override public X509Certificate parseResult(byte[] bytes) throws IOException { try { return (X509Certificate) certs.generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new RuntimeException(e); } } }))); } catch (RuntimeException e) { propagateIfInstanceOf(e.getCause(), CertificateException.class); throw e; } } static T fromPem(ByteSource supplier, PemProcessor<T> processor); static KeySpec privateKeySpec(ByteSource supplier); static KeySpec privateKeySpec(String pem); static KeySpec publicKeySpec(ByteSource supplier); static KeySpec publicKeySpec(String pem); static X509Certificate x509Certificate(ByteSource supplier, @Nullable CertificateFactory certFactory); static X509Certificate x509Certificate(String pem); static String pem(X509Certificate cert); static String pem(PublicKey key); static String pem(PrivateKey key); static final String PRIVATE_PKCS1_MARKER; static final String PRIVATE_PKCS8_MARKER; static final String CERTIFICATE_X509_MARKER; static final String PUBLIC_X509_MARKER; static final String PUBLIC_PKCS1_MARKER; static final String PROC_TYPE_ENCRYPTED; }
@Test void testExponentialBackoffDelayDefaultMaxInterval500() throws InterruptedException { long period = 500; long acceptableDelay = period - 1; long startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 1, 5, "TEST FAILURE: 1"); long elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period, period + acceptableDelay); startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 2, 5, "TEST FAILURE: 2"); elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period * 4, period * 9); startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 3, 5, "TEST FAILURE: 3"); elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period * 9, period * 10); startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 4, 5, "TEST FAILURE: 4"); elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period * 10, period * 11); startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 5, 5, "TEST FAILURE: 5"); elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period * 10, period * 11); }
public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(int failureCount, String commandDescription); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max, String commandDescription); }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(int failureCount, String commandDescription); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max, String commandDescription); static final BackoffLimitedRetryHandler INSTANCE; }
@Test(enabled = false) void testExponentialBackoffDelaySmallInterval5() throws InterruptedException { long period = 5; long acceptableDelay = period - 1; long startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 1, 5, "TEST FAILURE: 1"); long elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period, period + acceptableDelay); }
public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(int failureCount, String commandDescription); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max, String commandDescription); }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(int failureCount, String commandDescription); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max, String commandDescription); static final BackoffLimitedRetryHandler INSTANCE; }
@Test(enabled = false) void testExponentialBackoffDelaySmallInterval1() throws InterruptedException { long period = 1; long acceptableDelay = 5; long startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 1, 5, "TEST FAILURE: 1"); long elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period, period + acceptableDelay); }
public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(int failureCount, String commandDescription); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max, String commandDescription); }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(int failureCount, String commandDescription); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max, String commandDescription); static final BackoffLimitedRetryHandler INSTANCE; }
@Test void testExponentialBackoffDelaySmallInterval0() throws InterruptedException { long period = 0; long acceptableDelay = 5; long startTime = System.nanoTime(); handler.imposeBackoffExponentialDelay(period, 2, 1, 5, "TEST FAILURE: 1"); long elapsedTime = (System.nanoTime() - startTime) / 1000000; assertThat(elapsedTime).isBetween(period, period + acceptableDelay); }
public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(int failureCount, String commandDescription); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max, String commandDescription); }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) { imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(int failureCount, String commandDescription); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max, String commandDescription); static final BackoffLimitedRetryHandler INSTANCE; }
@Test void testInputStreamIsNotClosed() throws SecurityException, NoSuchMethodException, IOException { HttpCommand command = createCommand(); HttpResponse response = HttpResponse.builder().statusCode(500).build(); InputStream inputStream = new InputStream() { int count = 2; @Override public void close() { fail("The retry handler should not close the response stream"); } @Override public int read() throws IOException { return count < 0 ? -1 : --count; } @Override public int available() throws IOException { return count < 0 ? 0 : count; } }; response.setPayload(Payloads.newInputStreamPayload(inputStream)); response.getPayload().getContentMetadata().setContentLength(1L); assertEquals(response.getPayload().openStream().available(), 2); assertEquals(response.getPayload().openStream().read(), 1); handler.shouldRetryRequest(command, response); assertEquals(response.getPayload().openStream().available(), 1); assertEquals(response.getPayload().openStream().read(), 0); }
public boolean shouldRetryRequest(HttpCommand command, IOException error) { return ifReplayableBackoffAndReturnTrue(command); }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public boolean shouldRetryRequest(HttpCommand command, IOException error) { return ifReplayableBackoffAndReturnTrue(command); } }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public boolean shouldRetryRequest(HttpCommand command, IOException error) { return ifReplayableBackoffAndReturnTrue(command); } }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public boolean shouldRetryRequest(HttpCommand command, IOException error) { return ifReplayableBackoffAndReturnTrue(command); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(int failureCount, String commandDescription); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max, String commandDescription); }
BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler { public boolean shouldRetryRequest(HttpCommand command, IOException error) { return ifReplayableBackoffAndReturnTrue(command); } boolean shouldRetryRequest(HttpCommand command, IOException error); boolean shouldRetryRequest(HttpCommand command, HttpResponse response); void imposeBackoffExponentialDelay(int failureCount, String commandDescription); void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription); void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max, String commandDescription); static final BackoffLimitedRetryHandler INSTANCE; }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testDoNotRetryIfNoRateLimit() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(450).build(); assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response)); }
@Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testDoNotRetryIfNotReplayable() { Payload payload = newInputStreamPayload(new ByteArrayInputStream(new byte[0])); HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: .payload(payload).build()); HttpResponse response = HttpResponse.builder().statusCode(429).build(); try { assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response)); } finally { releasePayload(command.getCurrentRequest()); } }
@Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testDoNotRetryIfNoRateLimitInfo() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).build(); assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response)); }
@Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testDoNotRetryIfTooMuchWait() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(RETRY_AFTER, "400").build(); assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response)); }
@Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testRequestIsDelayed() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(RETRY_AFTER, "5").build(); long start = System.currentTimeMillis(); assertTrue(rateLimitRetryHandler.shouldRetryRequest(command, response)); assertTrue(System.currentTimeMillis() - start > 2500); }
@Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testDoNotRetryIfRequestIsAborted() throws Exception { final HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: .build()); final HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(RETRY_AFTER, "10").build(); final Thread requestThread = Thread.currentThread(); Thread killer = new Thread() { @Override public void run() { Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS); requestThread.interrupt(); } }; killer.start(); assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response)); }
@Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testIncrementsFailureCount() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).build(); rateLimitRetryHandler.shouldRetryRequest(command, response); assertEquals(command.getFailureCount(), 1); rateLimitRetryHandler.shouldRetryRequest(command, response); assertEquals(command.getFailureCount(), 2); rateLimitRetryHandler.shouldRetryRequest(command, response); assertEquals(command.getFailureCount(), 3); }
@Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
@Test(timeOut = TEST_SAFE_TIMEOUT) public void testDisallowExcessiveRetries() { HttpCommand command = new HttpCommand(HttpRequest.builder().method("GET").endpoint("http: HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(RETRY_AFTER, "0").build(); for (int i = 0; i < 5; i++) { assertTrue(rateLimitRetryHandler.shouldRetryRequest(command, response)); } assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response)); }
@Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
RateLimitRetryHandler implements HttpRetryHandler { @Override public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) { command.incrementFailureCount(); if (response.getStatusCode() != rateLimitErrorStatus()) { return false; } else if (!command.isReplayable()) { logger.error("Cannot retry after rate limit error, command is not replayable: %1$s", command); return false; } else if (command.getFailureCount() > retryCountLimit) { logger.error("Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s", retryCountLimit, command); return false; } else { return delayRequestUntilAllowed(command, response); } } @Override boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response); int getRetryCountLimit(); int getMaxRateLimitWait(); }
@Test public void testNullRange() { GetOptions options = new GetOptions(); assertNull(options.getRange()); }
public String getRange() { return (!ranges.isEmpty()) ? String.format("bytes=%s", Joiner.on(",").join(ranges)) : null; }
GetOptions extends BaseHttpRequestOptions { public String getRange() { return (!ranges.isEmpty()) ? String.format("bytes=%s", Joiner.on(",").join(ranges)) : null; } }
GetOptions extends BaseHttpRequestOptions { public String getRange() { return (!ranges.isEmpty()) ? String.format("bytes=%s", Joiner.on(",").join(ranges)) : null; } }
GetOptions extends BaseHttpRequestOptions { public String getRange() { return (!ranges.isEmpty()) ? String.format("bytes=%s", Joiner.on(",").join(ranges)) : null; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
GetOptions extends BaseHttpRequestOptions { public String getRange() { return (!ranges.isEmpty()) ? String.format("bytes=%s", Joiner.on(",").join(ranges)) : null; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GetOptions NONE; }
@Test public void testIfETagMatches() { GetOptions options = new GetOptions(); options.ifETagMatches(etag); matchesHex(options.getIfMatch()); }
public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; } }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; } }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GetOptions NONE; }
@Test(expectedExceptions = NullPointerException.class) public void testIfETagMatchesNPE() { ifETagMatches(null); }
public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; } }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; } }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagMatches(String eTag) { checkArgument(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkArgument(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GetOptions NONE; }
@Test public void testIfETagDoesntMatch() { GetOptions options = new GetOptions(); options.ifETagDoesntMatch(etag); matchesHex(options.getIfNoneMatch()); }
public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GetOptions NONE; }
@Test(expectedExceptions = NullPointerException.class) public void testIfETagDoesntMatchNPE() { ifETagDoesntMatch(null); }
public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
GetOptions extends BaseHttpRequestOptions { public GetOptions ifETagDoesntMatch(String eTag) { checkArgument(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); checkArgument(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } @Override Multimap<String, String> buildRequestHeaders(); GetOptions range(long start, long end); GetOptions startAt(long start); GetOptions tail(long count); String getRange(); GetOptions ifModifiedSince(Date ifModifiedSince); String getIfModifiedSince(); GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince); String getIfUnmodifiedSince(); GetOptions ifETagMatches(String eTag); String getIfMatch(); GetOptions ifETagDoesntMatch(String eTag); String getIfNoneMatch(); List<String> getRanges(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final GetOptions NONE; }
@Test(dataProvider = "strings") public void testQuery(String val) { assertThat(uriBuilder("https: .isEqualTo("moo=" + val); assertThat(uriBuilder("https: .isEqualTo("moo=" + urlEncode(val, '/', ',')); assertThat(uriBuilder("https: .getQuery()) .isEqualTo("foo=bar&kung=fu&moo=" + val); assertThat(uriBuilder("https: .getRawQuery()) .isEqualTo("foo=bar&kung=fu&moo=" + urlEncode(val, '/', ',')); assertThat(uriBuilder("https: .isEqualTo("moo=" + val); assertThat(uriBuilder("https: .isEqualTo("https: assertThat(uriBuilder("https: .getRawQuery()) .isEqualTo("moo=" + urlEncode(val, '/', ',')); assertThat(uriBuilder("https: .getPath()) .isEqualTo("/repos/bob"); }
public static UriBuilder uriBuilder(CharSequence template) { return new UriBuilder(template); }
Uris { public static UriBuilder uriBuilder(CharSequence template) { return new UriBuilder(template); } }
Uris { public static UriBuilder uriBuilder(CharSequence template) { return new UriBuilder(template); } }
Uris { public static UriBuilder uriBuilder(CharSequence template) { return new UriBuilder(template); } static UriBuilder uriBuilder(CharSequence template); static UriBuilder uriBuilder(URI uri); static boolean lastCharIsToken(CharSequence left, char token); static char lastChar(CharSequence in); static char firstChar(CharSequence in); static boolean isToken(CharSequence right, char token); }
Uris { public static UriBuilder uriBuilder(CharSequence template) { return new UriBuilder(template); } static UriBuilder uriBuilder(CharSequence template); static UriBuilder uriBuilder(URI uri); static boolean lastCharIsToken(CharSequence left, char token); static char lastChar(CharSequence in); static char firstChar(CharSequence in); static boolean isToken(CharSequence right, char token); }
@Test public void testAddUserMetadataTo() { HttpResponse from = HttpResponse.builder() .statusCode(200).message("ok") .payload("") .addHeader("prefix" + "key", "value").build(); MutableBlobMetadata metadata = blobMetadataProvider.get(); parser.addUserMetadataTo(from, metadata); assertEquals(metadata.getUserMetadata().get("key"), "value"); }
@VisibleForTesting void addUserMetadataTo(HttpResponse from, MutableBlobMetadata metadata) { for (Entry<String, String> header : from.getHeaders().entries()) { if (header.getKey() != null && header.getKey().toLowerCase().startsWith(metadataPrefix)) metadata.getUserMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(), header.getValue()); } }
ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>, InvocationContext<ParseSystemAndUserMetadataFromHeaders> { @VisibleForTesting void addUserMetadataTo(HttpResponse from, MutableBlobMetadata metadata) { for (Entry<String, String> header : from.getHeaders().entries()) { if (header.getKey() != null && header.getKey().toLowerCase().startsWith(metadataPrefix)) metadata.getUserMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(), header.getValue()); } } }
ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>, InvocationContext<ParseSystemAndUserMetadataFromHeaders> { @VisibleForTesting void addUserMetadataTo(HttpResponse from, MutableBlobMetadata metadata) { for (Entry<String, String> header : from.getHeaders().entries()) { if (header.getKey() != null && header.getKey().toLowerCase().startsWith(metadataPrefix)) metadata.getUserMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(), header.getValue()); } } @Inject ParseSystemAndUserMetadataFromHeaders(Provider<MutableBlobMetadata> metadataFactory, DateService dateParser, @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); }
ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>, InvocationContext<ParseSystemAndUserMetadataFromHeaders> { @VisibleForTesting void addUserMetadataTo(HttpResponse from, MutableBlobMetadata metadata) { for (Entry<String, String> header : from.getHeaders().entries()) { if (header.getKey() != null && header.getKey().toLowerCase().startsWith(metadataPrefix)) metadata.getUserMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(), header.getValue()); } } @Inject ParseSystemAndUserMetadataFromHeaders(Provider<MutableBlobMetadata> metadataFactory, DateService dateParser, @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); MutableBlobMetadata apply(HttpResponse from); ParseSystemAndUserMetadataFromHeaders setContext(HttpRequest request); ParseSystemAndUserMetadataFromHeaders setName(String name); }
ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>, InvocationContext<ParseSystemAndUserMetadataFromHeaders> { @VisibleForTesting void addUserMetadataTo(HttpResponse from, MutableBlobMetadata metadata) { for (Entry<String, String> header : from.getHeaders().entries()) { if (header.getKey() != null && header.getKey().toLowerCase().startsWith(metadataPrefix)) metadata.getUserMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(), header.getValue()); } } @Inject ParseSystemAndUserMetadataFromHeaders(Provider<MutableBlobMetadata> metadataFactory, DateService dateParser, @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); MutableBlobMetadata apply(HttpResponse from); ParseSystemAndUserMetadataFromHeaders setContext(HttpRequest request); ParseSystemAndUserMetadataFromHeaders setName(String name); }
@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, '/', ',')); }
public static UriBuilder uriBuilder(CharSequence template) { return new UriBuilder(template); }
Uris { public static UriBuilder uriBuilder(CharSequence template) { return new UriBuilder(template); } }
Uris { public static UriBuilder uriBuilder(CharSequence template) { return new UriBuilder(template); } }
Uris { public static UriBuilder uriBuilder(CharSequence template) { return new UriBuilder(template); } static UriBuilder uriBuilder(CharSequence template); static UriBuilder uriBuilder(URI uri); static boolean lastCharIsToken(CharSequence left, char token); static char lastChar(CharSequence in); static char firstChar(CharSequence in); static boolean isToken(CharSequence right, char token); }
Uris { public static UriBuilder uriBuilder(CharSequence template) { return new UriBuilder(template); } static UriBuilder uriBuilder(CharSequence template); static UriBuilder uriBuilder(URI uri); static boolean lastCharIsToken(CharSequence left, char token); static char lastChar(CharSequence in); static char firstChar(CharSequence in); static boolean isToken(CharSequence right, char token); }
@Test public void testExceptionWhenNoContentOn200() { Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x(); HttpResponse response = createMock(HttpResponse.class); Payload payload = createMock(Payload.class); expect(response.getStatusCode()).andReturn(200).atLeastOnce(); expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn("text/uri-list"); expect(response.getPayload()).andReturn(payload).atLeastOnce(); expect(payload.getInput()).andReturn(null); payload.release(); replay(payload); replay(response); try { function.apply(response); } catch (Exception e) { assert e.getMessage().equals("no content"); } verify(payload); verify(response); }
public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } URI apply(HttpResponse from); @Override ParseURIFromListOrLocationHeaderIf20x setContext(HttpRequest request); }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } URI apply(HttpResponse from); @Override ParseURIFromListOrLocationHeaderIf20x setContext(HttpRequest request); }
@Test public void testExceptionWhenIOExceptionOn200() { Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x(); HttpResponse response = createMock(HttpResponse.class); Payload payload = createMock(Payload.class); expect(response.getStatusCode()).andReturn(200).atLeastOnce(); expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn("text/uri-list"); RuntimeException exception = new RuntimeException("bad"); expect(response.getPayload()).andReturn(payload).atLeastOnce(); expect(payload.getInput()).andThrow(exception); payload.release(); replay(payload); replay(response); try { function.apply(response); } catch (Exception e) { assert e.equals(exception); } verify(payload); verify(response); }
public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } URI apply(HttpResponse from); @Override ParseURIFromListOrLocationHeaderIf20x setContext(HttpRequest request); }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } URI apply(HttpResponse from); @Override ParseURIFromListOrLocationHeaderIf20x setContext(HttpRequest request); }
@Test public void testResponseOk() { Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x(); HttpResponse response = createMock(HttpResponse.class); Payload payload = createMock(Payload.class); expect(response.getStatusCode()).andReturn(200).atLeastOnce(); expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn("text/uri-list"); expect(response.getPayload()).andReturn(payload).atLeastOnce(); expect(payload.getInput()).andReturn(toInputStream("http: payload.release(); replay(payload); replay(response); assertEquals(function.apply(response), URI.create("http: verify(payload); verify(response); }
public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } URI apply(HttpResponse from); @Override ParseURIFromListOrLocationHeaderIf20x setContext(HttpRequest request); }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } URI apply(HttpResponse from); @Override ParseURIFromListOrLocationHeaderIf20x setContext(HttpRequest request); }
@Test public void testResponseLocationOk() { Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x(); HttpResponse response = createMock(HttpResponse.class); Payload payload = createMock(Payload.class); expect(response.getStatusCode()).andReturn(200).atLeastOnce(); expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn("text/plain"); expect(response.getFirstHeaderOrNull(LOCATION)).andReturn("http: expect(response.getPayload()).andReturn(payload).atLeastOnce(); payload.release(); replay(payload); replay(response); assertEquals(function.apply(response), URI.create("http: verify(response); verify(payload); }
public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } URI apply(HttpResponse from); @Override ParseURIFromListOrLocationHeaderIf20x setContext(HttpRequest request); }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } URI apply(HttpResponse from); @Override ParseURIFromListOrLocationHeaderIf20x setContext(HttpRequest request); }
@Test public void testResponseLowercaseLocationOk() { Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x(); HttpResponse response = createMock(HttpResponse.class); Payload payload = createMock(Payload.class); expect(response.getStatusCode()).andReturn(200).atLeastOnce(); expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn("text/plain"); expect(response.getFirstHeaderOrNull(LOCATION)).andReturn(null); expect(response.getFirstHeaderOrNull("location")).andReturn("http: expect(response.getPayload()).andReturn(payload).atLeastOnce(); payload.release(); replay(payload); replay(response); assertEquals(function.apply(response), URI.create("http: verify(response); verify(payload); }
public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } URI apply(HttpResponse from); @Override ParseURIFromListOrLocationHeaderIf20x setContext(HttpRequest request); }
ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>, InvocationContext<ParseURIFromListOrLocationHeaderIf20x> { public URI apply(HttpResponse from) { if (from.getStatusCode() > 206) throw new HttpException(String.format("Unhandled status code - %1$s", from)); if ("text/uri-list".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) { try { if (from.getPayload().getInput() == null) throw new HttpResponseException("no content", null, from); String toParse = Strings2.toStringAndClose(from.getPayload().getInput()); return URI.create(toParse.trim()); } catch (IOException e) { throw new HttpResponseException("couldn't parse uri from content", null, from, e); } finally { releasePayload(from); } } else { 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"); if (!location.startsWith("/")) location = "/" + location; locationUri = URI.create(location); return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build(); } else { return null; } } } URI apply(HttpResponse from); @Override ParseURIFromListOrLocationHeaderIf20x setContext(HttpRequest request); }
@Test public void testAddDetailsAndPropagateOkWhenRequestWithNoDataAndRuntimeExceptionThrowsOriginalException() { ParseSax<String> parser = createParser(); Exception input = new RuntimeException("foo"); try { parser.addDetailsAndPropagate(null, input); } catch (RuntimeException e) { assertEquals(e, input); } }
public T addDetailsAndPropagate(HttpResponse response, Exception e) { return addDetailsAndPropagate(response, e, null); }
ParseSax implements Function<HttpResponse, T>, InvocationContext<ParseSax<T>> { public T addDetailsAndPropagate(HttpResponse response, Exception e) { return addDetailsAndPropagate(response, e, null); } }
ParseSax implements Function<HttpResponse, T>, InvocationContext<ParseSax<T>> { public T addDetailsAndPropagate(HttpResponse response, Exception e) { return addDetailsAndPropagate(response, e, null); } ParseSax(XMLReader parser, HandlerWithResult<T> handler); }
ParseSax implements Function<HttpResponse, T>, InvocationContext<ParseSax<T>> { public T addDetailsAndPropagate(HttpResponse response, Exception e) { return addDetailsAndPropagate(response, e, null); } ParseSax(XMLReader parser, HandlerWithResult<T> handler); T apply(HttpResponse from); T parse(String from); T parse(InputStream from); T parse(InputSource from); T addDetailsAndPropagate(HttpResponse response, Exception e); T addDetailsAndPropagate(HttpResponse response, Exception e, @Nullable String text); HandlerWithResult<T> getHandler(); @Override ParseSax<T> setContext(HttpRequest request); }
ParseSax implements Function<HttpResponse, T>, InvocationContext<ParseSax<T>> { public T addDetailsAndPropagate(HttpResponse response, Exception e) { return addDetailsAndPropagate(response, e, null); } ParseSax(XMLReader parser, HandlerWithResult<T> handler); T apply(HttpResponse from); T parse(String from); T parse(InputStream from); T parse(InputSource from); T addDetailsAndPropagate(HttpResponse response, Exception e); T addDetailsAndPropagate(HttpResponse response, Exception e, @Nullable String text); HandlerWithResult<T> getHandler(); @Override ParseSax<T> setContext(HttpRequest request); }
@Test public void testAddDetailsAndPropagateOkWhenRequestWithNoDataAndExceptionPropagates() { ParseSax<String> parser = createParser(); Exception input = new Exception("foo"); try { parser.addDetailsAndPropagate(null, input); } catch (RuntimeException e) { assertEquals(e.getMessage(), "java.lang.Exception: foo"); assertEquals(e.getCause(), input); } }
public T addDetailsAndPropagate(HttpResponse response, Exception e) { return addDetailsAndPropagate(response, e, null); }
ParseSax implements Function<HttpResponse, T>, InvocationContext<ParseSax<T>> { public T addDetailsAndPropagate(HttpResponse response, Exception e) { return addDetailsAndPropagate(response, e, null); } }
ParseSax implements Function<HttpResponse, T>, InvocationContext<ParseSax<T>> { public T addDetailsAndPropagate(HttpResponse response, Exception e) { return addDetailsAndPropagate(response, e, null); } ParseSax(XMLReader parser, HandlerWithResult<T> handler); }
ParseSax implements Function<HttpResponse, T>, InvocationContext<ParseSax<T>> { public T addDetailsAndPropagate(HttpResponse response, Exception e) { return addDetailsAndPropagate(response, e, null); } ParseSax(XMLReader parser, HandlerWithResult<T> handler); T apply(HttpResponse from); T parse(String from); T parse(InputStream from); T parse(InputSource from); T addDetailsAndPropagate(HttpResponse response, Exception e); T addDetailsAndPropagate(HttpResponse response, Exception e, @Nullable String text); HandlerWithResult<T> getHandler(); @Override ParseSax<T> setContext(HttpRequest request); }
ParseSax implements Function<HttpResponse, T>, InvocationContext<ParseSax<T>> { public T addDetailsAndPropagate(HttpResponse response, Exception e) { return addDetailsAndPropagate(response, e, null); } ParseSax(XMLReader parser, HandlerWithResult<T> handler); T apply(HttpResponse from); T parse(String from); T parse(InputStream from); T parse(InputSource from); T addDetailsAndPropagate(HttpResponse response, Exception e); T addDetailsAndPropagate(HttpResponse response, Exception e, @Nullable String text); HandlerWithResult<T> getHandler(); @Override ParseSax<T> setContext(HttpRequest request); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = ".* parameter 0 failed to be named by AnnotationBasedNamingStrategy requiring one of javax.inject.Named") public void testSerializedNameRequiredOnAllParameters() { parameterizedCtorFactory .create(gson, TypeToken.get(WithDeserializationConstructorButWithoutSerializedName.class)); }
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); TypeAdapter<T> create(Gson gson, TypeToken<T> type); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); TypeAdapter<T> create(Gson gson, TypeToken<T> type); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Multiple entries with same key: foo.*") public void testNoDuplicateSerializedNamesRequiredOnAllParameters() { parameterizedCtorFactory.create(gson, TypeToken.get(DuplicateSerializedNames.class)); }
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); TypeAdapter<T> create(Gson gson, TypeToken<T> type); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); TypeAdapter<T> create(Gson gson, TypeToken<T> type); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "absent!") public void testValidatedConstructor() throws IOException { Gson gson = new GsonBuilder().registerTypeAdapterFactory(parameterizedCtorFactory) .registerTypeAdapterFactory(new OptionalTypeAdapterFactory()).create(); assertEquals(new ValidatedConstructor(Optional.of(0), 1), gson.fromJson("{\"foo\":0,\"bar\":1}", ValidatedConstructor.class)); gson.fromJson("{\"bar\":1}", ValidatedConstructor.class); }
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); TypeAdapter<T> create(Gson gson, TypeToken<T> type); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); TypeAdapter<T> create(Gson gson, TypeToken<T> type); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Incorrect count of names on annotation of .*") public void testSerializedNamesMustHaveCorrectCountOfNames() { parameterizedCtorFactory.create(gson, TypeToken.get(ValueTypeWithFactoryMissingSerializedNames.class)); }
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); TypeAdapter<T> create(Gson gson, TypeToken<T> type); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); TypeAdapter<T> create(Gson gson, TypeToken<T> type); }
@Test(expectedExceptions = NullPointerException.class) public void testPartialObjectStillThrows() throws IOException { TypeAdapter<ComposedObjects> adapter = parameterizedCtorFactory .create(gson, TypeToken.get(ComposedObjects.class)); assertNull(adapter.fromJson("{\"x\":{\"foo\":0,\"bar\":1}}")); }
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); TypeAdapter<T> create(Gson gson, TypeToken<T> type); }
DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { com.google.common.reflect.TypeToken<T> token = typeToken(type.getType()); Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token); if (deserializationTarget == null) { return null; } if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) { String packageName = type.getRawType().getPackage().getName(); String autoClassName = type.getRawType().getName().replace('$', '_') .replace(packageName + ".", packageName + ".AutoValue_"); try { type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName)); } catch (ClassNotFoundException ignored) { } } return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget, getParameterReaders(gson, deserializationTarget)); } DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder, AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy); TypeAdapter<T> create(Gson gson, TypeToken<T> type); }
@Test public void testDontUseProxyForSockets() throws Exception { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, creds); ProxyForURI proxy = new ProxyForURI(config); Field useProxyForSockets = proxy.getClass().getDeclaredField("useProxyForSockets"); useProxyForSockets.setAccessible(true); useProxyForSockets.setBoolean(proxy, false); URI uri = new URI("socket: assertEquals(proxy.apply(uri), Proxy.NO_PROXY); }
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
@Test public void testUseProxyForSockets() throws Exception { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, creds); ProxyForURI proxy = new ProxyForURI(config); URI uri = new URI("socket: assertEquals(proxy.apply(uri), new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080))); }
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
@Test public void testUseProxyForSocketsSettingShouldntAffectHTTP() throws Exception { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, creds); ProxyForURI proxy = new ProxyForURI(config); Field useProxyForSockets = proxy.getClass().getDeclaredField("useProxyForSockets"); useProxyForSockets.setAccessible(true); useProxyForSockets.setBoolean(proxy, false); URI uri = new URI("http: assertEquals(proxy.apply(uri), new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080))); }
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
@Test public void testHTTPDirect() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds); URI uri = new URI("http: assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY); }
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
@Test public void testHTTPSDirect() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds); URI uri = new URI("https: assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY); }
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
@Test public void testFTPDirect() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds); URI uri = new URI("ftp: assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY); }
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
@Test public void testSocketDirect() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds); URI uri = new URI("socket: assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY); }
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
@Test public void testHTTPThroughHTTPProxy() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, creds); URI uri = new URI("http: assertEquals(new ProxyForURI(config).apply(uri), new Proxy(Proxy.Type.HTTP, new InetSocketAddress( "proxy.example.com", 8080))); }
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
@Test public void testThroughJvmProxy() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(false, true, Proxy.Type.HTTP, noHostAndPort, noCreds); URI uri = new URI("http: assertNotNull(new ProxyForURI(config).apply(uri)); }
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
@Test public void testCorrect() throws SecurityException, NoSuchMethodException { Blob blob = BLOB_FACTORY.create(null); blob.getMetadata().setName("foo"); assertEquals(fn.apply(blob), "foo"); }
public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); }
BlobName implements Function<Blob, String> { public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); } }
BlobName implements Function<Blob, String> { public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); } }
BlobName implements Function<Blob, String> { public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); } String apply(Blob input); }
BlobName implements Function<Blob, String> { public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); } String apply(Blob input); }
@Test public void testThroughSystemProxy() throws URISyntaxException { ProxyConfig config = new MyProxyConfig(true, false, Proxy.Type.HTTP, noHostAndPort, noCreds); URI uri = new URI("http: assertNotNull(new ProxyForURI(config).apply(uri)); }
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
@Test public void testJcloudsProxyHostsPreferredOverJvmProxy() throws URISyntaxException { ProxyConfig test = new MyProxyConfig(true, true, Proxy.Type.HTTP, hostAndPort, noCreds); ProxyConfig jclouds = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, noCreds); ProxyConfig jvm = new MyProxyConfig(false, true, Proxy.Type.HTTP, noHostAndPort, noCreds); URI uri = new URI("http: assertEquals(new ProxyForURI(test).apply(uri), new ProxyForURI(jclouds).apply(uri)); assertNotEquals(new ProxyForURI(test).apply(uri), new ProxyForURI(jvm).apply(uri)); }
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
@Test public void testJvmProxyAlwaysPreferredOverSystem() throws URISyntaxException { ProxyConfig test = new MyProxyConfig(true, true, Proxy.Type.HTTP, noHostAndPort, noCreds); ProxyConfig jvm = new MyProxyConfig(false, true, Proxy.Type.HTTP, noHostAndPort, noCreds); URI uri = new URI("http: assertEquals(new ProxyForURI(test).apply(uri), new ProxyForURI(jvm).apply(uri)); }
@Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
ProxyForURI implements Function<URI, Proxy> { @Override public Proxy apply(URI endpoint) { if (!useProxyForSockets && "socket".equals(endpoint.getScheme())) { return Proxy.NO_PROXY; } if (config.getProxy().isPresent()) { SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHostText(), config.getProxy().get() .getPort()); Proxy proxy = new Proxy(config.getType(), addr); final Optional<Credentials> creds = config.getCredentials(); if (creds.isPresent()) { Authenticator authenticator = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray()); } }; Authenticator.setDefault(authenticator); } return proxy; } if (config.isJvmProxyEnabled()) { return getDefaultProxy(endpoint); } if (config.useSystem()) { System.setProperty("java.net.useSystemProxies", "true"); return getDefaultProxy(endpoint); } return Proxy.NO_PROXY; } @VisibleForTesting @Inject ProxyForURI(ProxyConfig config); @Override Proxy apply(URI endpoint); }
@Test void testRetryAlwaysFalseMillis() { RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(Integer.MAX_VALUE); Predicate<String> predicate = retry(rawPredicate, 3, 1, SECONDS); stopwatch.start(); assertFalse(predicate.apply("")); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(3000 - EARLY_RETURN_GRACE, duration, 3000 + SLOW_BUILD_SERVER_GRACE); assertCallTimes(rawPredicate.callTimes, 0, 1000, 1000 + 1500, 3000); }
public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } static Predicate<String> startsWith(final String prefix); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout); }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } static Predicate<String> startsWith(final String prefix); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout); static final long DEFAULT_PERIOD; static final long DEFAULT_MAX_PERIOD; }
@Test void testRetryFirstTimeTrue() { RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(1); Predicate<String> predicate = retry(rawPredicate, 4, 1, SECONDS); stopwatch.start(); assertTrue(predicate.apply("")); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(0, duration, 0 + SLOW_BUILD_SERVER_GRACE); assertCallTimes(rawPredicate.callTimes, 0); }
public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } static Predicate<String> startsWith(final String prefix); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout); }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } static Predicate<String> startsWith(final String prefix); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout); static final long DEFAULT_PERIOD; static final long DEFAULT_MAX_PERIOD; }
@Test void testRetryWillRunOnceOnNegativeTimeout() { RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(1); Predicate<String> predicate = retry(rawPredicate, -1, 1, SECONDS); stopwatch.start(); assertTrue(predicate.apply("")); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(0, duration, 0 + SLOW_BUILD_SERVER_GRACE); assertCallTimes(rawPredicate.callTimes, 0); }
public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } static Predicate<String> startsWith(final String prefix); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout); }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } static Predicate<String> startsWith(final String prefix); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout); static final long DEFAULT_PERIOD; static final long DEFAULT_MAX_PERIOD; }
@Test void testRetryThirdTimeTrue() { RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(3); Predicate<String> predicate = retry(rawPredicate, 4, 1, SECONDS); stopwatch.start(); assertTrue(predicate.apply("")); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(2500 - EARLY_RETURN_GRACE, duration, 2500 + SLOW_BUILD_SERVER_GRACE); assertCallTimes(rawPredicate.callTimes, 0, 1000, 1000 + 1500); }
public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } static Predicate<String> startsWith(final String prefix); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout); }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } static Predicate<String> startsWith(final String prefix); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout); static final long DEFAULT_PERIOD; static final long DEFAULT_MAX_PERIOD; }
@Test void testRetryThirdTimeTrueLimitedMaxInterval() { RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(3); Predicate<String> predicate = retry(rawPredicate, 3, 1, 1, SECONDS); stopwatch.start(); assertTrue(predicate.apply("")); long duration = stopwatch.elapsed(MILLISECONDS); assertOrdered(2000 - EARLY_RETURN_GRACE, duration, 2000 + SLOW_BUILD_SERVER_GRACE); assertCallTimes(rawPredicate.callTimes, 0, 1000, 2000); }
public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } static Predicate<String> startsWith(final String prefix); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout); }
Predicates2 { public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) { return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit); } static Predicate<String> startsWith(final String prefix); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod); static Predicate<T> retry(Predicate<T> findOrBreak, long timeout); static final long DEFAULT_PERIOD; static final long DEFAULT_MAX_PERIOD; }
@Test(expectedExceptions = TestException.class) public void testPropagateExceptionThatsInList() throws Throwable { Exception e = new TestException(); propagateIfPossible(e, ImmutableSet.<TypeToken<? extends Throwable>> of(typeToken(TestException.class))); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { fn.apply(null); }
public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); }
BlobName implements Function<Blob, String> { public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); } }
BlobName implements Function<Blob, String> { public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); } }
BlobName implements Function<Blob, String> { public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); } String apply(Blob input); }
BlobName implements Function<Blob, String> { public String apply(Blob input) { return checkNotNull(checkNotNull(input, "input").getMetadata().getName(), "blobName"); } String apply(Blob input); }
@Test(expectedExceptions = TestException.class) public void testPropagateWrappedExceptionThatsInList() throws Throwable { Exception e = new TestException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of(typeToken(TestException.class))); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = IllegalStateException.class) public void testPropagateStandardExceptionIllegalStateException() throws Throwable { Exception e = new IllegalStateException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testPropagateStandardExceptionIllegalArgumentException() throws Throwable { Exception e = new IllegalArgumentException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = UnsupportedOperationException.class) public void testPropagateStandardExceptionUnsupportedOperationException() throws Throwable { Exception e = new UnsupportedOperationException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = AssertionError.class) public void testPropagateStandardExceptionAssertionError() throws Throwable { AssertionError e = new AssertionError(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = AuthorizationException.class) public void testPropagateStandardExceptionAuthorizationException() throws Throwable { Exception e = new AuthorizationException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = AuthorizationException.class) public void testPropagateProvisionExceptionAuthorizationException() throws Throwable { Exception e = new AuthorizationException(); propagateIfPossible( new ProvisionException(ImmutableSet.of(new Message(ImmutableList.of(), "Error in custom provider", e))), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = AuthorizationException.class) public void testPropagateCreationExceptionAuthorizationException() throws Throwable { Exception e = new AuthorizationException(); propagateIfPossible( new CreationException(ImmutableSet.of(new Message(ImmutableList.of(), "Error in custom provider", e))), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = InsufficientResourcesException.class) public void testPropagateStandardExceptionInsufficientResourcesException() throws Throwable { Exception e = new InsufficientResourcesException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = ResourceNotFoundException.class) public void testPropagateStandardExceptionResourceNotFoundException() throws Throwable { Exception e = new ResourceNotFoundException(); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = IllegalStateException.class) public void testPropagateStandardExceptionIllegalStateExceptionNestedInHttpResponseException() throws Throwable { Exception e = new IllegalStateException(); propagateIfPossible(new HttpResponseException("goo", createNiceMock(HttpCommand.class), null, e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testPropagateStandardExceptionIllegalArgumentExceptionNestedInHttpResponseException() throws Throwable { Exception e = new IllegalArgumentException(); propagateIfPossible(new HttpResponseException("goo", createNiceMock(HttpCommand.class), null, e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = UnsupportedOperationException.class) public void testPropagateStandardExceptionUnsupportedOperationExceptionNestedInHttpResponseException() throws Throwable { Exception e = new UnsupportedOperationException(); propagateIfPossible(new HttpResponseException("goo", createNiceMock(HttpCommand.class), null, e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = AuthorizationException.class) public void testPropagateStandardExceptionAuthorizationExceptionNestedInHttpResponseException() throws Throwable { Exception e = new AuthorizationException(); propagateIfPossible(new HttpResponseException("goo", createNiceMock(HttpCommand.class), null, e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = ResourceNotFoundException.class) public void testPropagateStandardExceptionResourceNotFoundExceptionNestedInHttpResponseException() throws Throwable { Exception e = new ResourceNotFoundException(); propagateIfPossible(new HttpResponseException("goo", createNiceMock(HttpCommand.class), null, e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test(expectedExceptions = HttpResponseException.class) public void testPropagateStandardExceptionHttpResponseException() throws Throwable { Exception e = new HttpResponseException("goo", createNiceMock(HttpCommand.class), null); propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of()); }
public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
Throwables2 { public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables) throws Throwable { for (TypeToken<? extends Throwable> type : throwables) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType()); if (throwable != null) { throw throwable; } } for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) { Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType); if (throwable != null) { throw throwable; } } } static Predicate<Throwable> containsThrowable(final Class<T> throwableType); @SuppressWarnings("unchecked") static T getFirstThrowableOfType(Throwable from, Class<T> clazz); static T propagateAuthorizationOrOriginalException(Exception e); static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables); }
@Test public void testGetLastValueInMap() { assertEquals( Suppliers2.<String, String> getLastValueInMap( Suppliers.<Map<String, Supplier<String>>> ofInstance(ImmutableMap.of("foo", Suppliers.ofInstance("bar")))).get(), "bar"); }
public static <K, V> Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input) { return new Supplier<V>() { @Override public V get() { Supplier<V> last = Iterables.getLast(input.get().values()); return last != null ? last.get() : null; } @Override public String toString() { return "getLastValueInMap()"; } }; }
Suppliers2 { public static <K, V> Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input) { return new Supplier<V>() { @Override public V get() { Supplier<V> last = Iterables.getLast(input.get().values()); return last != null ? last.get() : null; } @Override public String toString() { return "getLastValueInMap()"; } }; } }
Suppliers2 { public static <K, V> Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input) { return new Supplier<V>() { @Override public V get() { Supplier<V> last = Iterables.getLast(input.get().values()); return last != null ? last.get() : null; } @Override public String toString() { return "getLastValueInMap()"; } }; } }
Suppliers2 { public static <K, V> Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input) { return new Supplier<V>() { @Override public V get() { Supplier<V> last = Iterables.getLast(input.get().values()); return last != null ? last.get() : null; } @Override public String toString() { return "getLastValueInMap()"; } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback); }
Suppliers2 { public static <K, V> Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input) { return new Supplier<V>() { @Override public V get() { Supplier<V> last = Iterables.getLast(input.get().values()); return last != null ? last.get() : null; } @Override public String toString() { return "getLastValueInMap()"; } }; } static Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input); static Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue); static Function<X, Supplier<X>> ofInstanceFunction(); @Beta static Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback); @Beta static Supplier<T> onThrowable(final Supplier<T> unlessThrowable, final Class<X> throwable, final Supplier<T> fallback); }