module Dsc::Auto::HttpClient

Attributes

access_token[RW]
auth_type[RW]
base_uri[RW]
content_type[RW]
data_files_path[RW]
email[RW]
history[RW]
host[RW]
http[RW]
log_level[RW]
parsed_response[RW]
password[RW]
response[RW]
token[RW]
user_agent[RW]
version[RW]

Public Instance Methods

build_query(_params = {}) click to toggle source

Takes a hash of params and builds a query string for api calls

Parameters:

params

hash of params - { key_one: “ValueOne”, key_two: “ValueTwo” }

> 'key_one=ValueOne?key_two=ValueTwo'

# File lib/dsc_auto_http_client/http.rb, line 41
def build_query(_params = {})
  res = ''
  _params.each do |key, val|
    if val.kind_of?(Array)
      val.each do |v|
        res << "#{key}=#{v}&"
      end
    else
      res << "#{key}=#{val}&"
    end
  end

  res
end
call(_method, _path, _args = {}) click to toggle source

A symbol declaring the http method to use must be :get, :post, :put, :delete

calls http method on base_uri
# File lib/dsc_auto_http_client/http.rb, line 126
def call(_method, _path, _args = {})

  query = nil
  error_code = nil
  error_body = nil

  path = "#{@base_uri}#{_path}"
  headers = _args[:headers] || get_request_header

  payload = _args[:payload] || _args[:data]

  ### if get and pass in data, create url params out of the data hash
  if _method == :get && payload && payload.respond_to?(:each) && payload.length > 0
    query = build_query( payload )
    path << "?#{query}"
  end

  @logger.debug("DSC::Auto::RestClient.Call : #{query ? "GET, #{path}" :
                    "#{_method.upcase}, #{path}, #{_args}"}, #{headers}\r\n")

  ### default args for get , delete - no payload should be just URL and headers
  http_request_args = [ _method, path, { headers: headers }]
  ### add data to args if post or update
  if _method == :post || :put
    payload = _args[:payload] || _args[:data]
    if payload
      http_request_args[2][:payload] = payload.to_json
    end

  end

  if _args[:user]
    http_request_args[2][:user] = _args[:user]
  end

  if _args[:password]
    http_request_args[2][:password] = _args[:password]
  end

  http_request_args[2][:surpress_call_error] = _args[:surpress_call_error]

  response = self.send(:http_request, *http_request_args)

  @response = response
end
delete(_path, _args = {}) click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 188
def delete(_path, _args = {})
  call(:delete, _path, _args)
end
delete_external(_path, _args = {}) click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 206
def delete_external(_path, _args = {})
  http_request(:delete, _path, _args)
end
get(_path, _args = {}) click to toggle source

HTTP Methods to be called on @base_uri _path will be appended to @base_url

# File lib/dsc_auto_http_client/http.rb, line 176
def get(_path, _args = {})
  call(:get, _path, _args)
end
get_external(_path, _args = {}) click to toggle source

HTTP methods to be called on external hosts

# File lib/dsc_auto_http_client/http.rb, line 194
def get_external(_path, _args = {})
  http_request(:get, _path, _args)
end
get_header() click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 14
def get_header
  {
      :content_type => @content_type,
      :accept => '*/*',
      :cookies => @cookie
  }
end
get_request_header() click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 22
def get_request_header
  if @access_token
    {
        :content_type => @content_type,
        :accept => '*/*',
        :authorization => "Bearer #{@access_token}",
        :cookies => @cookie,
        'User-Agent' => @user_agent
    }
  else
    get_header
  end
end
http_request(_method, _path, _args = {}) click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 69
def http_request(_method, _path, _args = {})

  verify_ssl  = _args[:verify_ssl] == false ? false : true
  response = begin

    request = {
        url: _path,
        method: _method,
        verify_ssl: verify_ssl,
    }
    payload = _args[:data] || _args[:payload]
    request[:payload] = payload
    request[:headers] = _args[:headers] || { :content_type => :json, :accept => '*/*' }

    if _args[:user]
      request[:user] = _args[:user]
    end

    if _args[:password]
      request[:password] = _args[:password]
    end

    @logger.debug("RestClient Request : \r\n#{request}")

    RestClient::Request.execute(request)

  rescue RestClient::ExceptionWithResponse => e
    unless _args[:surpress_call_error]
      @logger.error("Dsc::Auto::HttpClient ERROR \r\n \
                    This may be expected if using this client to test an API\r\n\s \
                            Base URI : #{@base_uri}\r\n\s \
                            API VERSION : /api/v#{@version} \r\n\s \
                            METHOD : #{_method.upcase}\r\n\s \
                            PATH : #{_path} \r\n\s \
                            PARAMETERS : #{_args}\r\n\s \
                            HEADERS : #{request[:headers]}\r\n"
      )
      @logger.error(e.message)
      @logger.error(e.backtrace[0..7].join("\n"))
      error_code = e.response.code if response_has_code?(e.response)
      error_body = e.response.body if response_has_body?(e.response)
      @logger.error("ERROR API RESPONSE HEADERS - #{e.response.headers}") if e.response.headers
      @logger.error("ERROR API RESPONSE CODE - #{error_code}") if error_code
      @logger.error("ERROR API RESPONSE BODY - #{error_body}") if error_body
    end

    e.response

  end

  @history << response

  response
end
parse_json(_json_string, _options = {}) click to toggle source
# File lib/dsc_auto_http_client/parse_json.rb, line 5
def parse_json(_json_string, _options = {})
  fail_msg = _options[:failure_message] || _options[:path] || "parse_json failed trying to parse #{_json_string}"
  begin
    JSON.parse(_json_string)
  rescue JSON::ParserError => e
    full_fail_msg = "ERROR \r\n #{fail_msg} \r\n \
    .parse_json expected param to be json, \
         instead was #{_json_string} \r\n \
    #{e.message} \r\n #{e.backtrace[0..5].join("\r\n")}"
    raise(JSON::ParserError, full_fail_msg, caller )
  end
end
parsed_data_file(_filename) click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 8
def parsed_data_file(_filename)
  filename = _filename.end_with?('.json') ? _filename : "#{_filename}.json"
  @logger.debug("File : #{@data_files_path}/#{filename}")
  parse_json(File.read("#{@data_files_path}/#{filename}"))
end
post(_path, _args = {}) click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 180
def post(_path, _args = {})
  call(:post, _path, _args)
end
post_external(_path, _args = {}) click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 198
def post_external(_path, _args = {})
  http_request(:post, _path, _args)
end
put(_path, _args = {}) click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 184
def put(_path, _args = {})
  call(:put, _path, _args)
end
put_external(_path, _args = {}) click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 202
def put_external(_path, _args = {})
  http_request(:put, _path, _args)
end
query_string_to_hash(_query_string) click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 56
def query_string_to_hash(_query_string)
  Hash[CGI.parse(_query_string).map { |key, values| [key.to_sym, values[0] ||= true] }]
end
response_has_body?(response_object) click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 60
def response_has_body?(response_object)
  response_object.respond_to?('body')
end
response_has_code?(response_object) click to toggle source
# File lib/dsc_auto_http_client/http.rb, line 64
def response_has_code?(response_object)
  response_object.respond_to?('code')
end
set_http_client_attributes(_args = {}) click to toggle source
# File lib/dsc_auto_http_client.rb, line 21
def set_http_client_attributes(_args = {})
  @logger       = Logger.new(STDOUT)
  @log_level    = _args[:log_level] || "INFO"
  @logger.level = Logger.const_get(@log_level)

  @host     = _args[:host]
  @version  = _args[:version]
  @base_uri = _args[:base_uri] || "#{@host}/api/v#{@version}"

  @content_type = _args[:content_type] || :json

  @user_agent = _args[:user_agent] || "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) "\
                        "AppleWebKit/537.36 (KHTML, like Gecko) "\
                        "Chrome/48.0.2564.103 Safari/537.36"

  @token        = _args[:token]
  @cookie       = _args[:cookie]
  @access_token = _args[:access_token]

  @user
  @email    = _args[:email]
  @password = _args[:password]
  @auth_type = _args[:auth_type]
  @history  = []
end