1 # Copyright 2010 Google Inc.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
16 require 'addressable/uri'
17 require 'addressable/template'
19 require 'google/api_client/errors'
25 # A method that has been described by a discovery document.
29 # Creates a description of a particular method.
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] method_description
38 # The section of the discovery document that applies to this method.
40 # @return [Google::APIClient::Method] The constructed method object.
41 def initialize(api, method_base, method_name, discovery_document)
43 @method_base = method_base
45 @discovery_document = discovery_document
49 # Returns the API this method belongs to.
51 # @return [Google::APIClient::API] The API this method belongs to.
55 # Returns the identifier for the method.
57 # @return [String] The method identifier.
61 # Returns the parsed section of the discovery document that applies to
64 # @return [Hash] The method description.
65 attr_reader :description
68 # Returns the base URI for the method.
70 # @return [Addressable::URI]
71 # The base URI that this method will be joined to.
72 attr_reader :method_base
75 # Updates the method with the new base.
77 # @param [Addressable::URI, #to_str, String] new_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)
85 # Returns the method ID.
87 # @return [String] The method identifier.
89 return @discovery_document['id']
93 # Returns the HTTP method or 'GET' if none is specified.
95 # @return [String] The HTTP method that will be used in the request.
97 return @discovery_document['httpMethod'] || 'GET'
101 # Returns the URI template for the method. A parameter list can be
102 # used to expand this into a URI.
104 # @return [Addressable::Template] The URI template.
106 return @uri_template ||= Addressable::Template.new(
107 self.method_base.join(Addressable::URI.parse(@discovery_document['path']))
112 # Returns media upload information for this method, if supported
114 # @return [Google::APIClient::MediaUpload] Description of upload endpoints
116 if @discovery_document['mediaUpload']
117 return @media_upload ||= Google::APIClient::MediaUpload.new(self, self.method_base, @discovery_document['mediaUpload'])
124 # Returns the Schema object for the method's request, if any.
126 # @return [Google::APIClient::Schema] The request schema.
128 if @discovery_document['request']
129 schema_name = @discovery_document['request']['$ref']
130 return @api.schemas[schema_name]
137 # Returns the Schema object for the method's response, if any.
139 # @return [Google::APIClient::Schema] The response schema.
141 if @discovery_document['response']
142 schema_name = @discovery_document['response']['$ref']
143 return @api.schemas[schema_name]
150 # Normalizes parameters, converting to the appropriate types.
152 # @param [Hash, Array] parameters
153 # The parameters to normalize.
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}."
171 "Expected Hash or Array, got #{parameters.class}."
177 # Expands the method's URI template using a parameter list.
179 # @param [Hash, Array] parameters
180 # The parameter list to use.
182 # @return [Addressable::URI] The URI after expansion.
183 def generate_uri(parameters={})
184 parameters = self.normalize_parameters(parameters)
185 self.validate_parameters(parameters)
186 template_variables = self.uri_template.variables
187 upload_type = parameters.assoc('uploadType') || parameters.assoc('upload_type')
189 unless self.media_upload
190 raise ArgumentException, "Media upload not supported for this method"
192 case upload_type.last
193 when 'media', 'multipart', 'resumable'
194 uri = self.media_upload.uri_template.expand(parameters)
196 raise ArgumentException, "Invalid uploadType '#{upload_type}'"
199 uri = self.uri_template.expand(parameters)
201 query_parameters = parameters.reject do |k, v|
202 template_variables.include?(k)
204 # encode all non-template parameters
206 unless query_parameters.empty?
207 params = "?" + Addressable::URI.form_encode(query_parameters.sort)
209 # Normalization is necessary because of undesirable percent-escaping
210 # during URI template expansion
211 return uri.normalize + params
215 # Generates an HTTP request for this method.
217 # @param [Hash, Array] parameters
218 # The parameters to send.
219 # @param [String, StringIO] body The body for the HTTP request.
220 # @param [Hash, Array] headers The HTTP headers for the request.
221 # @option options [Faraday::Connection] :connection
222 # The HTTP connection to use.
224 # @return [Array] The generated HTTP request.
225 def generate_request(parameters={}, body='', headers=[], options={})
226 options[:connection] ||= Faraday.default_connection
227 if body.respond_to?(:string)
229 elsif body.respond_to?(:to_str)
232 raise TypeError, "Expected String or StringIO, got #{body.class}."
234 if !headers.kind_of?(Array) && !headers.kind_of?(Hash)
235 raise TypeError, "Expected Hash or Array, got #{headers.class}."
237 method = self.http_method
238 uri = self.generate_uri(parameters)
239 headers = headers.to_a if headers.kind_of?(Hash)
240 return options[:connection].build_request(
241 method.to_s.downcase.to_sym
243 req.url(Addressable::URI.parse(uri).normalize.to_s)
244 req.headers = Faraday::Utils::Headers.new(headers)
251 # Returns a <code>Hash</code> of the parameter descriptions for
254 # @return [Hash] The parameter descriptions.
255 def parameter_descriptions
256 @parameter_descriptions ||= (
257 @discovery_document['parameters'] || {}
258 ).inject({}) { |h,(k,v)| h[k]=v; h }
262 # Returns an <code>Array</code> of the parameters for this method.
264 # @return [Array] The parameters.
267 @discovery_document['parameters'] || {}
268 ).inject({}) { |h,(k,v)| h[k]=v; h }).keys
272 # Returns an <code>Array</code> of the required parameters for this
275 # @return [Array] The required parameters.
278 # # A list of all required parameters.
279 # method.required_parameters
280 def required_parameters
281 @required_parameters ||= ((self.parameter_descriptions.select do |k, v|
283 end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
287 # Returns an <code>Array</code> of the optional parameters for this
290 # @return [Array] The optional parameters.
293 # # A list of all optional parameters.
294 # method.optional_parameters
295 def optional_parameters
296 @optional_parameters ||= ((self.parameter_descriptions.reject do |k, v|
298 end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
302 # Verifies that the parameters are valid for this method. Raises an
303 # exception if validation fails.
305 # @param [Hash, Array] parameters
306 # The parameters to verify.
308 # @return [NilClass] <code>nil</code> if validation passes.
309 def validate_parameters(parameters={})
310 parameters = self.normalize_parameters(parameters)
311 required_variables = ((self.parameter_descriptions.select do |k, v|
313 end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
314 missing_variables = required_variables - parameters.map { |(k, _)| k }
315 if missing_variables.size > 0
317 "Missing required parameters: #{missing_variables.join(', ')}."
319 parameters.each do |k, v|
320 # Handle repeated parameters.
321 if self.parameter_descriptions[k] &&
322 self.parameter_descriptions[k]['repeated'] &&
324 # If this is a repeated parameter and we've got an array as a
325 # value, just provide the whole array to the loop below.
328 # If this is not a repeated parameter, or if it is but we're
329 # being given a single value, wrap the value in an array, so that
330 # the loop below still works for the single element.
335 if self.parameter_descriptions[k]
336 enum = self.parameter_descriptions[k]['enum']
337 if enum && !enum.include?(item)
339 "Parameter '#{k}' has an invalid value: #{item}. " +
340 "Must be one of #{enum.inspect}."
342 pattern = self.parameter_descriptions[k]['pattern']
344 regexp = Regexp.new("^#{pattern}$")
347 "Parameter '#{k}' has an invalid value: #{item}. " +
348 "Must match: /^#{pattern}$/."
358 # Returns a <code>String</code> representation of the method's state.
360 # @return [String] The method's state, as a <code>String</code>.
364 self.class.to_s, self.object_id, self.id