class Hawkular::BaseClient

This is the base functionality for all the clients, that inherit from it. You should not directly use it, but through the more specialized clients.

Constants

HawkularConnectionException
HawkularException

Attributes

credentials[R]

@!visibility private

entrypoint[R]

@!visibility private

logger[R]

@!visibility private

options[R]

@!visibility private

tenants[R]

@return [Tenants] access tenants API

Public Class Methods

new(entrypoint = nil, credentials = {}, options = {}) click to toggle source
   # File lib/hawkular/base_client.rb
23 def initialize(entrypoint = nil,
24                credentials = {},
25                options = {})
26   @entrypoint = entrypoint
27   @credentials = {
28     username: nil,
29     password: nil,
30     token: nil
31   }.merge(credentials)
32   @options = {
33     verify_ssl: OpenSSL::SSL::VERIFY_PEER,
34     headers: {}
35   }.merge(options)
36   @tenant = @options.delete(:tenant)
37   @admin_token = @options.delete(:admin_token)
38 
39   @logger = Hawkular::Logger.new
40 
41   fail Hawkular::ArgumentError, 'You need to provide an entrypoint' if entrypoint.nil?
42 end

Public Instance Methods

admin_header() click to toggle source
    # File lib/hawkular/base_client.rb
177 def admin_header
178   headers = {}
179   headers[:'Hawkular-Admin-Token'] = @admin_token unless @admin_token.nil?
180   headers
181 end
base_64_credentials(credentials = {}) click to toggle source

Encode the passed credentials (username/password) into a base64 representation that can be used to generate a Http-Authentication header @param credentials [Hash{:username,:password}] @return [String] Base64 encoded result

    # File lib/hawkular/base_client.rb
122 def base_64_credentials(credentials = {})
123   creds = credentials.empty? ? @credentials : credentials
124 
125   encoded = Base64.encode64(creds[:username] + ':' + creds[:password])
126   encoded.rstrip!
127 end
generate_query_params(params = {}) click to toggle source

Generate a query string from the passed hash, starting with '?' Values may be an array, in which case the array values are joined together by `,`. @param params [Hash] key-values pairs @return [String] complete query string to append to a base url, '' if no valid params

    # File lib/hawkular/base_client.rb
133 def generate_query_params(params = {})
134   params = params.reject { |_k, v| v.nil? || ((v.instance_of? Array) && v.empty?) }
135   return '' if params.empty?
136 
137   params.inject('?') do |ret, (k, v)|
138     ret += '&' unless ret == '?'
139     part = v.instance_of?(Array) ? "#{k}=#{v.join(',')}" : "#{k}=#{v}"
140     ret + hawk_escape(part)
141   end
142 end
http_delete(suburl, headers = {}) click to toggle source
   # File lib/hawkular/base_client.rb
80 def http_delete(suburl, headers = {})
81   res = rest_client(suburl).delete(http_headers(headers))
82 
83   logger.log(res)
84 
85   res.empty? ? {} : JSON.parse(res)
86 rescue
87   handle_fault $ERROR_INFO
88 end
http_get(suburl, headers = {}) click to toggle source
   # File lib/hawkular/base_client.rb
48 def http_get(suburl, headers = {})
49   res = rest_client(suburl).get(http_headers(headers))
50 
51   logger.log(res)
52 
53   res.empty? ? {} : JSON.parse(res)
54 rescue
55   handle_fault $ERROR_INFO
56 end
http_headers(headers = {}) click to toggle source

@!visibility private

    # File lib/hawkular/base_client.rb
103 def http_headers(headers = {})
104   {}.merge(tenant_header)
105     .merge(token_header)
106     .merge(@options[:headers])
107     .merge(content_type: 'application/json',
108            accept: 'application/json')
109     .merge(headers)
110 end
http_post(suburl, hash, headers = {}) click to toggle source
   # File lib/hawkular/base_client.rb
58 def http_post(suburl, hash, headers = {})
59   body = JSON.generate(hash)
60   res = rest_client(suburl).post(body, http_headers(headers))
61 
62   logger.log(res)
63 
64   res.empty? ? {} : JSON.parse(res)
65 rescue
66   handle_fault $ERROR_INFO
67 end
http_put(suburl, hash, headers = {}) click to toggle source
   # File lib/hawkular/base_client.rb
69 def http_put(suburl, hash, headers = {})
70   body = JSON.generate(hash)
71   res = rest_client(suburl).put(body, http_headers(headers))
72 
73   logger.log(res)
74 
75   res.empty? ? {} : JSON.parse(res)
76 rescue
77   handle_fault $ERROR_INFO
78 end
normalize_entrypoint_url(entrypoint, suffix_path) click to toggle source

Generate a new url with the passed sufix path if the path is not already added also, this function always remove the slash at the end of the URL, so if your entrypoint is localhost/hawkular/inventory/ this function will return localhost/hawkular/inventory to the URL @param entrypoint [String] base path (URIs are also accepted) @param suffix_path [String] sufix path to be added if it doesn't exist @return [String] URL with path attached to it at the end

    # File lib/hawkular/base_client.rb
151 def normalize_entrypoint_url(entrypoint, suffix_path)
152   fail Hawkular::ArgumentError, 'suffix_path must not be empty' if suffix_path.empty?
153 
154   strip_path = suffix_path.gsub(%r{/$}, '')
155   strip_path.nil? || suffix_path = strip_path
156   strip_path = suffix_path.gsub(%r{^/}, '')
157   strip_path.nil? || suffix_path = strip_path
158   entrypoint = entrypoint.to_s
159   strip_entrypoint = entrypoint.gsub(%r{/$}, '')
160   strip_path.nil? && strip_entrypoint = entrypoint
161   relative_path_rgx = Regexp.new("\/#{Regexp.quote(suffix_path)}(\/)*$")
162   if relative_path_rgx.match(entrypoint)
163     strip_entrypoint
164   else
165     "#{strip_entrypoint}/#{suffix_path}"
166   end
167 end
now() click to toggle source

timestamp of current time @return [Integer] timestamp

    # File lib/hawkular/base_client.rb
114 def now
115   Integer(Time.now.to_f * 1000)
116 end
rest_client(suburl) click to toggle source

@!visibility private

    # File lib/hawkular/base_client.rb
 91 def rest_client(suburl)
 92   opts = @options.dup
 93   opts[:timeout] ||= ENV['HAWKULARCLIENT_REST_TIMEOUT'] if ENV['HAWKULARCLIENT_REST_TIMEOUT']
 94   opts[:proxy] ||= opts.delete(:http_proxy_uri)
 95   opts[:user] = @credentials[:username]
 96   opts[:password] = @credentials[:password]
 97   # strip @endpoint in case suburl is absolute
 98   suburl = suburl[@entrypoint.length, suburl.length] if suburl =~ /^http/
 99   RestClient::Resource.new(@entrypoint, opts)[suburl]
100 end
url(url_format, *params) click to toggle source
   # File lib/hawkular/base_client.rb
44 def url(url_format, *params)
45   url_format % params.map { |p| ERB::Util.url_encode(p) }
46 end
url_with_websocket_scheme(url) click to toggle source

Generate a new url using the websocket scheme. It changes the current scheme to 'ws' for 'http' and 'wss' for 'https' urls. @param url [String|URI] url @return [String] URL with the scheme changed to 'ws' or 'wss' depending on the current scheme.

    # File lib/hawkular/base_client.rb
173 def url_with_websocket_scheme(url)
174   url.to_s.sub(/^http(s?)/, 'ws\1')
175 end

Private Instance Methods

connect_error(fault) click to toggle source

@!visibility private

    # File lib/hawkular/base_client.rb
196 def connect_error(fault)
197   if fault.is_a?(SocketError)
198     Hawkular::ConnectionException.new(fault.to_s)
199   elsif [Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EHOSTUNREACH,
200          Errno::EADDRNOTAVAIL, Errno::ENETDOWN, Errno::ENETUNREACH,
201          Errno::ETIMEDOUT].include?(fault.class)
202     Hawkular::ConnectionException.new(fault.to_s, fault.class::Errno)
203   end
204 end
handle_fault(f) click to toggle source
    # File lib/hawkular/base_client.rb
206 def handle_fault(f)
207   http_code = (f.respond_to?(:http_code) ? f.http_code : 0)
208   fail Hawkular::Exception.new('Unauthorized', http_code) if f.instance_of? RestClient::Unauthorized
209 
210   if f.respond_to?(:http_body) && !f.http_body.nil?
211     begin
212       json_body = JSON.parse(f.http_body)
213       fault_message = json_body['errorMsg'] || f.http_body
214     rescue JSON::ParserError
215       fault_message = f.http_body
216     end
217 
218     fail Hawkular::Exception.new(fault_message, http_code)
219   elsif (connect_error_exception = connect_error(f))
220     fail Hawkular::ConnectionException, connect_error_exception
221   else
222     fail Hawkular::Exception, f
223   end
224 end
tenant_header() click to toggle source
    # File lib/hawkular/base_client.rb
189 def tenant_header
190   headers = {}
191   headers[:'Hawkular-Tenant'] = @tenant unless @tenant.nil?
192   headers
193 end
token_header() click to toggle source
    # File lib/hawkular/base_client.rb
185 def token_header
186   @credentials[:token].nil? ? {} : { 'Authorization' => "Bearer #{@credentials[:token]}" }
187 end