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'
18 require 'extlib/inflection'
23 # An exception that is raised if a method is called with missing or
24 # invalid parameter values.
25 class ValidationError < StandardError
29 # A service that has been described by a discovery document.
33 # Creates a description of a particular version of a service.
35 # @param [String] service_name
36 # The identifier for the service. Note that while this frequently
37 # matches the first segment of all of the service's RPC names, this
38 # should not be assumed. There is no requirement that these match.
39 # @param [String] service_version
40 # The identifier for the service version.
41 # @param [Hash] service_description
42 # The section of the discovery document that applies to this service
45 # @return [Google::APIClient::Service] The constructed service object.
46 def initialize(service_name, service_version, service_description)
48 @version = service_version
49 @description = service_description
50 metaclass = (class <<self; self; end)
51 self.resources.each do |resource|
52 method_name = Extlib::Inflection.underscore(resource.name).to_sym
53 if !self.respond_to?(method_name)
54 metaclass.send(:define_method, method_name) { resource }
57 self.methods.each do |method|
58 method_name = Extlib::Inflection.underscore(method.name).to_sym
59 if !self.respond_to?(method_name)
60 metaclass.send(:define_method, method_name) { method }
66 # Returns the identifier for the service.
68 # @return [String] The service identifier.
72 # Returns the version of the service.
74 # @return [String] The service version.
78 # Returns the parsed section of the discovery document that applies to
79 # this version of the service.
81 # @return [Hash] The service description.
82 attr_reader :description
85 # Returns the base URI for this version of the service.
87 # @return [Addressable::URI] The base URI that methods are joined to.
89 return @base ||= Addressable::URI.parse(self.description['baseUrl'])
93 # A list of resources available at the root level of this version of the
96 # @return [Array] A list of {Google::APIClient::Resource} objects.
98 return @resources ||= (
99 (self.description['resources'] || []).inject([]) do |accu, (k, v)|
100 accu << ::Google::APIClient::Resource.new(self.base, k, v)
107 # A list of methods available at the root level of this version of the
110 # @return [Array] A list of {Google::APIClient::Method} objects.
112 return @methods ||= (
113 (self.description['methods'] || []).inject([]) do |accu, (k, v)|
114 accu << ::Google::APIClient::Method.new(self.base, k, v)
121 # Converts the service to a flat mapping of RPC names and method objects.
123 # @return [Hash] All methods available on the service.
126 # # Discover available methods
127 # method_names = client.discovered_service('buzz').to_h.keys
129 return @hash ||= (begin
131 self.methods.each do |method|
132 methods_hash[method.rpc_name] = method
134 self.resources.each do |resource|
135 methods_hash.merge!(resource.to_h)
142 # Compares two versions of a service.
144 # @param [Object] other The service to compare.
147 # <code>-1</code> if the service is older than <code>other</code>.
148 # <code>0</code> if the service is the same as <code>other</code>.
149 # <code>1</code> if the service is newer than <code>other</code>.
150 # <code>nil</code> if the service cannot be compared to
151 # <code>other</code>.
153 # We can only compare versions of the same service
154 if other.kind_of?(self.class) && self.name == other.name
155 split_version = lambda do |version|
156 dotted_version = version[/^v?(\d+(.\d+)*)-?(.*?)?$/, 1]
157 suffix = version[/^v?(\d+(.\d+)*)-?(.*?)?$/, 3]
158 [dotted_version.split('.').map { |v| v.to_i }, suffix]
160 self_sortable, self_suffix = split_version.call(self.version)
161 other_sortable, other_suffix = split_version.call(other.version)
162 result = self_sortable <=> other_sortable
165 # If the dotted versions are equal, check the suffix.
166 # An omitted suffix should be sorted after an included suffix.
167 elsif self_suffix == ''
169 elsif other_suffix == ''
172 return self_suffix <=> other_suffix
180 # Returns a <code>String</code> representation of the service's state.
182 # @return [String] The service's state, as a <code>String</code>.
185 "#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.name
191 # A resource that has been described by a discovery document.
195 # Creates a description of a particular version of a resource.
197 # @param [Addressable::URI] base
198 # The base URI for the service.
199 # @param [String] resource_name
200 # The identifier for the resource.
201 # @param [Hash] resource_description
202 # The section of the discovery document that applies to this resource.
204 # @return [Google::APIClient::Resource] The constructed resource object.
205 def initialize(base, resource_name, resource_description)
207 @name = resource_name
208 @description = resource_description
209 metaclass = (class <<self; self; end)
210 self.resources.each do |resource|
211 method_name = Extlib::Inflection.underscore(resource.name).to_sym
212 if !self.respond_to?(method_name)
213 metaclass.send(:define_method, method_name) { resource }
216 self.methods.each do |method|
217 method_name = Extlib::Inflection.underscore(method.name).to_sym
218 if !self.respond_to?(method_name)
219 metaclass.send(:define_method, method_name) { method }
225 # Returns the identifier for the resource.
227 # @return [String] The resource identifier.
231 # Returns the parsed section of the discovery document that applies to
234 # @return [Hash] The resource description.
235 attr_reader :description
238 # Returns the base URI for this resource.
240 # @return [Addressable::URI] The base URI that methods are joined to.
244 # A list of sub-resources available on this resource.
246 # @return [Array] A list of {Google::APIClient::Resource} objects.
248 return @resources ||= (
249 (self.description['resources'] || []).inject([]) do |accu, (k, v)|
250 accu << ::Google::APIClient::Resource.new(self.base, k, v)
257 # A list of methods available on this resource.
259 # @return [Array] A list of {Google::APIClient::Method} objects.
261 return @methods ||= (
262 (self.description['methods'] || []).inject([]) do |accu, (k, v)|
263 accu << ::Google::APIClient::Method.new(self.base, k, v)
270 # Converts the resource to a flat mapping of RPC names and method
273 # @return [Hash] All methods available on the resource.
275 return @hash ||= (begin
277 self.methods.each do |method|
278 methods_hash[method.rpc_name] = method
280 self.resources.each do |resource|
281 methods_hash.merge!(resource.to_h)
288 # Returns a <code>String</code> representation of the resource's state.
290 # @return [String] The resource's state, as a <code>String</code>.
293 "#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.name
299 # A method that has been described by a discovery document.
303 # Creates a description of a particular method.
305 # @param [Addressable::URI] base
306 # The base URI for the service.
307 # @param [String] method_name
308 # The identifier for the method.
309 # @param [Hash] method_description
310 # The section of the discovery document that applies to this method.
312 # @return [Google::APIClient::Method] The constructed method object.
313 def initialize(base, method_name, method_description)
316 @description = method_description
320 # Returns the identifier for the method.
322 # @return [String] The method identifier.
326 # Returns the parsed section of the discovery document that applies to
329 # @return [Hash] The method description.
330 attr_reader :description
333 # Returns the base URI for the method.
335 # @return [Addressable::URI]
336 # The base URI that this method will be joined to.
340 # Returns the RPC name for the method.
342 # @return [String] The RPC name.
344 return self.description['rpcName']
348 # Returns the URI template for the method. A parameter list can be
349 # used to expand this into a URI.
351 # @return [Addressable::Template] The URI template.
353 # TODO(bobaman) We shouldn't be calling #to_s here, this should be
354 # a join operation on a URI, but we have to treat these as Strings
355 # because of the way the discovery document provides the URIs.
356 # This should be fixed soon.
357 return @uri_template ||=
358 Addressable::Template.new(base.to_s + self.description['pathUrl'])
362 # Normalizes parameters, converting to the appropriate types.
364 # @param [Hash, Array] parameters
365 # The parameters to normalize.
367 # @return [Hash] The normalized parameters.
368 def normalize_parameters(parameters={})
369 # Convert keys to Strings when appropriate
370 if parameters.kind_of?(Hash) || parameters.kind_of?(Array)
371 # Is a Hash or an Array a better return type? Do we ever need to
372 # worry about the same parameter being sent twice with different
374 parameters = parameters.inject({}) do |accu, (k, v)|
375 k = k.to_s if k.kind_of?(Symbol)
376 k = k.to_str if k.respond_to?(:to_str)
377 unless k.kind_of?(String)
378 raise TypeError, "Expected String, got #{k.class}."
385 "Expected Hash or Array, got #{parameters.class}."
391 # Expands the method's URI template using a parameter list.
393 # @param [Hash, Array] parameters
394 # The parameter list to use.
396 # @return [Addressable::URI] The URI after expansion.
397 def generate_uri(parameters={})
398 parameters = self.normalize_parameters(parameters)
399 self.validate_parameters(parameters)
400 template_variables = self.uri_template.variables
401 uri = self.uri_template.expand(parameters)
402 query_parameters = parameters.reject do |k, v|
403 template_variables.include?(k)
405 if query_parameters.size > 0
406 uri.query_values = (uri.query_values || {}).merge(query_parameters)
408 # Normalization is necessary because of undesirable percent-escaping
409 # during URI template expansion
414 # Generates an HTTP request for this method.
416 # @param [Hash, Array] parameters
417 # The parameters to send.
418 # @param [String, StringIO] body The body for the HTTP request.
419 # @param [Hash, Array] headers The HTTP headers for the request.
421 # @return [Array] The generated HTTP request.
422 def generate_request(parameters={}, body='', headers=[])
423 if body.respond_to?(:string)
425 elsif body.respond_to?(:to_str)
428 raise TypeError, "Expected String or StringIO, got #{body.class}."
430 if !headers.kind_of?(Array) && !headers.kind_of?(Hash)
431 raise TypeError, "Expected Hash or Array, got #{headers.class}."
433 method = self.description['httpMethod'] || 'GET'
434 uri = self.generate_uri(parameters)
435 headers = headers.to_a if headers.kind_of?(Hash)
436 return [method, uri.to_str, headers, [body]]
440 # Returns a <code>Hash</code> of the parameter descriptions for
443 # @return [Hash] The parameter descriptions.
444 def parameter_descriptions
445 @parameter_descriptions ||= Hash[self.description['parameters'] || {}]
449 # Returns an <code>Array</code> of the parameters for this method.
451 # @return [Array] The parameters.
453 @parameters ||= Hash[self.description['parameters'] || {}].keys
457 # Returns an <code>Array</code> of the required parameters for this
460 # @return [Array] The required parameters.
463 # # A list of all required parameters.
464 # method.required_parameters
465 def required_parameters
466 @required_parameters ||= Hash[self.parameter_descriptions.select do |k, v|
472 # Returns an <code>Array</code> of the optional parameters for this
475 # @return [Array] The optional parameters.
478 # # A list of all optional parameters.
479 # method.optional_parameters
480 def optional_parameters
481 @optional_parameters ||= Hash[self.parameter_descriptions.reject do |k, v|
487 # Verifies that the parameters are valid for this method. Raises an
488 # exception if validation fails.
490 # @param [Hash, Array] parameters
491 # The parameters to verify.
493 # @return [NilClass] <code>nil</code> if validation passes.
494 def validate_parameters(parameters={})
495 parameters = self.normalize_parameters(parameters)
496 required_variables = Hash[self.parameter_descriptions.select do |k, v|
499 missing_variables = required_variables - parameters.keys
500 if missing_variables.size > 0
502 "Missing required parameters: #{missing_variables.join(', ')}."
504 parameters.each do |k, v|
505 if self.parameter_descriptions[k]
506 pattern = self.parameter_descriptions[k]['pattern']
508 regexp = Regexp.new("^#{pattern}$")
511 "Parameter '#{k}' has an invalid value: #{v}. " +
512 "Must match: /^#{pattern}$/."
521 # Returns a <code>String</code> representation of the method's state.
523 # @return [String] The method's state, as a <code>String</code>.
526 "#<%s:%#0x NAME:%s>", self.class.to_s, self.object_id, self.rpc_name