PageRenderTime 128ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/apis/sts/src/main/java/org/jclouds/aws/util/AWSUtils.java

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