Merge pull request #13 from sanemat/multi-json-in-rails-case
[arvados.git] / lib / google / api_client / discovery / method.rb
1 # Copyright 2010 Google Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15
16 require 'addressable/uri'
17 require 'addressable/template'
18
19 require 'google/api_client/errors'
20
21
22 module Google
23   class APIClient
24     ##
25     # A method that has been described by a discovery document.
26     class Method
27
28       ##
29       # Creates a description of a particular method.
30       #
31       # @param [Google::APIClient::API] api
32       #   The API this method belongs to.
33       # @param [Addressable::URI] method_base
34       #   The base URI for the service.
35       # @param [String] method_name
36       #   The identifier for the method.
37       # @param [Hash] discovery_document
38       #   The section of the discovery document that applies to this method.
39       #
40       # @return [Google::APIClient::Method] The constructed method object.
41       def initialize(api, method_base, method_name, discovery_document)
42         @api = api
43         @method_base = method_base
44         @name = method_name
45         @discovery_document = discovery_document
46       end
47
48       # @return [String] unparsed discovery document for the method
49       attr_reader :discovery_document
50
51       ##
52       # Returns the API this method belongs to.
53       #
54       # @return [Google::APIClient::API] The API this method belongs to.
55       attr_reader :api
56
57       ##
58       # Returns the identifier for the method.
59       #
60       # @return [String] The method identifier.
61       attr_reader :name
62
63       ##
64       # Returns the base URI for the method.
65       #
66       # @return [Addressable::URI]
67       #   The base URI that this method will be joined to.
68       attr_reader :method_base
69
70       ##
71       # Updates the method with the new base.
72       #
73       # @param [Addressable::URI, #to_str, String] new_method_base
74       #   The new base URI to use for the method.
75       def method_base=(new_method_base)
76         @method_base = Addressable::URI.parse(new_method_base)
77         @uri_template = nil
78       end
79
80       ##
81       # Returns a human-readable description of the method.
82       #
83       # @return [Hash] The API description.
84       def description
85         return @discovery_document['description']
86       end
87       
88       ##
89       # Returns the method ID.
90       #
91       # @return [String] The method identifier.
92       def id
93         return @discovery_document['id']
94       end
95
96       ##
97       # Returns the HTTP method or 'GET' if none is specified.
98       #
99       # @return [String] The HTTP method that will be used in the request.
100       def http_method
101         return @discovery_document['httpMethod'] || 'GET'
102       end
103
104       ##
105       # Returns the URI template for the method.  A parameter list can be
106       # used to expand this into a URI.
107       #
108       # @return [Addressable::Template] The URI template.
109       def uri_template
110         return @uri_template ||= Addressable::Template.new(
111           self.method_base.join(Addressable::URI.parse(@discovery_document['path']))
112         )
113       end
114
115       ##
116       # Returns media upload information for this method, if supported
117       #
118       # @return [Google::APIClient::MediaUpload] Description of upload endpoints
119       def media_upload
120         if @discovery_document['mediaUpload']
121           return @media_upload ||= Google::APIClient::MediaUpload.new(self, self.method_base, @discovery_document['mediaUpload'])
122         else
123           return nil
124         end
125       end
126
127       ##
128       # Returns the Schema object for the method's request, if any.
129       #
130       # @return [Google::APIClient::Schema] The request schema.
131       def request_schema
132         if @discovery_document['request']
133           schema_name = @discovery_document['request']['$ref']
134           return @api.schemas[schema_name]
135         else
136           return nil
137         end
138       end
139
140       ##
141       # Returns the Schema object for the method's response, if any.
142       #
143       # @return [Google::APIClient::Schema] The response schema.
144       def response_schema
145         if @discovery_document['response']
146           schema_name = @discovery_document['response']['$ref']
147           return @api.schemas[schema_name]
148         else
149           return nil
150         end
151       end
152
153       ##
154       # Normalizes parameters, converting to the appropriate types.
155       #
156       # @param [Hash, Array] parameters
157       #   The parameters to normalize.
158       #
159       # @return [Hash] The normalized parameters.
160       def normalize_parameters(parameters={})
161         # Convert keys to Strings when appropriate
162         if parameters.kind_of?(Hash) || parameters.kind_of?(Array)
163           # Returning an array since parameters can be repeated (ie, Adsense Management API)
164           parameters = parameters.inject([]) do |accu, (k, v)|
165             k = k.to_s if k.kind_of?(Symbol)
166             k = k.to_str if k.respond_to?(:to_str)
167             unless k.kind_of?(String)
168               raise TypeError, "Expected String, got #{k.class}."
169             end
170             accu << [k, v]
171             accu
172           end
173         else
174           raise TypeError,
175             "Expected Hash or Array, got #{parameters.class}."
176         end
177         return parameters
178       end
179
180       ##
181       # Expands the method's URI template using a parameter list.
182       #
183       # @api private
184       # @param [Hash, Array] parameters
185       #   The parameter list to use.
186       #
187       # @return [Addressable::URI] The URI after expansion.
188       def generate_uri(parameters={})
189         parameters = self.normalize_parameters(parameters)
190         self.validate_parameters(parameters)
191         template_variables = self.uri_template.variables
192         upload_type = parameters.assoc('uploadType') || parameters.assoc('upload_type')
193         if upload_type
194           unless self.media_upload
195             raise ArgumentException, "Media upload not supported for this method"
196           end
197           case upload_type.last
198           when 'media', 'multipart', 'resumable'
199             uri = self.media_upload.uri_template.expand(parameters)
200           else
201             raise ArgumentException, "Invalid uploadType '#{upload_type}'"
202           end
203         else
204           uri = self.uri_template.expand(parameters)
205         end
206         query_parameters = parameters.reject do |k, v|
207           template_variables.include?(k)
208         end
209         # encode all non-template parameters
210         params = ""
211         unless query_parameters.empty?
212           params = "?" + Addressable::URI.form_encode(query_parameters.sort)
213         end
214         # Normalization is necessary because of undesirable percent-escaping
215         # during URI template expansion
216         return uri.normalize + params
217       end
218
219       ##
220       # Generates an HTTP request for this method.
221       #
222       # @api private
223       # @param [Hash, Array] parameters
224       #   The parameters to send.
225       # @param [String, StringIO] body The body for the HTTP request.
226       # @param [Hash, Array] headers The HTTP headers for the request.
227       # @option options [Faraday::Connection] :connection
228       #   The HTTP connection to use.
229       #
230       # @return [Array] The generated HTTP request.
231       def generate_request(parameters={}, body='', headers={}, options={})
232         if !headers.kind_of?(Array) && !headers.kind_of?(Hash)
233           raise TypeError, "Expected Hash or Array, got #{headers.class}."
234         end
235         method = self.http_method.to_s.downcase.to_sym
236         uri = self.generate_uri(parameters)
237         headers = Faraday::Utils::Headers.new(headers)
238         return [method, uri, headers, body]
239       end
240
241
242       ##
243       # Returns a <code>Hash</code> of the parameter descriptions for
244       # this method.
245       #
246       # @return [Hash] The parameter descriptions.
247       def parameter_descriptions
248         @parameter_descriptions ||= (
249           @discovery_document['parameters'] || {}
250         ).inject({}) { |h,(k,v)| h[k]=v; h }
251       end
252
253       ##
254       # Returns an <code>Array</code> of the parameters for this method.
255       #
256       # @return [Array] The parameters.
257       def parameters
258         @parameters ||= ((
259           @discovery_document['parameters'] || {}
260         ).inject({}) { |h,(k,v)| h[k]=v; h }).keys
261       end
262
263       ##
264       # Returns an <code>Array</code> of the required parameters for this
265       # method.
266       #
267       # @return [Array] The required parameters.
268       #
269       # @example
270       #   # A list of all required parameters.
271       #   method.required_parameters
272       def required_parameters
273         @required_parameters ||= ((self.parameter_descriptions.select do |k, v|
274           v['required']
275         end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
276       end
277
278       ##
279       # Returns an <code>Array</code> of the optional parameters for this
280       # method.
281       #
282       # @return [Array] The optional parameters.
283       #
284       # @example
285       #   # A list of all optional parameters.
286       #   method.optional_parameters
287       def optional_parameters
288         @optional_parameters ||= ((self.parameter_descriptions.reject do |k, v|
289           v['required']
290         end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
291       end
292
293       ##
294       # Verifies that the parameters are valid for this method.  Raises an
295       # exception if validation fails.
296       #
297       # @api private
298       # @param [Hash, Array] parameters
299       #   The parameters to verify.
300       #
301       # @return [NilClass] <code>nil</code> if validation passes.
302       def validate_parameters(parameters={})
303         parameters = self.normalize_parameters(parameters)
304         required_variables = ((self.parameter_descriptions.select do |k, v|
305           v['required']
306         end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
307         missing_variables = required_variables - parameters.map { |(k, _)| k }
308         if missing_variables.size > 0
309           raise ArgumentError,
310             "Missing required parameters: #{missing_variables.join(', ')}."
311         end
312         parameters.each do |k, v|
313           # Handle repeated parameters.
314           if self.parameter_descriptions[k] &&
315               self.parameter_descriptions[k]['repeated'] &&
316               v.kind_of?(Array)
317             # If this is a repeated parameter and we've got an array as a
318             # value, just provide the whole array to the loop below.
319             items = v
320           else
321             # If this is not a repeated parameter, or if it is but we're
322             # being given a single value, wrap the value in an array, so that
323             # the loop below still works for the single element.
324             items = [v]
325           end
326
327           items.each do |item|
328             if self.parameter_descriptions[k]
329               enum = self.parameter_descriptions[k]['enum']
330               if enum && !enum.include?(item)
331                 raise ArgumentError,
332                   "Parameter '#{k}' has an invalid value: #{item}. " +
333                   "Must be one of #{enum.inspect}."
334               end
335               pattern = self.parameter_descriptions[k]['pattern']
336               if pattern
337                 regexp = Regexp.new("^#{pattern}$")
338                 if item !~ regexp
339                   raise ArgumentError,
340                     "Parameter '#{k}' has an invalid value: #{item}. " +
341                     "Must match: /^#{pattern}$/."
342                 end
343               end
344             end
345           end
346         end
347         return nil
348       end
349
350       ##
351       # Returns a <code>String</code> representation of the method's state.
352       #
353       # @return [String] The method's state, as a <code>String</code>.
354       def inspect
355         sprintf(
356           "#<%s:%#0x ID:%s>",
357           self.class.to_s, self.object_id, self.id
358         )
359       end
360     end
361   end
362 end