EMMA Coverage Report (generated Wed Jun 22 19:47:49 EDT 2011)
[all classes][org.jclouds.rest.internal]

COVERAGE SUMMARY FOR SOURCE FILE [RestAnnotationProcessor.java]

nameclass, %method, %block, %line, %
RestAnnotationProcessor.java100% (16/16)97%  (77/79)84%  (2988/3540)85%  (523.7/613)

COVERAGE BREAKDOWN BY CLASS AND METHOD

nameclass, %method, %block, %line, %
     
class RestAnnotationProcessor$MethodKey100% (1/1)100% (3/3)78%  (90/116)67%  (20.8/31)
equals (Object): boolean 100% (1/1)63%  (38/60)50%  (10/20)
hashCode (): int 100% (1/1)90%  (35/39)97%  (5.8/6)
RestAnnotationProcessor$MethodKey (Method): void 100% (1/1)100% (17/17)100% (5/5)
     
class RestAnnotationProcessor100% (1/1)96%  (51/53)84%  (2744/3270)86%  (481.9/561)
indexWithOnlyOneAnnotation (Method, String, Map): Map 0%   (0/1)0%   (0/31)0%   (0/4)
replaceQuery (URI, String, Comparator): URI 0%   (0/1)0%   (0/9)0%   (0/1)
findOptionsIn (Method, Object []): HttpRequestOptions 100% (1/1)39%  (32/82)32%  (4.8/15)
getHttpMethodOrConstantOrThrowException (Method): String 100% (1/1)52%  (14/27)75%  (3/4)
getMapPayloadBinderOrNull (Method, Object []): MapBinder 100% (1/1)56%  (59/106)56%  (11.8/21)
addProducesIfPresentOnTypeOrMethod (Multimap, Method): void 100% (1/1)63%  (22/35)71%  (5/7)
decorateRequest (GeneratedHttpRequest): GeneratedHttpRequest 100% (1/1)64%  (132/206)61%  (17/28)
addForm (Multimap, FormParams, Collection): void 100% (1/1)65%  (30/46)67%  (4/6)
addMatrix (Multimap, MatrixParams, Collection): void 100% (1/1)65%  (30/46)67%  (4/6)
createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation (Injector, Me... 100% (1/1)67%  (12/18)75%  (3/4)
getAcceptHeadersOrNull (Method): List 100% (1/1)69%  (22/32)75%  (6/8)
getMatrixParamKeyValues (Method, Object []): Multimap 100% (1/1)70%  (84/120)76%  (14.5/19)
getEndpointInParametersOrNull (Method, Object [], Injector): URI 100% (1/1)72%  (102/142)79%  (14.9/19)
createResponseParser (ParseSax$Factory, Injector, Method, HttpRequest): Function 100% (1/1)72%  (21/29)86%  (6/7)
getSaxResponseParserClassOrNull (Method): Class 100% (1/1)75%  (9/12)75%  (3/4)
getFormParamKeyValues (Method, Object []): Multimap 100% (1/1)77%  (92/120)82%  (15.5/19)
getQueryParamKeyValues (Method, Object []): Multimap 100% (1/1)77%  (92/120)82%  (15.5/19)
addMapPayload (Map, PayloadParams, Collection): void 100% (1/1)77%  (30/39)80%  (4/5)
buildPostParams (Method, Object []): Map 100% (1/1)77%  (75/97)80%  (11.9/15)
getJsonParserKeyForMethodAnType (Method, Type): Key 100% (1/1)85%  (93/110)93%  (14/15)
findHttpRequestInArgs (Object []): HttpRequest 100% (1/1)92%  (24/26)83%  (5/6)
createRequest (Method, Object []): GeneratedHttpRequest 100% (1/1)93%  (494/534)93%  (87/94)
findPayloadInArgs (Object []): Payload 100% (1/1)95%  (37/39)88%  (7/8)
getParserOrThrowException (Method): Key 100% (1/1)95%  (115/121)89%  (16/18)
<static initializer> 100% (1/1)100% (83/83)100% (23/23)
RestAnnotationProcessor (Injector, ConcurrentMap, String, ParseSax$Factory, H... 100% (1/1)100% (53/53)100% (14/14)
access$100 (): Class 100% (1/1)100% (2/2)100% (1/1)
addConsumesIfPresentOnTypeOrMethod (Multimap, Method): void 100% (1/1)100% (12/12)100% (4/4)
addFormParams (Collection, Method, Object []): Multimap 100% (1/1)100% (59/59)100% (10/10)
addHeader (Multimap, Headers, Collection): void 100% (1/1)100% (27/27)100% (5/5)
addHeaderIfAnnotationPresentOnMethod (Multimap, Method, Collection): void 100% (1/1)100% (31/31)100% (7/7)
addMatrixParams (Collection, Method, Object []): Multimap 100% (1/1)100% (59/59)100% (10/10)
addPathAndGetTokens (Class, Method, Object [], UriBuilder): Multimap 100% (1/1)100% (25/25)100% (5/5)
addQuery (Multimap, QueryParams, Collection): void 100% (1/1)100% (46/46)100% (6/6)
addQueryParams (Collection, Method, Object []): Multimap 100% (1/1)100% (59/59)100% (10/10)
buildHeaders (Collection, Method, Object []): Multimap 100% (1/1)100% (66/66)100% (12/12)
createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation (Method): Fun... 100% (1/1)100% (5/5)100% (1/1)
createMethodToIndexOfParamToAnnotation (Class): Map 100% (1/1)100% (9/9)100% (1/1)
createResponseParser (Method, HttpRequest): Function 100% (1/1)100% (8/8)100% (1/1)
encodeValues (Multimap, char []): Multimap 100% (1/1)100% (26/26)100% (4/4)
filterOutContentHeaders (Multimap): Multimap 100% (1/1)100% (30/30)100% (5/5)
getDelegateOrNull (Method): Method 100% (1/1)100% (8/8)100% (1/1)
getEndpointFor (Method, Object [], Injector): URI 100% (1/1)100% (51/51)100% (9/9)
getFiltersIfAnnotated (Method): List 100% (1/1)100% (111/111)100% (14/14)
getHttpMethods (Method): Set 100% (1/1)100% (42/42)100% (7/7)
getJsonParserKeyForMethod (Method): Key 100% (1/1)100% (7/7)100% (2/2)
getParts (Method, Object [], Iterable): List 100% (1/1)100% (79/79)100% (14/14)
getPathParamKeyValues (Method, Object []): Multimap 100% (1/1)100% (120/120)100% (19/19)
getReturnTypeForMethod (Method): Type 100% (1/1)100% (40/40)100% (10/10)
indexWithAtLeastOneAnnotation (Method, Map): Map 100% (1/1)100% (11/11)100% (2/2)
replaceQuery (Provider, URI, String, Comparator, char []): URI 100% (1/1)100% (19/19)100% (3/3)
setCaller (ClassMethodArgs): void 100% (1/1)100% (22/22)100% (6/6)
shouldAddHostHeader (Method): boolean 100% (1/1)100% (13/13)100% (3/3)
     
class RestAnnotationProcessor$1100% (1/1)100% (2/2)100% (17/17)100% (2/2)
RestAnnotationProcessor$1 (Class): void 100% (1/1)100% (6/6)100% (1/1)
apply (Method): Map 100% (1/1)100% (11/11)100% (1/1)
     
class RestAnnotationProcessor$10100% (1/1)100% (1/1)100% (3/3)100% (1/1)
RestAnnotationProcessor$10 (): void 100% (1/1)100% (3/3)100% (1/1)
     
class RestAnnotationProcessor$11100% (1/1)100% (2/2)100% (11/11)100% (2/2)
RestAnnotationProcessor$11 (): void 100% (1/1)100% (3/3)100% (1/1)
apply (Set): boolean 100% (1/1)100% (8/8)100% (1/1)
     
class RestAnnotationProcessor$12100% (1/1)100% (2/2)100% (11/11)100% (2/2)
RestAnnotationProcessor$12 (): void 100% (1/1)100% (3/3)100% (1/1)
apply (Set): boolean 100% (1/1)100% (8/8)100% (1/1)
     
class RestAnnotationProcessor$2100% (1/1)100% (2/2)100% (11/11)100% (2/2)
RestAnnotationProcessor$2 (): void 100% (1/1)100% (3/3)100% (1/1)
apply (Map$Entry): Part 100% (1/1)100% (8/8)100% (1/1)
     
class RestAnnotationProcessor$3100% (1/1)100% (2/2)100% (35/35)100% (7/7)
RestAnnotationProcessor$3 (): void 100% (1/1)100% (3/3)100% (1/1)
apply (Method): Set 100% (1/1)100% (32/32)100% (6/6)
     
class RestAnnotationProcessor$4100% (1/1)100% (2/2)100% (12/12)100% (2/2)
RestAnnotationProcessor$4 (Object []): void 100% (1/1)100% (6/6)100% (1/1)
apply (Integer): Object 100% (1/1)100% (6/6)100% (1/1)
     
class RestAnnotationProcessor$5100% (1/1)100% (1/1)100% (3/3)100% (1/1)
RestAnnotationProcessor$5 (): void 100% (1/1)100% (3/3)100% (1/1)
     
class RestAnnotationProcessor$6100% (1/1)100% (1/1)100% (3/3)100% (1/1)
RestAnnotationProcessor$6 (): void 100% (1/1)100% (3/3)100% (1/1)
     
class RestAnnotationProcessor$7100% (1/1)100% (1/1)100% (3/3)100% (1/1)
RestAnnotationProcessor$7 (): void 100% (1/1)100% (3/3)100% (1/1)
     
class RestAnnotationProcessor$8100% (1/1)100% (1/1)100% (3/3)100% (1/1)
RestAnnotationProcessor$8 (): void 100% (1/1)100% (3/3)100% (1/1)
     
class RestAnnotationProcessor$9100% (1/1)100% (1/1)100% (3/3)100% (1/1)
RestAnnotationProcessor$9 (): void 100% (1/1)100% (3/3)100% (1/1)
     
class RestAnnotationProcessor$GetAnnotationsForMethodParameterIndex100% (1/1)100% (3/3)100% (26/26)100% (6/6)
RestAnnotationProcessor$GetAnnotationsForMethodParameterIndex (Method, Class)... 100% (1/1)100% (9/9)100% (4/4)
access$000 (RestAnnotationProcessor$GetAnnotationsForMethodParameterIndex): C... 100% (1/1)100% (3/3)100% (1/1)
apply (Integer): Set 100% (1/1)100% (14/14)100% (1/1)
     
class RestAnnotationProcessor$GetAnnotationsForMethodParameterIndex$1100% (1/1)100% (2/2)100% (13/13)100% (2/2)
RestAnnotationProcessor$GetAnnotationsForMethodParameterIndex$1 (RestAnnotati... 100% (1/1)100% (6/6)100% (1/1)
apply (Annotation): boolean 100% (1/1)100% (7/7)100% (1/1)

1/**
2 *
3 * Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
4 *
5 * ====================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 * ====================================================================
18 */
19package org.jclouds.rest.internal;
20 
21import static com.google.common.base.Preconditions.checkArgument;
22import static com.google.common.collect.Collections2.filter;
23import static com.google.common.collect.Iterables.concat;
24import static com.google.common.collect.Iterables.get;
25import static com.google.common.collect.Iterables.transform;
26import static com.google.common.collect.Lists.newLinkedList;
27import static com.google.common.collect.Maps.filterValues;
28import static com.google.common.collect.Maps.newHashMap;
29import static com.google.common.collect.Sets.newTreeSet;
30import static java.util.Arrays.asList;
31import static javax.ws.rs.core.HttpHeaders.ACCEPT;
32import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE;
33import static javax.ws.rs.core.HttpHeaders.HOST;
34import static org.jclouds.io.Payloads.newPayload;
35 
36import java.io.InputStream;
37import java.lang.annotation.Annotation;
38import java.lang.reflect.Array;
39import java.lang.reflect.Method;
40import java.lang.reflect.ParameterizedType;
41import java.lang.reflect.Type;
42import java.lang.reflect.WildcardType;
43import java.net.URI;
44import java.util.Collection;
45import java.util.Collections;
46import java.util.Comparator;
47import java.util.List;
48import java.util.Map;
49import java.util.Set;
50import java.util.SortedSet;
51import java.util.Map.Entry;
52import java.util.concurrent.ConcurrentMap;
53 
54import javax.annotation.Nullable;
55import javax.annotation.Resource;
56import javax.inject.Named;
57import javax.inject.Provider;
58import javax.ws.rs.Consumes;
59import javax.ws.rs.FormParam;
60import javax.ws.rs.HeaderParam;
61import javax.ws.rs.HttpMethod;
62import javax.ws.rs.MatrixParam;
63import javax.ws.rs.Path;
64import javax.ws.rs.PathParam;
65import javax.ws.rs.Produces;
66import javax.ws.rs.QueryParam;
67import javax.ws.rs.core.MediaType;
68import javax.ws.rs.core.UriBuilder;
69import javax.ws.rs.core.UriBuilderException;
70 
71import org.jclouds.Constants;
72import org.jclouds.functions.IdentityFunction;
73import org.jclouds.http.HttpRequest;
74import org.jclouds.http.HttpRequestFilter;
75import org.jclouds.http.HttpResponse;
76import org.jclouds.http.HttpUtils;
77import org.jclouds.http.functions.ParseJson;
78import org.jclouds.http.functions.ParseSax;
79import org.jclouds.http.functions.ParseURIFromListOrLocationHeaderIf20x;
80import org.jclouds.http.functions.ReleasePayloadAndReturn;
81import org.jclouds.http.functions.ReturnInputStream;
82import org.jclouds.http.functions.ReturnStringIf2xx;
83import org.jclouds.http.functions.ReturnTrueIf2xx;
84import org.jclouds.http.functions.UnwrapOnlyJsonValue;
85import org.jclouds.http.functions.UnwrapOnlyJsonValueInSet;
86import org.jclouds.http.functions.UnwrapOnlyNestedJsonValue;
87import org.jclouds.http.functions.UnwrapOnlyNestedJsonValueInSet;
88import org.jclouds.http.functions.ParseSax.HandlerWithResult;
89import org.jclouds.http.options.HttpRequestOptions;
90import org.jclouds.http.utils.ModifyRequest;
91import org.jclouds.internal.ClassMethodArgs;
92import org.jclouds.io.ContentMetadata;
93import org.jclouds.io.Payload;
94import org.jclouds.io.PayloadEnclosing;
95import org.jclouds.io.Payloads;
96import org.jclouds.io.payloads.MultipartForm;
97import org.jclouds.io.payloads.Part;
98import org.jclouds.io.payloads.Part.PartOptions;
99import org.jclouds.logging.Logger;
100import org.jclouds.rest.Binder;
101import org.jclouds.rest.InputParamValidator;
102import org.jclouds.rest.InvocationContext;
103import org.jclouds.rest.annotations.BinderParam;
104import org.jclouds.rest.annotations.Endpoint;
105import org.jclouds.rest.annotations.EndpointParam;
106import org.jclouds.rest.annotations.ExceptionParser;
107import org.jclouds.rest.annotations.FormParams;
108import org.jclouds.rest.annotations.Headers;
109import org.jclouds.rest.annotations.MapBinder;
110import org.jclouds.rest.annotations.MatrixParams;
111import org.jclouds.rest.annotations.OverrideRequestFilters;
112import org.jclouds.rest.annotations.ParamParser;
113import org.jclouds.rest.annotations.PartParam;
114import org.jclouds.rest.annotations.PayloadParam;
115import org.jclouds.rest.annotations.PayloadParams;
116import org.jclouds.rest.annotations.QueryParams;
117import org.jclouds.rest.annotations.RequestFilters;
118import org.jclouds.rest.annotations.ResponseParser;
119import org.jclouds.rest.annotations.SkipEncoding;
120import org.jclouds.rest.annotations.Unwrap;
121import org.jclouds.rest.annotations.VirtualHost;
122import org.jclouds.rest.annotations.WrapWith;
123import org.jclouds.rest.annotations.XMLResponseParser;
124import org.jclouds.rest.binders.BindMapToStringPayload;
125import org.jclouds.rest.binders.BindToJsonPayloadWrappedWith;
126import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions;
127import org.jclouds.util.Maps2;
128import org.jclouds.util.Strings2;
129 
130import com.google.common.annotations.VisibleForTesting;
131import com.google.common.base.Function;
132import com.google.common.base.Predicate;
133import com.google.common.base.Predicates;
134import com.google.common.collect.ImmutableList;
135import com.google.common.collect.ImmutableMultimap;
136import com.google.common.collect.ImmutableSet;
137import com.google.common.collect.Iterables;
138import com.google.common.collect.LinkedHashMultimap;
139import com.google.common.collect.LinkedListMultimap;
140import com.google.common.collect.Lists;
141import com.google.common.collect.MapMaker;
142import com.google.common.collect.Multimap;
143import com.google.common.collect.ImmutableSet.Builder;
144import com.google.common.util.concurrent.ListenableFuture;
145import com.google.inject.Inject;
146import com.google.inject.Injector;
147import com.google.inject.Key;
148import com.google.inject.TypeLiteral;
149import com.google.inject.util.Types;
150 
151/**
152 * Creates http methods based on annotations on a class or interface.
153 * 
154 * @author Adrian Cole
155 */
156public class RestAnnotationProcessor<T> {
157 
158   @Resource
159   protected Logger logger = Logger.NULL;
160 
161   private final Class<T> declaring;
162 
163   // TODO replace with Table object
164   static final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToBinderParamAnnotation = createMethodToIndexOfParamToAnnotation(BinderParam.class);
165   static final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToWrapWithAnnotation = createMethodToIndexOfParamToAnnotation(WrapWith.class);
166   static final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToHeaderParamAnnotations = createMethodToIndexOfParamToAnnotation(HeaderParam.class);
167   static final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToEndpointAnnotations = createMethodToIndexOfParamToAnnotation(Endpoint.class);
168   static final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToEndpointParamAnnotations = createMethodToIndexOfParamToAnnotation(EndpointParam.class);
169   static final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToMatrixParamAnnotations = createMethodToIndexOfParamToAnnotation(MatrixParam.class);
170   static final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToFormParamAnnotations = createMethodToIndexOfParamToAnnotation(FormParam.class);
171   static final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToQueryParamAnnotations = createMethodToIndexOfParamToAnnotation(QueryParam.class);
172   static final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToPathParamAnnotations = createMethodToIndexOfParamToAnnotation(PathParam.class);
173   static final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToPostParamAnnotations = createMethodToIndexOfParamToAnnotation(PayloadParam.class);
174   static final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToPartParamAnnotations = createMethodToIndexOfParamToAnnotation(PartParam.class);
175   static final Map<Method, Map<Integer, Set<Annotation>>> methodToIndexOfParamToParamParserAnnotations = createMethodToIndexOfParamToAnnotation(ParamParser.class);
176   static final Map<MethodKey, Method> delegationMap = newHashMap();
177 
178   static Map<Method, Map<Integer, Set<Annotation>>> createMethodToIndexOfParamToAnnotation(
179            final Class<? extends Annotation> annotation) {
180      return new MapMaker().makeComputingMap(new Function<Method, Map<Integer, Set<Annotation>>>() {
181         public Map<Integer, Set<Annotation>> apply(final Method method) {
182            return new MapMaker().makeComputingMap(new GetAnnotationsForMethodParameterIndex(method, annotation));
183         }
184      });
185   }
186 
187   static class GetAnnotationsForMethodParameterIndex implements Function<Integer, Set<Annotation>> {
188      private final Method method;
189      private final Class<?> clazz;
190 
191      protected GetAnnotationsForMethodParameterIndex(Method method, Class<?> clazz) {
192         this.method = method;
193         this.clazz = clazz;
194      }
195 
196      public Set<Annotation> apply(final Integer index) {
197         return ImmutableSet.<Annotation> copyOf(filter(ImmutableList.copyOf(method.getParameterAnnotations()[index]),
198                  new Predicate<Annotation>() {
199                     public boolean apply(Annotation input) {
200                        return input.annotationType().equals(clazz);
201                     }
202                  }));
203      }
204 
205   }
206 
207   private static final Class<? extends HttpRequestOptions[]> optionsVarArgsClass = new HttpRequestOptions[] {}
208            .getClass();
209 
210   private static final Function<? super Entry<String, String>, ? extends Part> ENTRY_TO_PART = new Function<Entry<String, String>, Part>() {
211 
212      @Override
213      public Part apply(Entry<String, String> from) {
214         return Part.create(from.getKey(), from.getValue());
215      }
216 
217   };
218 
219   static final Map<Method, Set<Integer>> methodToIndexesOfOptions = new MapMaker()
220            .makeComputingMap(new Function<Method, Set<Integer>>() {
221               public Set<Integer> apply(final Method method) {
222                  Builder<Integer> toReturn = ImmutableSet.<Integer> builder();
223                  for (int index = 0; index < method.getParameterTypes().length; index++) {
224                     Class<?> type = method.getParameterTypes()[index];
225                     if (HttpRequestOptions.class.isAssignableFrom(type) || optionsVarArgsClass.isAssignableFrom(type))
226                        toReturn.add(index);
227                  }
228                  return toReturn.build();
229               }
230            });
231 
232   private final ParseSax.Factory parserFactory;
233   private final HttpUtils utils;
234   private final Provider<UriBuilder> uriBuilderProvider;
235   private final ConcurrentMap<Class<?>, Boolean> seedAnnotationCache;
236   private final String apiVersion;
237   private char[] skips;
238 
239   @Inject
240   private InputParamValidator inputParamValidator;
241 
242   @VisibleForTesting
243   Function<HttpResponse, ?> createResponseParser(Method method, HttpRequest request) {
244      return createResponseParser(parserFactory, injector, method, request);
245   }
246 
247   @VisibleForTesting
248   public static Function<HttpResponse, ?> createResponseParser(ParseSax.Factory parserFactory, Injector injector,
249            Method method, HttpRequest request) {
250      Function<HttpResponse, ?> transformer;
251      Class<? extends HandlerWithResult<?>> handler = getSaxResponseParserClassOrNull(method);
252      if (handler != null) {
253         transformer = parserFactory.create(injector.getInstance(handler));
254      } else {
255         transformer = injector.getInstance(getParserOrThrowException(method));
256      }
257      if (transformer instanceof InvocationContext<?>) {
258         ((InvocationContext<?>) transformer).setContext(request);
259      }
260      return transformer;
261   }
262 
263   @VisibleForTesting
264   Function<Exception, ?> createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(Method method) {
265      return createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(injector, method);
266   }
267 
268   @VisibleForTesting
269   public static Function<Exception, ?> createExceptionParserOrThrowResourceNotFoundOn404IfNoAnnotation(
270            Injector injector, Method method) {
271      ExceptionParser annotation = method.getAnnotation(ExceptionParser.class);
272      if (annotation != null) {
273         return injector.getInstance(annotation.value());
274      }
275      return injector.getInstance(MapHttp4xxCodesToExceptions.class);
276   }
277 
278   @SuppressWarnings("unchecked")
279   @Inject
280   public RestAnnotationProcessor(Injector injector, ConcurrentMap<Class<?>, Boolean> seedAnnotationCache,
281            @Named(Constants.PROPERTY_API_VERSION) String apiVersion, ParseSax.Factory parserFactory, HttpUtils utils,
282            TypeLiteral<T> typeLiteral) {
283      this.declaring = (Class<T>) typeLiteral.getRawType();
284      this.injector = injector;
285      this.parserFactory = parserFactory;
286      this.utils = utils;
287      this.uriBuilderProvider = injector.getProvider(UriBuilder.class);
288      this.seedAnnotationCache = seedAnnotationCache;
289      seedAnnotationCache.get(declaring);
290      if (declaring.isAnnotationPresent(SkipEncoding.class)) {
291         skips = declaring.getAnnotation(SkipEncoding.class).value();
292      } else {
293         skips = new char[] {};
294      }
295      this.apiVersion = apiVersion;
296   }
297 
298   public Method getDelegateOrNull(Method in) {
299      return delegationMap.get(new MethodKey(in));
300   }
301 
302   public static class MethodKey {
303 
304      @Override
305      public int hashCode() {
306         final int prime = 31;
307         int result = 1;
308         result = prime * result + ((declaringPackage == null) ? 0 : declaringPackage.hashCode());
309         result = prime * result + ((name == null) ? 0 : name.hashCode());
310         result = prime * result + parameterCount;
311         return result;
312      }
313 
314      @Override
315      public boolean equals(Object obj) {
316         if (this == obj)
317            return true;
318         if (obj == null)
319            return false;
320         if (getClass() != obj.getClass())
321            return false;
322         MethodKey other = (MethodKey) obj;
323         if (declaringPackage == null) {
324            if (other.declaringPackage != null)
325               return false;
326         } else if (!declaringPackage.equals(other.declaringPackage))
327            return false;
328         if (name == null) {
329            if (other.name != null)
330               return false;
331         } else if (!name.equals(other.name))
332            return false;
333         if (parameterCount != other.parameterCount)
334            return false;
335         return true;
336      }
337 
338      private final String name;
339      private final int parameterCount;
340      private final Package declaringPackage;
341 
342      public MethodKey(Method method) {
343         this.name = method.getName();
344         this.declaringPackage = method.getDeclaringClass().getPackage();
345         this.parameterCount = method.getParameterTypes().length;
346      }
347 
348   }
349 
350   final Injector injector;
351 
352   private ClassMethodArgs caller;
353   private URI callerEndpoint;
354 
355   public void setCaller(ClassMethodArgs caller) {
356      seedAnnotationCache.get(caller.getMethod().getDeclaringClass());
357      this.caller = caller;
358      try {
359         callerEndpoint = getEndpointFor(caller.getMethod(), caller.getArgs(), injector);
360      } catch (IllegalStateException e) {
361      }
362   }
363 
364   public GeneratedHttpRequest<T> createRequest(Method method, Object... args) {
365      inputParamValidator.validateMethodParametersOrThrow(method, args);
366      ClassMethodArgs cma = logger.isTraceEnabled() ? new ClassMethodArgs(method.getDeclaringClass(), method, args)
367               : null;
368 
369      URI endpoint = callerEndpoint;
370      try {
371         if (endpoint == null) {
372            endpoint = getEndpointFor(method, args, injector);
373            logger.trace("using endpoint %s for %s", endpoint, cma);
374         } else {
375            logger.trace("using endpoint %s from caller %s for %s", caller, endpoint, cma);
376         }
377      } catch (IllegalStateException e) {
378         logger.trace("looking up default endpoint for %s", cma);
379         endpoint = injector.getInstance(Key.get(URI.class, org.jclouds.location.Provider.class));
380         logger.trace("using default endpoint %s for %s", endpoint, cma);
381      }
382      GeneratedHttpRequest.Builder<T> requestBuilder;
383      HttpRequest r = RestAnnotationProcessor.findHttpRequestInArgs(args);
384      if (r != null) {
385         requestBuilder = GeneratedHttpRequest.Builder.<T> from(r);
386         endpoint = r.getEndpoint();
387      } else {
388         requestBuilder = GeneratedHttpRequest.<T> builder();
389         requestBuilder.method(getHttpMethodOrConstantOrThrowException(method));
390      }
391 
392      requestBuilder.declaring(declaring).javaMethod(method).args(args).skips(skips);
393      requestBuilder.filters(getFiltersIfAnnotated(method));
394 
395      UriBuilder builder = uriBuilderProvider.get().uri(endpoint);
396 
397      Multimap<String, String> tokenValues = LinkedHashMultimap.create();
398 
399      tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion);
400 
401      tokenValues.putAll(addPathAndGetTokens(declaring, method, args, builder));
402 
403      Multimap<String, String> formParams = addFormParams(tokenValues.entries(), method, args);
404      Multimap<String, String> queryParams = addQueryParams(tokenValues.entries(), method, args);
405      Multimap<String, String> matrixParams = addMatrixParams(tokenValues.entries(), method, args);
406      Multimap<String, String> headers = buildHeaders(tokenValues.entries(), method, args);
407      if (r != null)
408         headers.putAll(r.getHeaders());
409 
410      if (shouldAddHostHeader(method)) {
411         StringBuilder hostHeader = new StringBuilder(endpoint.getHost());
412         if (endpoint.getPort() != -1)
413            hostHeader.append(":").append(endpoint.getPort());
414         headers.put(HOST, hostHeader.toString());
415      }
416 
417      Payload payload = null;
418      HttpRequestOptions options = findOptionsIn(method, args);
419      if (options != null) {
420         injector.injectMembers(options);// TODO test case
421         for (Entry<String, String> header : options.buildRequestHeaders().entries()) {
422            headers.put(header.getKey(), Strings2.replaceTokens(header.getValue(), tokenValues.entries()));
423         }
424         for (Entry<String, String> matrix : options.buildMatrixParameters().entries()) {
425            matrixParams.put(matrix.getKey(), Strings2.replaceTokens(matrix.getValue(), tokenValues.entries()));
426         }
427         for (Entry<String, String> query : options.buildQueryParameters().entries()) {
428            queryParams.put(query.getKey(), Strings2.replaceTokens(query.getValue(), tokenValues.entries()));
429         }
430         for (Entry<String, String> form : options.buildFormParameters().entries()) {
431            formParams.put(form.getKey(), Strings2.replaceTokens(form.getValue(), tokenValues.entries()));
432         }
433 
434         String pathSuffix = options.buildPathSuffix();
435         if (pathSuffix != null) {
436            builder.path(pathSuffix);
437         }
438         String stringPayload = options.buildStringPayload();
439         if (stringPayload != null)
440            payload = Payloads.newStringPayload(stringPayload);
441      }
442 
443      if (matrixParams.size() > 0) {
444         for (String key : matrixParams.keySet())
445            builder.matrixParam(key, Lists.newArrayList(matrixParams.get(key)).toArray());
446      }
447 
448      if (queryParams.size() > 0) {
449         builder.replaceQuery(ModifyRequest.makeQueryLine(queryParams, null, skips));
450      }
451 
452      requestBuilder.headers(filterOutContentHeaders(headers));
453 
454      try {
455         requestBuilder.endpoint(builder.buildFromEncodedMap(Maps2.convertUnsafe(tokenValues)));
456      } catch (IllegalArgumentException e) {
457         throw new IllegalStateException(e);
458      } catch (UriBuilderException e) {
459         throw new IllegalStateException(e);
460      }
461 
462      if (payload == null)
463         payload = findPayloadInArgs(args);
464      List<? extends Part> parts = getParts(method, args, concat(tokenValues.entries(), formParams.entries()));
465      if (parts.size() > 0) {
466         if (formParams.size() > 0) {
467            parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts));
468         }
469         payload = new MultipartForm(BOUNDARY, parts);
470      } else if (formParams.size() > 0) {
471         payload = Payloads.newUrlEncodedFormPayload(formParams, skips);
472      } else if (headers.containsKey(CONTENT_TYPE)) {
473         if (payload == null)
474            payload = Payloads.newByteArrayPayload(new byte[] {});
475         payload.getContentMetadata().setContentType(Iterables.get(headers.get(CONTENT_TYPE), 0));
476      }
477      if (payload != null) {
478         requestBuilder.payload(payload);
479      }
480      GeneratedHttpRequest<T> request = requestBuilder.build();
481 
482      org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(method, args);
483      if (mapBinder != null) {
484         Map<String, String> mapParams = buildPostParams(method, args);
485         if (method.isAnnotationPresent(PayloadParams.class)) {
486            PayloadParams params = method.getAnnotation(PayloadParams.class);
487            addMapPayload(mapParams, params, headers.entries());
488         }
489         request = mapBinder.bindToRequest(request, mapParams);
490      } else {
491         request = decorateRequest(request);
492      }
493 
494      if (request.getPayload() != null)
495         request.getPayload().getContentMetadata().setPropertiesFromHttpHeaders(headers);
496      utils.checkRequestHasRequiredProperties(request);
497      return request;
498   }
499 
500   public static Multimap<String, String> filterOutContentHeaders(Multimap<String, String> headers) {
501      // TODO make a filter like {@link Maps.filterKeys} instead of this
502      ImmutableMultimap.Builder<String, String> headersBuilder = ImmutableMultimap.builder();
503      // http message usually comes in as a null key header, let's filter it out.
504      for (String header : Iterables.filter(headers.keySet(), Predicates.notNull())) {
505         if (!ContentMetadata.HTTP_HEADERS.contains(header)) {
506            headersBuilder.putAll(header, headers.get(header));
507         }
508      }
509      return headersBuilder.build();
510   }
511 
512   public static final String BOUNDARY = "--JCLOUDS--";
513 
514   private Multimap<String, String> addPathAndGetTokens(Class<?> clazz, Method method, Object[] args, UriBuilder builder) {
515      if (clazz.isAnnotationPresent(Path.class))
516         builder.path(clazz);
517      if (method.isAnnotationPresent(Path.class))
518         builder.path(method);
519      return encodeValues(getPathParamKeyValues(method, args), skips);
520   }
521 
522   public URI replaceQuery(URI in, String newQuery, @Nullable Comparator<Entry<String, String>> sorter) {
523      return replaceQuery(uriBuilderProvider, in, newQuery, sorter, skips);
524   }
525 
526   public static URI replaceQuery(Provider<UriBuilder> uriBuilderProvider, URI in, String newQuery,
527            @Nullable Comparator<Entry<String, String>> sorter, char... skips) {
528      UriBuilder builder = uriBuilderProvider.get().uri(in);
529      builder.replaceQuery(ModifyRequest.makeQueryLine(ModifyRequest.parseQueryToMap(newQuery), sorter, skips));
530      return builder.build();
531   }
532 
533   private Multimap<String, String> addMatrixParams(Collection<Entry<String, String>> tokenValues, Method method,
534            Object... args) {
535      Multimap<String, String> matrixMap = LinkedListMultimap.create();
536      if (declaring.isAnnotationPresent(MatrixParams.class)) {
537         MatrixParams matrix = declaring.getAnnotation(MatrixParams.class);
538         addMatrix(matrixMap, matrix, tokenValues);
539      }
540 
541      if (method.isAnnotationPresent(MatrixParams.class)) {
542         MatrixParams matrix = method.getAnnotation(MatrixParams.class);
543         addMatrix(matrixMap, matrix, tokenValues);
544      }
545 
546      for (Entry<String, String> matrix : getMatrixParamKeyValues(method, args).entries()) {
547         matrixMap.put(matrix.getKey(), Strings2.replaceTokens(matrix.getValue(), tokenValues));
548      }
549      return matrixMap;
550   }
551 
552   private Multimap<String, String> addFormParams(Collection<Entry<String, String>> tokenValues, Method method,
553            Object... args) {
554      Multimap<String, String> formMap = LinkedListMultimap.create();
555      if (declaring.isAnnotationPresent(FormParams.class)) {
556         FormParams form = declaring.getAnnotation(FormParams.class);
557         addForm(formMap, form, tokenValues);
558      }
559 
560      if (method.isAnnotationPresent(FormParams.class)) {
561         FormParams form = method.getAnnotation(FormParams.class);
562         addForm(formMap, form, tokenValues);
563      }
564 
565      for (Entry<String, String> form : getFormParamKeyValues(method, args).entries()) {
566         formMap.put(form.getKey(), Strings2.replaceTokens(form.getValue(), tokenValues));
567      }
568      return formMap;
569   }
570 
571   private Multimap<String, String> addQueryParams(Collection<Entry<String, String>> tokenValues, Method method,
572            Object... args) {
573      Multimap<String, String> queryMap = LinkedListMultimap.create();
574      if (declaring.isAnnotationPresent(QueryParams.class)) {
575         QueryParams query = declaring.getAnnotation(QueryParams.class);
576         addQuery(queryMap, query, tokenValues);
577      }
578 
579      if (method.isAnnotationPresent(QueryParams.class)) {
580         QueryParams query = method.getAnnotation(QueryParams.class);
581         addQuery(queryMap, query, tokenValues);
582      }
583 
584      for (Entry<String, String> query : getQueryParamKeyValues(method, args).entries()) {
585         queryMap.put(query.getKey(), Strings2.replaceTokens(query.getValue(), tokenValues));
586      }
587      return queryMap;
588   }
589 
590   private void addForm(Multimap<String, String> formParams, FormParams form,
591            Collection<Entry<String, String>> tokenValues) {
592      for (int i = 0; i < form.keys().length; i++) {
593         if (form.values()[i].equals(FormParams.NULL)) {
594            formParams.removeAll(form.keys()[i]);
595            formParams.put(form.keys()[i], null);
596         } else {
597            formParams.put(form.keys()[i], Strings2.replaceTokens(form.values()[i], tokenValues));
598         }
599      }
600   }
601 
602   private void addQuery(Multimap<String, String> queryParams, QueryParams query,
603            Collection<Entry<String, String>> tokenValues) {
604      for (int i = 0; i < query.keys().length; i++) {
605         if (query.values()[i].equals(QueryParams.NULL)) {
606            queryParams.removeAll(query.keys()[i]);
607            queryParams.put(query.keys()[i], null);
608         } else {
609            queryParams.put(query.keys()[i], Strings2.replaceTokens(query.values()[i], tokenValues));
610         }
611      }
612   }
613 
614   private void addMatrix(Multimap<String, String> matrixParams, MatrixParams matrix,
615            Collection<Entry<String, String>> tokenValues) {
616      for (int i = 0; i < matrix.keys().length; i++) {
617         if (matrix.values()[i].equals(MatrixParams.NULL)) {
618            matrixParams.removeAll(matrix.keys()[i]);
619            matrixParams.put(matrix.keys()[i], null);
620         } else {
621            matrixParams.put(matrix.keys()[i], Strings2.replaceTokens(matrix.values()[i], tokenValues));
622         }
623      }
624   }
625 
626   private void addMapPayload(Map<String, String> postParams, PayloadParams mapDefaults,
627            Collection<Entry<String, String>> tokenValues) {
628      for (int i = 0; i < mapDefaults.keys().length; i++) {
629         if (mapDefaults.values()[i].equals(PayloadParams.NULL)) {
630            postParams.put(mapDefaults.keys()[i], null);
631         } else {
632            postParams.put(mapDefaults.keys()[i], Strings2.replaceTokens(mapDefaults.values()[i], tokenValues));
633         }
634      }
635   }
636 
637   @VisibleForTesting
638   List<HttpRequestFilter> getFiltersIfAnnotated(Method method) {
639      List<HttpRequestFilter> filters = Lists.newArrayList();
640      if (declaring.isAnnotationPresent(RequestFilters.class)) {
641         for (Class<? extends HttpRequestFilter> clazz : declaring.getAnnotation(RequestFilters.class).value()) {
642            HttpRequestFilter instance = injector.getInstance(clazz);
643            filters.add(instance);
644            logger.trace("adding filter %s from annotation on %s", instance, declaring.getName());
645         }
646      }
647      if (method.isAnnotationPresent(RequestFilters.class)) {
648         if (method.isAnnotationPresent(OverrideRequestFilters.class))
649            filters.clear();
650         for (Class<? extends HttpRequestFilter> clazz : method.getAnnotation(RequestFilters.class).value()) {
651            HttpRequestFilter instance = injector.getInstance(clazz);
652            filters.add(instance);
653            logger.trace("adding filter %s from annotation on %s", instance, method.getName());
654         }
655      }
656      return filters;
657   }
658 
659   @VisibleForTesting
660   public static URI getEndpointInParametersOrNull(Method method, final Object[] args, Injector injector) {
661      Map<Integer, Set<Annotation>> map = indexWithAtLeastOneAnnotation(method,
662               methodToIndexOfParamToEndpointParamAnnotations);
663      if (map.size() >= 1 && args.length > 0) {
664         EndpointParam firstAnnotation = (EndpointParam) get(get(map.values(), 0), 0);
665         Function<Object, URI> parser = injector.getInstance(firstAnnotation.parser());
666 
667         if (map.size() == 1) {
668            int index = map.keySet().iterator().next();
669            try {
670               URI returnVal = parser.apply(args[index]);
671               checkArgument(returnVal != null, String.format("endpoint for [%s] not configured for %s", args[index],
672                        method));
673               return returnVal;
674            } catch (NullPointerException e) {
675               throw new IllegalArgumentException(String.format("argument at index %d on method %s", index, method), e);
676            }
677         } else {
678            SortedSet<Integer> keys = newTreeSet(map.keySet());
679            Iterable<Object> argsToParse = transform(keys, new Function<Integer, Object>() {
680 
681               @Override
682               public Object apply(Integer from) {
683                  return args[from];
684               }
685 
686            });
687            try {
688               URI returnVal = parser.apply(argsToParse);
689               checkArgument(returnVal != null, String.format("endpoint for [%s] not configured for %s", argsToParse,
690                        method));
691               return returnVal;
692            } catch (NullPointerException e) {
693               throw new IllegalArgumentException(String.format("argument at indexes %s on method %s", map.keySet(),
694                        method), e);
695            }
696         }
697      }
698      return null;
699   }
700 
701   public static URI getEndpointFor(Method method, Object[] args, Injector injector) {
702      URI endpoint = getEndpointInParametersOrNull(method, args, injector);
703      if (endpoint == null) {
704         Endpoint annotation;
705         if (method.isAnnotationPresent(Endpoint.class)) {
706            annotation = method.getAnnotation(Endpoint.class);
707         } else if (method.getDeclaringClass().isAnnotationPresent(Endpoint.class)) {
708            annotation = method.getDeclaringClass().getAnnotation(Endpoint.class);
709         } else {
710            throw new IllegalStateException("no annotations on class or method: " + method);
711         }
712         return injector.getInstance(Key.get(URI.class, annotation.value()));
713      }
714      return endpoint;
715   }
716 
717   public static final TypeLiteral<ListenableFuture<Boolean>> futureBooleanLiteral = new TypeLiteral<ListenableFuture<Boolean>>() {
718   };
719   public static final TypeLiteral<ListenableFuture<String>> futureStringLiteral = new TypeLiteral<ListenableFuture<String>>() {
720   };
721   public static final TypeLiteral<ListenableFuture<Void>> futureVoidLiteral = new TypeLiteral<ListenableFuture<Void>>() {
722   };
723   public static final TypeLiteral<ListenableFuture<URI>> futureURILiteral = new TypeLiteral<ListenableFuture<URI>>() {
724   };
725   public static final TypeLiteral<ListenableFuture<InputStream>> futureInputStreamLiteral = new TypeLiteral<ListenableFuture<InputStream>>() {
726   };
727   public static final TypeLiteral<ListenableFuture<HttpResponse>> futureHttpResponseLiteral = new TypeLiteral<ListenableFuture<HttpResponse>>() {
728   };
729 
730   @SuppressWarnings( { "unchecked", "rawtypes" })
731   public static Key<? extends Function<HttpResponse, ?>> getParserOrThrowException(Method method) {
732      ResponseParser annotation = method.getAnnotation(ResponseParser.class);
733      if (annotation == null) {
734         if (method.getReturnType().equals(void.class)
735                  || TypeLiteral.get(method.getGenericReturnType()).equals(futureVoidLiteral)) {
736            return Key.get(ReleasePayloadAndReturn.class);
737         } else if (method.getReturnType().equals(boolean.class) || method.getReturnType().equals(Boolean.class)
738                  || TypeLiteral.get(method.getGenericReturnType()).equals(futureBooleanLiteral)) {
739            return Key.get(ReturnTrueIf2xx.class);
740         } else if (method.getReturnType().equals(InputStream.class)
741                  || TypeLiteral.get(method.getGenericReturnType()).equals(futureInputStreamLiteral)) {
742            return Key.get(ReturnInputStream.class);
743         } else if (method.getReturnType().equals(HttpResponse.class)
744                  || TypeLiteral.get(method.getGenericReturnType()).equals(futureHttpResponseLiteral)) {
745            return Key.get((Class) IdentityFunction.class);
746         } else if (getAcceptHeadersOrNull(method).contains(MediaType.APPLICATION_JSON)) {
747            return getJsonParserKeyForMethod(method);
748         } else if (method.getReturnType().equals(String.class)
749                  || TypeLiteral.get(method.getGenericReturnType()).equals(futureStringLiteral)) {
750            return Key.get(ReturnStringIf2xx.class);
751         } else if (method.getReturnType().equals(URI.class)
752                  || TypeLiteral.get(method.getGenericReturnType()).equals(futureURILiteral)) {
753            return Key.get(ParseURIFromListOrLocationHeaderIf20x.class);
754         } else {
755            throw new IllegalStateException("You must specify a ResponseParser annotation on: " + method.toString());
756         }
757      }
758      return Key.get(annotation.value());
759   }
760 
761   public static Key<? extends Function<HttpResponse, ?>> getJsonParserKeyForMethod(Method method) {
762      Type returnVal = getReturnTypeForMethod(method);
763      return getJsonParserKeyForMethodAnType(method, returnVal);
764   }
765 
766   public static Type getReturnTypeForMethod(Method method) {
767      Type returnVal;
768      if (method.getReturnType().getTypeParameters().length == 0) {
769         returnVal = method.getReturnType();
770      } else if (method.getReturnType().equals(ListenableFuture.class)) {
771         ParameterizedType futureType = ((ParameterizedType) method.getGenericReturnType());
772         returnVal = futureType.getActualTypeArguments()[0];
773         if (returnVal instanceof WildcardType)
774            returnVal = WildcardType.class.cast(returnVal).getUpperBounds()[0];
775      } else {
776         returnVal = method.getGenericReturnType();
777      }
778      return returnVal;
779   }
780 
781   @SuppressWarnings( { "unchecked", "rawtypes" })
782   public static Key<? extends Function<HttpResponse, ?>> getJsonParserKeyForMethodAnType(Method method, Type returnVal) {
783      ParameterizedType parserType;
784      if (method.isAnnotationPresent(Unwrap.class)) {
785         int depth = method.getAnnotation(Unwrap.class).depth();
786         Class edgeCollection = method.getAnnotation(Unwrap.class).edgeCollection();
787         if (depth == 1 && edgeCollection == Map.class)
788            parserType = Types.newParameterizedType(UnwrapOnlyJsonValue.class, returnVal);
789         else if (depth == 2 && edgeCollection == Map.class)
790            parserType = Types.newParameterizedType(UnwrapOnlyNestedJsonValue.class, returnVal);
791         else if (depth == 2 && edgeCollection == Set.class)
792            parserType = Types.newParameterizedType(UnwrapOnlyJsonValueInSet.class, returnVal);
793         else if (depth == 3 && edgeCollection == Set.class)
794            parserType = Types.newParameterizedType(UnwrapOnlyNestedJsonValueInSet.class, returnVal);
795         else
796            throw new IllegalStateException(String.format("depth(%d) edgeCollection(%s) not yet supported for @Unwrap",
797                     depth, edgeCollection));
798      } else {
799         parserType = Types.newParameterizedType(ParseJson.class, returnVal);
800      }
801      return (Key<? extends Function<HttpResponse, ?>>) Key.get(parserType);
802   }
803 
804   public static Class<? extends HandlerWithResult<?>> getSaxResponseParserClassOrNull(Method method) {
805      XMLResponseParser annotation = method.getAnnotation(XMLResponseParser.class);
806      if (annotation != null) {
807         return annotation.value();
808      }
809      return null;
810   }
811 
812   public org.jclouds.rest.MapBinder getMapPayloadBinderOrNull(Method method, Object... args) {
813      if (args != null) {
814         for (Object arg : args) {
815            if (arg instanceof Object[]) {
816               Object[] postBinders = (Object[]) arg;
817               if (postBinders.length == 0) {
818               } else if (postBinders.length == 1) {
819                  if (postBinders[0] instanceof org.jclouds.rest.MapBinder) {
820                     org.jclouds.rest.MapBinder binder = (org.jclouds.rest.MapBinder) postBinders[0];
821                     injector.injectMembers(binder);
822                     return binder;
823                  }
824               } else {
825                  if (postBinders[0] instanceof org.jclouds.rest.MapBinder) {
826                     throw new IllegalArgumentException("we currently do not support multiple varargs postBinders in: "
827                              + method.getName());
828                  }
829               }
830            } else if (arg instanceof org.jclouds.rest.MapBinder) {
831               org.jclouds.rest.MapBinder binder = (org.jclouds.rest.MapBinder) arg;
832               injector.injectMembers(binder);
833               return binder;
834            }
835         }
836      }
837      if (method.isAnnotationPresent(MapBinder.class)) {
838         return injector.getInstance(method.getAnnotation(MapBinder.class).value());
839      } else if (method.isAnnotationPresent(org.jclouds.rest.annotations.Payload.class)) {
840         return injector.getInstance(BindMapToStringPayload.class);
841      }
842      return null;
843   }
844 
845   public static Set<String> getHttpMethods(Method method) {
846      Builder<String> methodsBuilder = ImmutableSet.<String> builder();
847      for (Annotation annotation : method.getAnnotations()) {
848         HttpMethod http = annotation.annotationType().getAnnotation(HttpMethod.class);
849         if (http != null)
850            methodsBuilder.add(http.value());
851      }
852      Set<String> methods = methodsBuilder.build();
853      return (methods.size() == 0) ? null : methods;
854   }
855 
856   public String getHttpMethodOrConstantOrThrowException(Method method) {
857      Set<String> requests = getHttpMethods(method);
858      if (requests == null || requests.size() != 1) {
859         throw new IllegalStateException(
860                  "You must use at least one, but no more than one http method or pathparam annotation on: "
861                           + method.toString());
862      }
863      return requests.iterator().next();
864   }
865 
866   public boolean shouldAddHostHeader(Method method) {
867      if (declaring.isAnnotationPresent(VirtualHost.class) || method.isAnnotationPresent(VirtualHost.class)) {
868         return true;
869      }
870      return false;
871   }
872 
873   private static final Predicate<Set<?>> notEmpty = new Predicate<Set<?>>() {
874      public boolean apply(Set<?> input) {
875         return input.size() >= 1;
876      }
877   };
878 
879   public GeneratedHttpRequest<T> decorateRequest(GeneratedHttpRequest<T> request) {
880      OUTER: for (Entry<Integer, Set<Annotation>> entry : concat(//
881               filterValues(methodToIndexOfParamToBinderParamAnnotation.get(request.getJavaMethod()), notEmpty)
882                        .entrySet(), //
883               filterValues(methodToIndexOfParamToWrapWithAnnotation.get(request.getJavaMethod()), notEmpty).entrySet())) {
884         boolean shouldBreak = false;
885         Annotation annotation = Iterables.get(entry.getValue(), 0);
886         Binder binder;
887         if (annotation instanceof BinderParam)
888            binder = injector.getInstance(BinderParam.class.cast(annotation).value());
889         else
890            binder = injector.getInstance(BindToJsonPayloadWrappedWith.Factory.class).create(
891                     WrapWith.class.cast(annotation).value());
892         if (request.getArgs().size() >= entry.getKey() + 1 && request.getArgs().get(entry.getKey()) != null) {
893            Object input;
894            Class<?> parameterType = request.getJavaMethod().getParameterTypes()[entry.getKey()];
895            Class<? extends Object> argType = request.getArgs().get(entry.getKey()).getClass();
896            if (!argType.isArray() && request.getJavaMethod().isVarArgs() && parameterType.isArray()) {
897               int arrayLength = request.getArgs().size() - request.getJavaMethod().getParameterTypes().length + 1;
898               if (arrayLength == 0)
899                  break OUTER;
900               input = (Object[]) Array.newInstance(request.getArgs().get(entry.getKey()).getClass(), arrayLength);
901               System.arraycopy(request.getArgs().toArray(), entry.getKey(), input, 0, arrayLength);
902               shouldBreak = true;
903            } else if (argType.isArray() && request.getJavaMethod().isVarArgs() && parameterType.isArray()) {
904               input = request.getArgs().get(entry.getKey());
905            } else {
906               input = request.getArgs().get(entry.getKey());
907               if (input.getClass().isArray()) {
908                  Object[] payloadArray = (Object[]) input;
909                  input = payloadArray.length > 0 ? payloadArray[0] : null;
910               }
911            }
912            if (input != null) {
913               request = binder.bindToRequest(request, input);
914            }
915            if (shouldBreak)
916               break OUTER;
917         }
918      }
919 
920      return request;
921   }
922 
923   public static Map<Integer, Set<Annotation>> indexWithOnlyOneAnnotation(Method method, String description,
924            Map<Method, Map<Integer, Set<Annotation>>> toRefine) {
925      Map<Integer, Set<Annotation>> indexToPayloadAnnotation = indexWithAtLeastOneAnnotation(method, toRefine);
926      if (indexToPayloadAnnotation.size() > 1) {
927         throw new IllegalStateException(String.format(
928                  "You must not specify more than one %s annotation on: %s; found %s", description, method.toString(),
929                  indexToPayloadAnnotation));
930      }
931      return indexToPayloadAnnotation;
932   }
933 
934   private static Map<Integer, Set<Annotation>> indexWithAtLeastOneAnnotation(Method method,
935            Map<Method, Map<Integer, Set<Annotation>>> toRefine) {
936      Map<Integer, Set<Annotation>> indexToPayloadAnnotation = filterValues(toRefine.get(method),
937               new Predicate<Set<Annotation>>() {
938                  public boolean apply(Set<Annotation> input) {
939                     return input.size() == 1;
940                  }
941               });
942      return indexToPayloadAnnotation;
943   }
944 
945   private HttpRequestOptions findOptionsIn(Method method, Object... args) {
946      for (int index : methodToIndexesOfOptions.get(method)) {
947         if (args.length >= index + 1) {// accomodate varargs
948            if (args[index] instanceof Object[]) {
949               Object[] options = (Object[]) args[index];
950               if (options.length == 0) {
951               } else if (options.length == 1) {
952                  if (options[0] instanceof HttpRequestOptions) {
953                     HttpRequestOptions binder = (HttpRequestOptions) options[0];
954                     injector.injectMembers(binder);
955                     return binder;
956                  }
957               } else {
958                  if (options[0] instanceof HttpRequestOptions) {
959                     throw new IllegalArgumentException("we currently do not support multiple varargs options in: "
960                              + method.getName());
961                  }
962               }
963            } else {
964               return (HttpRequestOptions) args[index];
965            }
966         }
967      }
968      return null;
969   }
970 
971   public Multimap<String, String> buildHeaders(Collection<Entry<String, String>> tokenValues, Method method,
972            final Object... args) {
973      Multimap<String, String> headers = LinkedHashMultimap.create();
974      addHeaderIfAnnotationPresentOnMethod(headers, method, tokenValues);
975      Map<Integer, Set<Annotation>> indexToHeaderParam = methodToIndexOfParamToHeaderParamAnnotations.get(method);
976      for (Entry<Integer, Set<Annotation>> entry : indexToHeaderParam.entrySet()) {
977         for (Annotation key : entry.getValue()) {
978            String value = args[entry.getKey()].toString();
979            value = Strings2.replaceTokens(value, tokenValues);
980            headers.put(((HeaderParam) key).value(), value);
981         }
982      }
983      addProducesIfPresentOnTypeOrMethod(headers, method);
984      addConsumesIfPresentOnTypeOrMethod(headers, method);
985      return headers;
986   }
987 
988   void addConsumesIfPresentOnTypeOrMethod(Multimap<String, String> headers, Method method) {
989      List<String> accept = getAcceptHeadersOrNull(method);
990      if (accept.size() > 0)
991         headers.replaceValues(ACCEPT, accept);
992   }
993 
994   private static List<String> getAcceptHeadersOrNull(Method method) {
995      List<String> accept = Collections.emptyList();
996      if (method.getDeclaringClass().isAnnotationPresent(Consumes.class)) {
997         Consumes header = method.getDeclaringClass().getAnnotation(Consumes.class);
998         accept = asList(header.value());
999      }
1000      if (method.isAnnotationPresent(Consumes.class)) {
1001         Consumes header = method.getAnnotation(Consumes.class);
1002         accept = asList(header.value());
1003      }
1004      return accept;
1005   }
1006 
1007   void addProducesIfPresentOnTypeOrMethod(Multimap<String, String> headers, Method method) {
1008      if (declaring.isAnnotationPresent(Produces.class)) {
1009         Produces header = declaring.getAnnotation(Produces.class);
1010         headers.replaceValues(CONTENT_TYPE, asList(header.value()));
1011      }
1012      if (method.isAnnotationPresent(Produces.class)) {
1013         Produces header = method.getAnnotation(Produces.class);
1014         headers.replaceValues(CONTENT_TYPE, asList(header.value()));
1015      }
1016   }
1017 
1018   public void addHeaderIfAnnotationPresentOnMethod(Multimap<String, String> headers, Method method,
1019            Collection<Entry<String, String>> tokenValues) {
1020      if (declaring.isAnnotationPresent(Headers.class)) {
1021         Headers header = declaring.getAnnotation(Headers.class);
1022         addHeader(headers, header, tokenValues);
1023      }
1024      if (method.isAnnotationPresent(Headers.class)) {
1025         Headers header = method.getAnnotation(Headers.class);
1026         addHeader(headers, header, tokenValues);
1027      }
1028   }
1029 
1030   private void addHeader(Multimap<String, String> headers, Headers header,
1031            Collection<Entry<String, String>> tokenValues) {
1032      for (int i = 0; i < header.keys().length; i++) {
1033         String value = header.values()[i];
1034         value = Strings2.replaceTokens(value, tokenValues);
1035         headers.put(header.keys()[i], value);
1036      }
1037 
1038   }
1039 
1040   List<? extends Part> getParts(Method method, Object[] args, Iterable<Entry<String, String>> iterable) {
1041      List<Part> parts = newLinkedList();
1042      Map<Integer, Set<Annotation>> indexToPartParam = methodToIndexOfParamToPartParamAnnotations.get(method);
1043      for (Entry<Integer, Set<Annotation>> entry : indexToPartParam.entrySet()) {
1044         for (Annotation key : entry.getValue()) {
1045            PartParam param = (PartParam) key;
1046            PartOptions options = new PartOptions();
1047            if (!PartParam.NO_CONTENT_TYPE.equals(param.contentType()))
1048               options.contentType(param.contentType());
1049            if (!PartParam.NO_FILENAME.equals(param.filename()))
1050               options.filename(Strings2.replaceTokens(param.filename(), iterable));
1051            Part part = Part.create(param.name(), newPayload(args[entry.getKey()]), options);
1052            parts.add(part);
1053         }
1054      }
1055      return parts;
1056   }
1057 
1058   public static HttpRequest findHttpRequestInArgs(Object[] args) {
1059      if (args == null)
1060         return null;
1061      for (int i = 0; i < args.length; i++)
1062         if (args[i] instanceof HttpRequest)
1063            return HttpRequest.class.cast(args[i]);
1064      return null;
1065   }
1066 
1067   public static Payload findPayloadInArgs(Object[] args) {
1068      if (args == null)
1069         return null;
1070      for (int i = 0; i < args.length; i++)
1071         if (args[i] instanceof Payload)
1072            return Payload.class.cast(args[i]);
1073         else if (args[i] instanceof PayloadEnclosing)
1074            return PayloadEnclosing.class.cast(args[i]).getPayload();
1075      return null;
1076   }
1077 
1078   private Multimap<String, String> getPathParamKeyValues(Method method, Object... args) {
1079      Multimap<String, String> pathParamValues = LinkedHashMultimap.create();
1080      Map<Integer, Set<Annotation>> indexToPathParam = methodToIndexOfParamToPathParamAnnotations.get(method);
1081 
1082      Map<Integer, Set<Annotation>> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations.get(method);
1083      for (Entry<Integer, Set<Annotation>> entry : indexToPathParam.entrySet()) {
1084         for (Annotation key : entry.getValue()) {
1085            Set<Annotation> extractors = indexToParamExtractor.get(entry.getKey());
1086            String paramKey = ((PathParam) key).value();
1087            String paramValue;
1088            if (extractors != null && extractors.size() > 0) {
1089               ParamParser extractor = (ParamParser) extractors.iterator().next();
1090               paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]);
1091            } else {
1092               paramValue = args[entry.getKey()].toString();
1093            }
1094            pathParamValues.put(paramKey, paramValue);
1095         }
1096      }
1097 
1098      if (method.isAnnotationPresent(PathParam.class) && method.isAnnotationPresent(ParamParser.class)) {
1099         String paramKey = method.getAnnotation(PathParam.class).value();
1100         String paramValue = injector.getInstance(method.getAnnotation(ParamParser.class).value()).apply(args);
1101         pathParamValues.put(paramKey, paramValue);
1102 
1103      }
1104      return pathParamValues;
1105   }
1106 
1107   private Multimap<String, String> encodeValues(Multimap<String, String> unencoded, char... skips) {
1108      Multimap<String, String> encoded = LinkedHashMultimap.create();
1109      for (Entry<String, String> entry : unencoded.entries()) {
1110         encoded.put(entry.getKey(), Strings2.urlEncode(entry.getValue(), skips));
1111      }
1112      return encoded;
1113   }
1114 
1115   private Multimap<String, String> getMatrixParamKeyValues(Method method, Object... args) {
1116      Multimap<String, String> matrixParamValues = LinkedHashMultimap.create();
1117      Map<Integer, Set<Annotation>> indexToMatrixParam = methodToIndexOfParamToMatrixParamAnnotations.get(method);
1118 
1119      Map<Integer, Set<Annotation>> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations.get(method);
1120      for (Entry<Integer, Set<Annotation>> entry : indexToMatrixParam.entrySet()) {
1121         for (Annotation key : entry.getValue()) {
1122            Set<Annotation> extractors = indexToParamExtractor.get(entry.getKey());
1123            String paramKey = ((MatrixParam) key).value();
1124            String paramValue;
1125            if (extractors != null && extractors.size() > 0) {
1126               ParamParser extractor = (ParamParser) extractors.iterator().next();
1127               paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]);
1128            } else {
1129               paramValue = args[entry.getKey()].toString();
1130            }
1131            matrixParamValues.put(paramKey, paramValue);
1132         }
1133      }
1134 
1135      if (method.isAnnotationPresent(MatrixParam.class) && method.isAnnotationPresent(ParamParser.class)) {
1136         String paramKey = method.getAnnotation(MatrixParam.class).value();
1137         String paramValue = injector.getInstance(method.getAnnotation(ParamParser.class).value()).apply(args);
1138         matrixParamValues.put(paramKey, paramValue);
1139 
1140      }
1141      return matrixParamValues;
1142   }
1143 
1144   private Multimap<String, String> getFormParamKeyValues(Method method, Object... args) {
1145      Multimap<String, String> formParamValues = LinkedHashMultimap.create();
1146      Map<Integer, Set<Annotation>> indexToFormParam = methodToIndexOfParamToFormParamAnnotations.get(method);
1147 
1148      Map<Integer, Set<Annotation>> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations.get(method);
1149      for (Entry<Integer, Set<Annotation>> entry : indexToFormParam.entrySet()) {
1150         for (Annotation key : entry.getValue()) {
1151            Set<Annotation> extractors = indexToParamExtractor.get(entry.getKey());
1152            String paramKey = ((FormParam) key).value();
1153            String paramValue;
1154            if (extractors != null && extractors.size() > 0) {
1155               ParamParser extractor = (ParamParser) extractors.iterator().next();
1156               paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]);
1157            } else {
1158               paramValue = args[entry.getKey()].toString();
1159            }
1160            formParamValues.put(paramKey, paramValue);
1161         }
1162      }
1163 
1164      if (method.isAnnotationPresent(FormParam.class) && method.isAnnotationPresent(ParamParser.class)) {
1165         String paramKey = method.getAnnotation(FormParam.class).value();
1166         String paramValue = injector.getInstance(method.getAnnotation(ParamParser.class).value()).apply(args);
1167         formParamValues.put(paramKey, paramValue);
1168 
1169      }
1170      return formParamValues;
1171   }
1172 
1173   private Multimap<String, String> getQueryParamKeyValues(Method method, Object... args) {
1174      Multimap<String, String> queryParamValues = LinkedHashMultimap.create();
1175      Map<Integer, Set<Annotation>> indexToQueryParam = methodToIndexOfParamToQueryParamAnnotations.get(method);
1176 
1177      Map<Integer, Set<Annotation>> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations.get(method);
1178      for (Entry<Integer, Set<Annotation>> entry : indexToQueryParam.entrySet()) {
1179         for (Annotation key : entry.getValue()) {
1180            Set<Annotation> extractors = indexToParamExtractor.get(entry.getKey());
1181            String paramKey = ((QueryParam) key).value();
1182            String paramValue;
1183            if (extractors != null && extractors.size() > 0) {
1184               ParamParser extractor = (ParamParser) extractors.iterator().next();
1185               paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]);
1186            } else {
1187               paramValue = args[entry.getKey()].toString();
1188            }
1189            queryParamValues.put(paramKey, paramValue);
1190         }
1191      }
1192 
1193      if (method.isAnnotationPresent(QueryParam.class) && method.isAnnotationPresent(ParamParser.class)) {
1194         String paramKey = method.getAnnotation(QueryParam.class).value();
1195         String paramValue = injector.getInstance(method.getAnnotation(ParamParser.class).value()).apply(args);
1196         queryParamValues.put(paramKey, paramValue);
1197 
1198      }
1199      return queryParamValues;
1200   }
1201 
1202   private Map<String, String> buildPostParams(Method method, Object... args) {
1203      Map<String, String> postParams = newHashMap();
1204      Map<Integer, Set<Annotation>> indexToPathParam = methodToIndexOfParamToPostParamAnnotations.get(method);
1205      Map<Integer, Set<Annotation>> indexToParamExtractor = methodToIndexOfParamToParamParserAnnotations.get(method);
1206      for (Entry<Integer, Set<Annotation>> entry : indexToPathParam.entrySet()) {
1207         for (Annotation key : entry.getValue()) {
1208            Set<Annotation> extractors = indexToParamExtractor.get(entry.getKey());
1209            String paramKey = ((PayloadParam) key).value();
1210            String paramValue;
1211            if (extractors != null && extractors.size() > 0) {
1212               ParamParser extractor = (ParamParser) extractors.iterator().next();
1213               paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]);
1214            } else {
1215               paramValue = args[entry.getKey()] != null ? args[entry.getKey()].toString() : null;
1216            }
1217            postParams.put(paramKey, paramValue);
1218 
1219         }
1220      }
1221      return postParams;
1222   }
1223 
1224}

[all classes][org.jclouds.rest.internal]
EMMA 2.0.5312 (C) Vladimir Roubtsov