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] discovery_document
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
48 # @return [String] unparsed discovery document for the method
49 attr_reader :discovery_document
52 # Returns the API this method belongs to.
54 # @return [Google::APIClient::API] The API this method belongs to.
58 # Returns the identifier for the method.
60 # @return [String] The method identifier.
64 # Returns the base URI for the method.
66 # @return [Addressable::URI]
67 # The base URI that this method will be joined to.
68 attr_reader :method_base
71 # Updates the method with the new base.
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)
81 # Returns a human-readable description of the method.
83 # @return [Hash] The API description.
85 return @discovery_document['description']
89 # Returns the method ID.
91 # @return [String] The method identifier.
93 return @discovery_document['id']
97 # Returns the HTTP method or 'GET' if none is specified.
99 # @return [String] The HTTP method that will be used in the request.
101 return @discovery_document['httpMethod'] || 'GET'
105 # Returns the URI template for the method. A parameter list can be
106 # used to expand this into a URI.
108 # @return [Addressable::Template] The URI template.
110 return @uri_template ||= Addressable::Template.new(
111 self.method_base.join(Addressable::URI.parse("./" + @discovery_document['path']))
116 # Returns media upload information for this method, if supported
118 # @return [Google::APIClient::MediaUpload] Description of upload endpoints
120 if @discovery_document['mediaUpload']
121 return @media_upload ||= Google::APIClient::MediaUpload.new(self, self.method_base, @discovery_document['mediaUpload'])
128 # Returns the Schema object for the method's request, if any.
130 # @return [Google::APIClient::Schema] The request schema.
132 if @discovery_document['request']
133 schema_name = @discovery_document['request']['$ref']
134 return @api.schemas[schema_name]
141 # Returns the Schema object for the method's response, if any.
143 # @return [Google::APIClient::Schema] The response schema.
145 if @discovery_document['response']
146 schema_name = @discovery_document['response']['$ref']
147 return @api.schemas[schema_name]
154 # Normalizes parameters, converting to the appropriate types.
156 # @param [Hash, Array] parameters
157 # The parameters to normalize.
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}."
175 "Expected Hash or Array, got #{parameters.class}."
181 # Expands the method's URI template using a parameter list.
184 # @param [Hash, Array] parameters
185 # The parameter list to use.
187 # @return [Addressable::URI] The URI after expansion.
188 def generate_uri(parameters={})
189 parameters = self.normalize_parameters(parameters)
191 self.validate_parameters(parameters)
192 template_variables = self.uri_template.variables
193 upload_type = parameters.assoc('uploadType') || parameters.assoc('upload_type')
195 unless self.media_upload
196 raise ArgumentException, "Media upload not supported for this method"
198 case upload_type.last
199 when 'media', 'multipart', 'resumable'
200 uri = self.media_upload.uri_template.expand(parameters)
202 raise ArgumentException, "Invalid uploadType '#{upload_type}'"
205 uri = self.uri_template.expand(parameters)
207 query_parameters = parameters.reject do |k, v|
208 template_variables.include?(k)
210 # encode all non-template parameters
212 unless query_parameters.empty?
213 params = "?" + Addressable::URI.form_encode(query_parameters.sort)
215 # Normalization is necessary because of undesirable percent-escaping
216 # during URI template expansion
217 return uri.normalize + params
221 # Generates an HTTP request for this method.
224 # @param [Hash, Array] parameters
225 # The parameters to send.
226 # @param [String, StringIO] body The body for the HTTP request.
227 # @param [Hash, Array] headers The HTTP headers for the request.
228 # @option options [Faraday::Connection] :connection
229 # The HTTP connection to use.
231 # @return [Array] The generated HTTP request.
232 def generate_request(parameters={}, body='', headers={}, options={})
233 if !headers.kind_of?(Array) && !headers.kind_of?(Hash)
234 raise TypeError, "Expected Hash or Array, got #{headers.class}."
236 method = self.http_method.to_s.downcase.to_sym
237 uri = self.generate_uri(parameters)
238 headers = Faraday::Utils::Headers.new(headers)
239 return [method, uri, headers, body]
244 # Returns a <code>Hash</code> of the parameter descriptions for
247 # @return [Hash] The parameter descriptions.
248 def parameter_descriptions
249 @parameter_descriptions ||= (
250 @discovery_document['parameters'] || {}
251 ).inject({}) { |h,(k,v)| h[k]=v; h }
255 # Returns an <code>Array</code> of the parameters for this method.
257 # @return [Array] The parameters.
260 @discovery_document['parameters'] || {}
261 ).inject({}) { |h,(k,v)| h[k]=v; h }).keys
265 # Returns an <code>Array</code> of the required parameters for this
268 # @return [Array] The required parameters.
271 # # A list of all required parameters.
272 # method.required_parameters
273 def required_parameters
274 @required_parameters ||= ((self.parameter_descriptions.select do |k, v|
276 end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
280 # Returns an <code>Array</code> of the optional parameters for this
283 # @return [Array] The optional parameters.
286 # # A list of all optional parameters.
287 # method.optional_parameters
288 def optional_parameters
289 @optional_parameters ||= ((self.parameter_descriptions.reject do |k, v|
291 end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
295 # Verifies that the parameters are valid for this method. Raises an
296 # exception if validation fails.
299 # @param [Hash, Array] parameters
300 # The parameters to verify.
302 # @return [NilClass] <code>nil</code> if validation passes.
303 def validate_parameters(parameters={})
304 parameters = self.normalize_parameters(parameters)
305 required_variables = ((self.parameter_descriptions.select do |k, v|
307 end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
308 missing_variables = required_variables - parameters.map { |(k, _)| k }
309 if missing_variables.size > 0
311 "Missing required parameters: #{missing_variables.join(', ')}."
313 parameters.each do |k, v|
314 # Handle repeated parameters.
315 if self.parameter_descriptions[k] &&
316 self.parameter_descriptions[k]['repeated'] &&
318 # If this is a repeated parameter and we've got an array as a
319 # value, just provide the whole array to the loop below.
322 # If this is not a repeated parameter, or if it is but we're
323 # being given a single value, wrap the value in an array, so that
324 # the loop below still works for the single element.
329 if self.parameter_descriptions[k]
330 enum = self.parameter_descriptions[k]['enum']
331 if enum && !enum.include?(item)
333 "Parameter '#{k}' has an invalid value: #{item}. " +
334 "Must be one of #{enum.inspect}."
336 pattern = self.parameter_descriptions[k]['pattern']
338 regexp = Regexp.new("^#{pattern}$")
341 "Parameter '#{k}' has an invalid value: #{item}. " +
342 "Must match: /^#{pattern}$/."
352 # Returns a <code>String</code> representation of the method's state.
354 # @return [String] The method's state, as a <code>String</code>.
358 self.class.to_s, self.object_id, self.id