EMMA Coverage Report (generated Mon Oct 17 05:41:20 EDT 2011)
[all classes][org.jclouds.aws.util]

COVERAGE SUMMARY FOR SOURCE FILE [AWSUtils.java]

nameclass, %method, %block, %line, %
AWSUtils.java50%  (1/2)14%  (2/14)11%  (86/752)16%  (16/98)

COVERAGE BREAKDOWN BY CLASS AND METHOD

nameclass, %method, %block, %line, %
     
class AWSUtils$GetRegionFromLocation0%   (0/1)0%   (0/2)0%   (0/16)0%   (0/3)
AWSUtils$GetRegionFromLocation (): void 0%   (0/1)0%   (0/3)0%   (0/1)
apply (Location): String 0%   (0/1)0%   (0/13)0%   (0/2)
     
class AWSUtils100% (1/1)17%  (2/12)12%  (86/736)17%  (16/95)
findRegionInArgsOrNull (GeneratedHttpRequest): String 0%   (0/1)0%   (0/24)0%   (0/7)
getRegionFromLocationOrNull (Location): String 0%   (0/1)0%   (0/11)0%   (0/1)
indexIterableToFormValuesWithPrefix (HttpRequest, String, Object): HttpRequest 0%   (0/1)0%   (0/75)0%   (0/8)
indexMapOfIterableToFormValuesWithPrefix (HttpRequest, String, String, String... 0%   (0/1)0%   (0/123)0%   (0/14)
indexMapToFormValuesWithPrefix (HttpRequest, String, String, String, Object):... 0%   (0/1)0%   (0/103)0%   (0/11)
indexMultimapToFormValuesWithPrefix (HttpRequest, String, String, String, Obj... 0%   (0/1)0%   (0/116)0%   (0/14)
indexStringArrayToFormValuesWithPrefix (HttpRequest, String, Object): HttpReq... 0%   (0/1)0%   (0/72)0%   (0/7)
indexStringArrayToFormValuesWithStringFormat (HttpRequest, String, Object): H... 0%   (0/1)0%   (0/71)0%   (0/7)
isRegion (String): boolean 0%   (0/1)0%   (0/4)0%   (0/1)
parseHandle (String): String [] 0%   (0/1)0%   (0/24)0%   (0/2)
parseAWSErrorFromContent (HttpRequest, HttpResponse): AWSError 100% (1/1)65%  (51/78)53%  (8/15)
AWSUtils (String, RequestSigner, ParseSax$Factory, Provider): void 100% (1/1)100% (35/35)100% (8/8)

1/**
2 * Licensed to jclouds, Inc. (jclouds) under one or more
3 * contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  jclouds licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  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,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19package org.jclouds.aws.util;
20 
21import static com.google.common.base.Preconditions.checkArgument;
22import static com.google.common.base.Preconditions.checkNotNull;
23import static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;
24 
25import java.util.Map;
26 
27import javax.annotation.Resource;
28import javax.inject.Inject;
29import javax.inject.Named;
30import javax.inject.Provider;
31import javax.inject.Singleton;
32 
33import org.jclouds.aws.domain.AWSError;
34import org.jclouds.aws.domain.Region;
35import org.jclouds.aws.xml.ErrorHandler;
36import org.jclouds.domain.Location;
37import org.jclouds.domain.LocationScope;
38import org.jclouds.http.HttpRequest;
39import org.jclouds.http.HttpResponse;
40import org.jclouds.http.functions.ParseSax;
41import org.jclouds.http.functions.ParseSax.Factory;
42import org.jclouds.http.utils.ModifyRequest;
43import org.jclouds.logging.Logger;
44import org.jclouds.rest.RequestSigner;
45import org.jclouds.rest.internal.GeneratedHttpRequest;
46 
47import com.google.common.base.Function;
48import com.google.common.collect.ImmutableMultimap;
49import com.google.common.collect.ImmutableMultimap.Builder;
50import com.google.common.collect.Iterables;
51import com.google.common.collect.Multimap;
52 
53/**
54 * Needed to sign and verify requests and responses.
55 * 
56 * @author Adrian Cole
57 */
58@Singleton
59public class AWSUtils {
60   @Singleton
61   public static class GetRegionFromLocation implements Function<Location, String> {
62      public String apply(Location location) {
63         String region = location.getScope() == LocationScope.REGION ? location.getId() : location.getParent().getId();
64         return region;
65      }
66   }
67 
68   private final RequestSigner signer;
69   private final ParseSax.Factory factory;
70   private final Provider<ErrorHandler> errorHandlerProvider;
71   private final String requestId;
72   private final String requestToken;
73 
74   @Resource
75   protected Logger logger = Logger.NULL;
76 
77   @Inject
78   AWSUtils(@Named(PROPERTY_HEADER_TAG) String headerTag, RequestSigner signer, Factory factory,
79         Provider<ErrorHandler> errorHandlerProvider) {
80      this.signer = signer;
81      this.factory = factory;
82      this.errorHandlerProvider = errorHandlerProvider;
83      this.requestId = String.format("x-%s-request-id", headerTag);
84      this.requestToken = String.format("x-%s-id-2", headerTag);
85   }
86 
87   public AWSError parseAWSErrorFromContent(HttpRequest request, HttpResponse response) {
88      // HEAD has no content
89      if (response.getPayload() == null)
90         return null;
91      // Eucalyptus and Walrus occasionally return text/plain
92      if (response.getPayload().getContentMetadata().getContentType() != null
93            && response.getPayload().getContentMetadata().getContentType().indexOf("text/plain") != -1)
94         return null;
95      try {
96         AWSError error = (AWSError) factory.create(errorHandlerProvider.get()).setContext(request).apply(response);
97         if (error.getRequestId() == null)
98            error.setRequestId(response.getFirstHeaderOrNull(requestId));
99         error.setRequestToken(response.getFirstHeaderOrNull(requestToken));
100         if ("SignatureDoesNotMatch".equals(error.getCode())) {
101            error.setStringSigned(signer.createStringToSign(request));
102            error.setSignature(signer.sign(error.getStringSigned()));
103         }
104         return error;
105      } catch (RuntimeException e) {
106         logger.warn(e, "error parsing error");
107         return null;
108      }
109   }
110 
111   public static <R extends HttpRequest> R indexStringArrayToFormValuesWithStringFormat(R request, String format,
112         Object input) {
113      checkArgument(checkNotNull(input, "input") instanceof String[], "this binder is only valid for String[] : "
114            + input.getClass());
115      String[] values = (String[]) input;
116      Builder<String, String> builder = ImmutableMultimap.<String, String> builder();
117      for (int i = 0; i < values.length; i++) {
118         builder.put(String.format(format, (i + 1)), checkNotNull(values[i], format.toLowerCase() + "s[" + i + "]"));
119      }
120      ImmutableMultimap<String, String> forms = builder.build();
121      return forms.size() == 0 ? request : ModifyRequest.putFormParams(request, forms);
122   }
123 
124   // TODO: make this more dynamic
125   public static boolean isRegion(String regionName) {
126      return Region.DEFAULT_REGIONS.contains(regionName);
127   }
128 
129   public static <R extends HttpRequest> R indexIterableToFormValuesWithPrefix(R request, String prefix, Object input) {
130      checkArgument(checkNotNull(input, "input") instanceof Iterable<?>, "this binder is only valid for Iterable<?>: "
131            + input.getClass());
132      Iterable<?> values = (Iterable<?>) input;
133      Builder<String, String> builder = ImmutableMultimap.<String, String> builder();
134      int i = 0;
135      for (Object o : values) {
136         builder.put(prefix + "." + (i++ + 1), checkNotNull(o.toString(), prefix.toLowerCase() + "s[" + i + "]"));
137      }
138      ImmutableMultimap<String, String> forms = builder.build();
139      return forms.size() == 0 ? request : ModifyRequest.putFormParams(request, forms);
140   }
141 
142   public static <R extends HttpRequest> R indexStringArrayToFormValuesWithPrefix(R request, String prefix, Object input) {
143      checkArgument(checkNotNull(input, "input") instanceof String[], "this binder is only valid for String[] : "
144            + input.getClass());
145      String[] values = (String[]) input;
146      Builder<String, String> builder = ImmutableMultimap.<String, String> builder();
147      for (int i = 0; i < values.length; i++) {
148         builder.put(prefix + "." + (i + 1), checkNotNull(values[i], prefix.toLowerCase() + "s[" + i + "]"));
149      }
150      ImmutableMultimap<String, String> forms = builder.build();
151      return forms.size() == 0 ? request : ModifyRequest.putFormParams(request, forms);
152   }
153 
154   public static <R extends HttpRequest> R indexMapToFormValuesWithPrefix(R request, String prefix, String keySuffix, String valueSuffix, Object input) {
155      checkArgument(checkNotNull(input, "input") instanceof Map<?, ?>, "this binder is only valid for Map<?,?>: " + input.getClass());
156      Map<?, ?> map = (Map<?, ?>) input;
157      Builder<String, String> builder = ImmutableMultimap.<String, String> builder();
158      int i = 1;
159      for (Map.Entry<?, ?> e : map.entrySet()) {
160         builder.put(prefix + "." + i + "." + keySuffix, checkNotNull(e.getKey().toString(), keySuffix.toLowerCase() + "s[" + i + "]"));
161         if (e.getValue() != null) {
162            builder.put(prefix + "." + i + "." + valueSuffix, e.getValue().toString());
163         }
164         i++;
165      }
166      ImmutableMultimap<String, String> forms = builder.build();
167      return forms.size() == 0 ? request : ModifyRequest.putFormParams(request, forms);
168   }
169 
170   @SuppressWarnings("unchecked")
171   public static <R extends HttpRequest> R indexMultimapToFormValuesWithPrefix(R request, String prefix, String keySuffix, String valueSuffix, Object input) {
172      checkArgument(checkNotNull(input, "input") instanceof Multimap<?, ?>, "this binder is only valid for Multimap<?,?>: " + input.getClass());
173      Multimap<Object, Object> map = (Multimap<Object, Object>) input;
174      Builder<String, String> builder = ImmutableMultimap.<String, String> builder();
175      int i = 1;
176      for (Object k : map.keySet()) {
177         builder.put(prefix + "." + i + "." + keySuffix, checkNotNull(k.toString(), keySuffix.toLowerCase() + "s[" + i + "]"));
178         int j = 1;
179         for (Object v : map.get(k)) {
180            builder.put(prefix + "." + i + "." + valueSuffix + "." + j, v.toString());
181            j++;
182         }
183         i++;
184      }
185      ImmutableMultimap<String, String> forms = builder.build();
186      return forms.size() == 0 ? request : ModifyRequest.putFormParams(request, forms);
187   }
188 
189   @SuppressWarnings("unchecked")
190   public static <R extends HttpRequest> R indexMapOfIterableToFormValuesWithPrefix(R request, String prefix, String keySuffix, String valueSuffix, Object input) {
191      checkArgument(checkNotNull(input, "input") instanceof Map<?, ?>, "this binder is only valid for Map<?,Iterable<?>>: " + input.getClass());
192      Map<Object, Iterable<Object>> map = (Map<Object, Iterable<Object>>) input;
193      Builder<String, String> builder = ImmutableMultimap.<String, String> builder();
194      int i = 1;
195      for (Object k : map.keySet()) {
196         builder.put(prefix + "." + i + "." + keySuffix, checkNotNull(k.toString(), keySuffix.toLowerCase() + "s[" + i + "]"));
197         if (!Iterables.isEmpty(map.get(k))) {
198            int j = 1;
199            for (Object v : map.get(k)) {
200               builder.put(prefix + "." + i + "." + valueSuffix + "." + j, v.toString());
201               j++;
202            }
203         }
204         i++;
205      }
206      ImmutableMultimap<String, String> forms = builder.build();
207      return forms.size() == 0 ? request : ModifyRequest.putFormParams(request, forms);
208   }
209 
210   public static String getRegionFromLocationOrNull(Location location) {
211      return location.getScope() == LocationScope.ZONE ? location.getParent().getId() : location.getId();
212   }
213 
214   // there may not be a region, and in this case we do-not encode it into the string
215   public static String[] parseHandle(String id) {
216      String[] parts = checkNotNull(id, "id").split("/");
217      return (parts.length == 1) ? new String[] { null, id } : parts;
218   }
219 
220   public static String findRegionInArgsOrNull(GeneratedHttpRequest<?> gRequest) {
221      for (Object arg : gRequest.getArgs()) {
222         if (arg instanceof String) {
223            String regionName = (String) arg;
224            // TODO regions may not be amazon regions!
225            // take from a configured value
226            if (isRegion(regionName))
227               return regionName;
228         }
229      }
230      return null;
231   }
232}

[all classes][org.jclouds.aws.util]
EMMA 2.0.5312 (C) Vladimir Roubtsov