class AdsCommon::Api

Attributes

config[R]

Methods that return the client library configuration. Needs to be redefined in subclasses.

credential_handler[R]

Credential handler objects used for authentication.

logger[R]

The logger for this API object.

Public Class Methods

new(provided_config = nil) click to toggle source

Constructor for API.

# File lib/ads_common/api.rb, line 44
def initialize(provided_config = nil)
  @wrappers = {}
  load_config(provided_config)
  check_version(@logger)
end

Public Instance Methods

api_config() click to toggle source

Getter for the API service configurations.

# File lib/ads_common/api.rb, line 57
def api_config()
  return AdsCommon::ApiConfig
end
authorize(parameters = {}) { |oauth_url| ... } click to toggle source

Authorize with specified authentication method.

Args:

- parameters - hash of credentials to add to configuration
- block - code block to handle auth login url

Returns:

- Auth token for the method

Throws:

- AdsCommon::Errors::AuthError or derived if authetication error has
  occured
# File lib/ads_common/api.rb, line 100
def authorize(parameters = {}, &block)
  parameters.each_pair do |key, value|
    @credential_handler.set_credential(key, value)
  end

  auth_handler = get_auth_handler()
  token = auth_handler.get_token()

  # If token is invalid ask for a new one.
  if token.nil?
    begin
      credentials = @credential_handler.credentials
      token = auth_handler.get_token(credentials)
    rescue AdsCommon::Errors::OAuth2VerificationRequired => e
      verification_code = (block_given?) ? yield(e.oauth_url) : nil
      # Retry with verification code if one provided.
      if verification_code
        @credential_handler.set_credential(
            :oauth2_verification_code, verification_code)
        retry
      else
        raise e
      end
    end
  end
  return token
end
get_auth_handler() click to toggle source

Auxiliary method to get an authentication handler. Creates a new one if the handler has not been initialized yet.

Returns:

  • auth handler

# File lib/ads_common/api.rb, line 134
def get_auth_handler()
  if @auth_handler.nil?
    @auth_handler = create_auth_handler()
    @credential_handler.set_auth_handler(@auth_handler)
  end
  return @auth_handler
end
logger=(logger) click to toggle source

Sets the logger to use.

# File lib/ads_common/api.rb, line 51
def logger=(logger)
  @logger = logger
  @config.set('library.logger', @logger)
end
save_oauth2_token(token) click to toggle source

Updates default configuration file to include OAuth2 token information.

# File lib/ads_common/api.rb, line 143
def save_oauth2_token(token)
  raise AdsCommon::Errors::Error, "Can't save nil token" if token.nil?
  AdsCommon::Utils.save_oauth2_token(
      File.join(ENV['HOME'], api_config.default_config_filename), token)
end
service(name, version = nil) click to toggle source

Obtain an API service, given a version and its name.

Args:

  • name: name for the intended service

  • version: intended API version.

Returns:

  • the service wrapper for the intended service.

# File lib/ads_common/api.rb, line 70
def service(name, version = nil)
  name = name.to_sym
  version = (version.nil?) ? api_config.default_version : version.to_sym

  # Check if the combination is available.
  validate_service_request(version, name)

  # Try to re-use the service for this version if it was requested before.
  wrapper = if @wrappers.include?(version) && @wrappers[version][name]
    @wrappers[version][name]
  else
    @wrappers[version] ||= {}
    @wrappers[version][name] = prepare_wrapper(version, name)
  end
  return wrapper
end

Private Instance Methods

class_for_path(path) click to toggle source

Converts complete class path into class object.

# File lib/ads_common/api.rb, line 284
def class_for_path(path)
  path.split('::').inject(Kernel) do |scope, const_name|
    scope.const_get(const_name)
  end
end
create_auth_handler() click to toggle source

Auxiliary method to create an authentication handler.

Returns:

  • auth handler

# File lib/ads_common/api.rb, line 190
def create_auth_handler()
  auth_method = @config.read('authentication.method', :OAUTH2)
  return case auth_method
    when :OAUTH
      raise AdsCommon::Errors::Error,
          'OAuth authorization method is deprecated, use OAuth2 instead.'
    when :OAUTH2
      AdsCommon::Auth::OAuth2Handler.new(
          @config,
          api_config.config(:oauth_scope)
      )
    when :OAUTH2_SERVICE_ACCOUNT
      AdsCommon::Auth::OAuth2ServiceAccountHandler.new(
          @config,
          api_config.config(:oauth_scope)
      )
    else
      raise AdsCommon::Errors::Error,
          "Unknown authentication method '%s'" % auth_method
    end
end
create_default_logger() click to toggle source

Auxiliary method to create a default Logger.

# File lib/ads_common/api.rb, line 238
def create_default_logger()
  logger = Logger.new(STDOUT)
  logger.level = get_log_level_for_string(
      @config.read('library.log_level', 'INFO'))
  return logger
end
get_log_level_for_string(log_level) click to toggle source

Converts log level string (from config) to Logger value.

# File lib/ads_common/api.rb, line 279
def get_log_level_for_string(log_level)
  return Logger.const_get(log_level)
end
init_config() click to toggle source

Initializes config with default values and converts existing if required.

# File lib/ads_common/api.rb, line 255
def init_config()
  # Set up logger.
  provided_logger = @config.read('library.logger')
  self.logger = (provided_logger.nil?) ?
      create_default_logger() : provided_logger

  # Set up default HTTPI adapter.
  provided_adapter = @config.read('connection.adapter')
  @config.set('connection.adapter', :httpclient) if provided_adapter.nil?

  # Make sure Auth param is a symbol.
  symbolize_config_value('authentication.method')
end
load_config(provided_config = nil) click to toggle source

Helper method to load the default configuration file or a given config.

# File lib/ads_common/api.rb, line 246
def load_config(provided_config = nil)
  @config = (provided_config.nil?) ?
      AdsCommon::Config.new(
          File.join(ENV['HOME'], api_config.default_config_filename)) :
      AdsCommon::Config.new(provided_config)
  init_config()
end
prepare_wrapper(version, service) click to toggle source

Handle loading of a single service. Creates the wrapper, sets up handlers and creates an instance of it.

Args:

  • version: intended API version, must be a symbol

  • service: name for the intended service

Returns:

  • a simplified wrapper generated for the service

# File lib/ads_common/api.rb, line 222
def prepare_wrapper(version, service)
  api_config.do_require(version, service)
  endpoint = api_config.endpoint(version, service)
  interface_class_name = api_config.interface_name(version, service)

  wrapper = class_for_path(interface_class_name).new(@config, endpoint)
  auth_handler = get_auth_handler()
  header_ns = api_config.config(:header_ns) + version.to_s
  soap_handler = soap_header_handler(auth_handler, version, header_ns,
                                     wrapper.namespace)
  wrapper.header_handler = soap_handler

  return wrapper
end
soap_header_handler(auth_handler, version, header_ns, default_ns) click to toggle source

Retrieve the SOAP header handler to generate headers based on the configuration. Needs to be implemented on the specific API, because of the different types of SOAP headers.

Args:

  • auth_handler: instance of an AdsCommon::Auth::BaseHandler subclass to handle authentication

  • version: intended API version

  • header_ns: header namespace

  • default_ns: default namespace

Returns:

  • a SOAP header handler

# File lib/ads_common/api.rb, line 181
def soap_header_handler(auth_handler, version, header_ns, default_ns)
  raise NotImplementedError, 'soap_header_handler not overridden.'
end
symbolize_config_value(key) click to toggle source

Converts value of a config key to uppercase symbol.

# File lib/ads_common/api.rb, line 270
def symbolize_config_value(key)
  value_str = @config.read(key).to_s
  if !value_str.nil? and !value_str.empty?
    value = value_str.upcase.to_sym
    @config.set(key, value)
  end
end
validate_service_request(version, service) click to toggle source

Auxiliary method to test parameters correctness for the service request.

# File lib/ads_common/api.rb, line 152
def validate_service_request(version, service)
  # Check if the current config supports the requested version.
  unless api_config.has_version(version)
    raise AdsCommon::Errors::Error,
        "Version '%s' not recognized" % version.to_s
  end

  # Check if the specified version has the requested service.
  unless api_config.version_has_service(version, service)
    raise AdsCommon::Errors::Error,
        "Version '%s' does not contain service '%s'" %
        [version.to_s, service.to_s]
  end
end