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
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_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)
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.
180 # @param [Hash, Array] parameters
181 # The parameter list to use.
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')
190 unless self.media_upload
191 raise ArgumentException, "Media upload not supported for this method"
193 case upload_type.last
194 when 'media', 'multipart', 'resumable'
195 uri = self.media_upload.uri_template.expand(parameters)
197 raise ArgumentException, "Invalid uploadType '#{upload_type}'"
200 uri = self.uri_template.expand(parameters)
202 query_parameters = parameters.reject do |k, v|
203 template_variables.include?(k)
205 # encode all non-template parameters
207 unless query_parameters.empty?
208 params = "?" + Addressable::URI.form_encode(query_parameters.sort)
210 # Normalization is necessary because of undesirable percent-escaping
211 # during URI template expansion
212 return uri.normalize + params
216 # Generates an HTTP request for this method.
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.
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}."
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]
239 # Returns a <code>Hash</code> of the parameter descriptions for
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 }
250 # Returns an <code>Array</code> of the parameters for this method.
252 # @return [Array] The parameters.
255 @discovery_document['parameters'] || {}
256 ).inject({}) { |h,(k,v)| h[k]=v; h }).keys
260 # Returns an <code>Array</code> of the required parameters for this
263 # @return [Array] The required parameters.
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|
271 end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
275 # Returns an <code>Array</code> of the optional parameters for this
278 # @return [Array] The optional parameters.
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|
286 end).inject({}) { |h,(k,v)| h[k]=v; h }).keys
290 # Verifies that the parameters are valid for this method. Raises an
291 # exception if validation fails.
294 # @param [Hash, Array] parameters
295 # The parameters to verify.
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|
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
306 "Missing required parameters: #{missing_variables.join(', ')}."
308 parameters.each do |k, v|
309 # Handle repeated parameters.
310 if self.parameter_descriptions[k] &&
311 self.parameter_descriptions[k]['repeated'] &&
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.
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.
324 if self.parameter_descriptions[k]
325 enum = self.parameter_descriptions[k]['enum']
326 if enum && !enum.include?(item)
328 "Parameter '#{k}' has an invalid value: #{item}. " +
329 "Must be one of #{enum.inspect}."
331 pattern = self.parameter_descriptions[k]['pattern']
333 regexp = Regexp.new("^#{pattern}$")
336 "Parameter '#{k}' has an invalid value: #{item}. " +
337 "Must match: /^#{pattern}$/."
347 # Returns a <code>String</code> representation of the method's state.
349 # @return [String] The method's state, as a <code>String</code>.
353 self.class.to_s, self.object_id, self.id