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