Class: GoodData::Rest::Connection

Inherits:
Object
  • Object
show all
Includes:
MonitorMixin
Defined in:
lib/gooddata/rest/connection.rb,
lib/gooddata/rest/phmap.rb

Overview

Wrapper of low-level HTTP/REST client/library

Constant Summary collapse

PH_MAP =

PH_MAP for wildcarding of URLs in reports

[
  ['/gdc/projects/{id}/execute', %r{/gdc/projects/[^\/]+/execute}],

  ['/gdc/dataload/projects/{id}/outputStage', %r{/gdc/dataload/projects/[^\/]+/outputStage}],

  ['/gdc/datawarehouse/instances/{id}', %r{/gdc/datawarehouse/instances/[^\/]+}],
  ['/gdc/datawarehouse/executions/{id}', %r{/gdc/datawarehouse/executions/[^\/]+}],

  # domain dataproducts' clients
  ['/gdc/domains/{id}/dataproducts/{data_product}/clients?segment={segment}',
   %r{\/gdc\/domains\/[^\/]+\/dataproducts\/[^\/]+\/clients\?.*segment=[^\/]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/clients/{client}', %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/clients/[^\/]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/clients', %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/clients}],

  # domain dataproducts' segments
  ['/gdc/domains/{id}/dataproducts/{data_product}/segments/{segment}/synchronizeClients/results/{result}/details?offset={offset}&limit={limit}',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/segments/[^\/]+/synchronizeClients/results/[^\/]+/details\?offset=[\d]+&limit=[\d]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/segments/{segment}/synchronizeClients/results/{result}',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/segments/[^\/]+/synchronizeClients/results/[^\/]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/segments/{segment}', %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/segments/[^\/]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/segments', %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/segments}],

  # domain dataproducts' provision & update
  ['/gdc/domains/{id}/dataproducts/{data_product}/provisionClientProjects/results/{result}/details?offset={offset}&limit={limit}',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/provisionClientProjects/results/[^\/]+/details\?offset=[\d]+&limit=[\d]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/provisionClientProjects/results/{result}',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/provisionClientProjects/results/[^\/]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/provisionClientProjects',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/provisionClientProjects}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/updateClients?deleteExtraInSegments={segments}',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/updateClients\?deleteExtraInSegments=[^\/]+}],
  ['/gdc/domains/{id}/dataproducts/{data_product}/updateClients',
   %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+/updateClients}],

  # domain dataproduct
  ['/gdc/domains/{id}/dataproducts/{data_product}', %r{/gdc/domains/[^\/]+/dataproducts/[^\/]+}],
  ['/gdc/domains/{id}/dataproducts', %r{/gdc/domains/[^\/]+/dataproducts}],

  # domain segments
  ['/gdc/domains/{id}/segments/{segment}/synchronizeClients/results/{result}/details?offset={offset}&limit={limit}',
   %r{/gdc/domains/[^\/]+/segments/[^\/]+/synchronizeClients/results/[^\/]+/details\?offset=[\d]+&limit=[\d]+}],
  ['/gdc/domains/{id}/segments/{segment}/synchronizeClients/results/{result}',
   %r{/gdc/domains/[^\/]+/segments/[^\/]+/synchronizeClients/results/[^\/]+}],
  ['/gdc/domains/{id}/segments/{segment}/', %r{/gdc/domains/[^\/]+/segments/[^\/]+/}],
  ['/gdc/domains/{id}/segments/{segment}', %r{/gdc/domains/[^\/]+/segments/[^\/]+}],

  # domain clients
  ['/gdc/domains/{id}/clients?segment={segment}', %r{/gdc/domains/[^\/]+/clients\?segment=[^\/]+}],
  ['/gdc/domains/{id}/clients/{client_id}/settings/lcm.title', %r{/gdc/domains/[^\/]+/clients/[^\/]+/settings/lcm.title}],
  ['/gdc/domains/{id}/clients/{client_id}/settings/lcm.token', %r{/gdc/domains/[^\/]+/clients/[^\/]+/settings/lcm.token}],
  ['/gdc/domains/{id}/clients/{client_id}', %r{/gdc/domains/[^\/]+/clients/[^\/]+}],
  ['/gdc/domains/{id}/provisionClientProjects/results/{result}/details?offset={offset}&limit={limit}',
   %r{/gdc/domains/[^\/]+/provisionClientProjects/results/[^\/]+/details\?offset=[\d]+&limit=[\d]+}],
  ['/gdc/domains/{id}/provisionClientProjects/results/{result}', %r{/gdc/domains/[^\/]+/provisionClientProjects/results/[^\/]+}],
  ['/gdc/domains/{id}/provisionClientProjects', %r{/gdc/domains/[^\/]+/provisionClientProjects}],
  ['/gdc/domains/{id}/updateClients', %r{/gdc/domains/[^\/]+/updateClients}],
  ['/gdc/domains/{id}/', %r{/gdc/domains/[^\/]+/}],

  ['/gdc/exporter/result/{id}/{id}', %r{/gdc/exporter/result/[^\/]+/[^\/]+}],

  ['/gdc/internal/lcm/domains/{id}/dataproducts/{data_product}/segments/{segment}/syncProcesses/{process}',
   %r{/gdc/internal/lcm/domains/[^\/]+/dataproducts/[^\/]+/segments/[^\/]+/syncProcesses/[^\/]+}],
  ['/gdc/internal/lcm/domains/{id}/dataproducts/{data_product}/segments/{segment}/syncProcesses',
   %r{/gdc/internal/lcm/domains/[^\/]+/dataproducts/[^\/]+/segments/[^\/]+/syncProcesses}],

  ['/gdc/internal/projects/{id}/objects/setPermissions', %r{/gdc/internal/projects/[^\/]+/objects/setPermissions}],
  ['/gdc/internal/projects/{id}/roles', %r{/gdc/internal/projects/[^\/]+/roles}],
  ['/gdc/dataload/projects/{id}/modelMapping/datasets/bulk/upsert', %r{/gdc/dataload/projects/[^\/]+/modelMapping/datasets/bulk/upsert}],
  ['/gdc/md/{id}/variables/item/{id}', %r{/gdc/md/[^\/]+/variables/item/[\d]+}],
  ['/gdc/md/{id}/validate/task/{id}', %r{/gdc/md/[^\/]+/validate/task/[^\/]+}],
  ['/gdc/md/{id}/using2/{id}/{id}', %r{/gdc/md/[^\/]+/using2/[\d]+/[\d]+}],
  ['/gdc/md/{id}/using2/{id}', %r{/gdc/md/[^\/]+/using2/[\d]+}],
  ['/gdc/md/{id}/userfilters?users={users}', %r{\/gdc\/md\/[^\/]+\/userfilters\?users=[\/\w+@.]+}],
  ['/gdc/md/{id}/userfilters?count={count}&offset={offset}', %r{/gdc/md/[^\/]+/userfilters\?count=[\d]+&offset=[\d]+}],
  ['/gdc/md/{id}/usedby2/{id}/{id}', %r{/gdc/md/[^\/]+/usedby2/[\d]+/[\d]+}],
  ['/gdc/md/{id}/usedby2/{id}', %r{/gdc/md/[^\/]+/usedby2/[\d]+}],
  ['/gdc/md/{id}/tasks/{id}/status', %r{/gdc/md/[^\/]+/tasks/[^\/]+/status}],
  ['/gdc/md/{id}/obj/{id}/validElements', %r{/gdc/md/[^\/]+/obj/[\d]+/validElements(/)?(\?.*)?}],
  ['/gdc/md/{id}/obj/{id}/elements', %r{/gdc/md/[^\/]+/obj/[\d]+/elements(/)?(\?.*)?}],
  ['/gdc/md/{id}/obj/{id}', %r{/gdc/md/[^\/]+/obj/[\d]+}],
  ['/gdc/md/{id}/etltask/{id}', %r{/gdc/md/[^\/]+/etltask/[^\/]+}],
  ['/gdc/md/{id}/dataResult/{id}', %r{/gdc/md/[^\/]+/dataResult/[\d]+}],
  ['/gdc/md/{id}', %r{/gdc/md/[^\/]+}],

  ['/gdc/projects/{id}/users/{id}/roles', %r{/gdc/projects/[^\/]+/users/[^\/]+/roles}],
  ['/gdc/projects/{id}/users/{id}/permissions', %r{/gdc/projects/[^\/]+/users/[^\/]+/permissions}],
  ['/gdc/projects/{id}/users', %r{/gdc/projects/[^\/]+/users}],
  ['/gdc/projects/{id}/schedules/{id}/executions/{id}', %r{/gdc/projects/[^\/]+/schedules/[^\/]+/executions/[^\/]+}],
  ['/gdc/projects/{id}/schedules/{id}', %r{/gdc/projects/[^\/]+/schedules/[^\/]+}],
  ['/gdc/projects/{id}/roles/{id}', %r{/gdc/projects/[^\/]+/roles/[\d]+}],
  ['/gdc/projects/{id}/model/view/{id}', %r{/gdc/projects/[^\/]+/model/view/[^\/]+}],
  ['/gdc/projects/{id}/model/view', %r{/gdc/projects/[^\/]+/model/view}],
  ['/gdc/projects/{id}/model/diff/{id}', %r{/gdc/projects/[^\/]+/model/diff/[^\/]+}],
  ['/gdc/projects/{id}/model/diff', %r{/gdc/projects/[^\/]+/model/diff}],
  ['/gdc/projects/{id}/dataload/metadata/{project}', %r{/gdc/projects/[^\/]+/dataload/metadata/[^\/]+}],
  ['/gdc/projects/{id}/dataload/processes/{id}/executions/{id}', %r{/gdc/projects/[^\/]+/dataload/processes/[^\/]+/executions/[^\/]+}],
  ['/gdc/projects/{id}/dataload/processes/{id}', %r{/gdc/projects/[^\/]+/dataload/processes/[^\/]+}],
  ['/gdc/projects/{id}/', %r{/gdc/projects/[^\/]+/}],
  ['/gdc/projects/{id}', %r{/gdc/projects/[^\/]+}],

  ['/gdc/userGroups/{id}', %r{/gdc/userGroups/[^\/]+}],

  ['/gdc/account/profile/{id}', %r{/gdc/account/profile/[^\/]+}],
  ['/gdc/account/login/{id}', %r{/gdc/account/login/[^\/]+}],
  ['/gdc/account/domains/{id}/users?login={login}', %r{/gdc/account/domains/[^\/]+/users\?login=[^&$]+}],
  ['/gdc/account/domains/{id}', %r{/gdc/account/domains/[^\/]+}]
]
HTTPS_PROTOCOL =
'https://'
HTTP_PROTOCOL =
'http://'
DEFAULT_URL =
'https://secure.gooddata.com'
LOGIN_PATH =
'/gdc/account/login'
TOKEN_PATH =
'/gdc/account/token'
KEYS_TO_SCRUB =
[:password, :verifyPassword, :authorizationToken]
API_LEVEL =
2
ID_LENGTH =
16
DEFAULT_HEADERS =
{
  :content_type => :json,
  :accept => [:json, :zip],
  :user_agent => GoodData.gem_version_string
}
DEFAULT_WEBDAV_HEADERS =
{
  :user_agent => GoodData.gem_version_string
}
CERTIFICATE_STORE =
OpenSSL::X509::Store.new.freeze
DEFAULT_LOGIN_PAYLOAD =
{
  :headers => DEFAULT_HEADERS,
  :verify_ssl => true,
  :ssl_cert_store => CERTIFICATE_STORE
}
RETRYABLE_ERRORS =
[
  Net::HTTPBadResponse,
  RestClient::InternalServerError,
  RestClient::RequestTimeout,
  RestClient::MethodNotAllowed,
  SystemCallError,
  Timeout::Error
]
RETRY_TIME_INITIAL_VALUE =
1
RETRY_TIME_COEFFICIENT =
1.5

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Connection

Returns a new instance of Connection.



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/gooddata/rest/connection.rb', line 142

def initialize(opts)
  super()
  @stats = ThreadSafe::Hash.new
  @execution_id = opts[:execution_id]

  headers = opts[:headers] || {}
  @webdav_headers = DEFAULT_WEBDAV_HEADERS.merge(headers)

  @user = nil
  @server = nil
  @opts = opts
  @verify_ssl = @opts[:verify_ssl] == false || @opts[:verify_ssl] == OpenSSL::SSL::VERIFY_NONE ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER

  # Initialize headers
  reset_headers!

  @at_exit_handler_installed = nil
end

Instance Attribute Details

#request_paramsObject (readonly) Also known as: cookies, headers

Returns the value of attribute request_params.



132
133
134
# File 'lib/gooddata/rest/connection.rb', line 132

def request_params
  @request_params
end

#serverObject (readonly)

Returns the value of attribute server.



137
138
139
# File 'lib/gooddata/rest/connection.rb', line 137

def server
  @server
end

#statsObject (readonly)

Returns the value of attribute stats.



138
139
140
# File 'lib/gooddata/rest/connection.rb', line 138

def stats
  @stats
end

#userObject (readonly)

Returns the value of attribute user.



139
140
141
# File 'lib/gooddata/rest/connection.rb', line 139

def user
  @user
end

#verify_sslObject (readonly)

Returns the value of attribute verify_ssl.



140
141
142
# File 'lib/gooddata/rest/connection.rb', line 140

def verify_ssl
  @verify_ssl
end

Class Method Details

.construct_login_payload(username, password) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
# File 'lib/gooddata/rest/connection.rb', line 72

def (username, password)
  res = {
    'postUserLogin' => {
      'login' => username,
      'password' => password,
      'remember' => 1,
      'verify_level' => 2
    }
  }
  res
end

.generate_string(length = ID_LENGTH) ⇒ String

Generate random string with URL safe base64 encoding

Parameters:

  • length (String) (defaults to: ID_LENGTH)

    Length of random string to be generated

Returns:

  • (String)

    Generated random string



89
90
91
# File 'lib/gooddata/rest/connection.rb', line 89

def generate_string(length = ID_LENGTH)
  SecureRandom.urlsafe_base64(length)
end

.map_placeholders(title) ⇒ Object



10
11
12
13
14
15
# File 'lib/gooddata/rest/phmap.rb', line 10

def self.map_placeholders(title)
  PH_MAP.each do |pm|
    break if title.gsub!(pm[1], pm[0])
  end
  title
end

.retryable(options = {}, &_block) ⇒ Object

Retry block if exception thrown



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/gooddata/rest/connection.rb', line 94

def retryable(options = {}, &_block)
  opts = { :tries => 12, :on => RETRYABLE_ERRORS }.merge(options)

  retry_exception = opts[:on]
  retries = opts[:tries]

  unless retry_exception.is_a?(Array)
    retry_exception = [retry_exception]
  end

  retry_time = RETRY_TIME_INITIAL_VALUE
  begin
    return yield
  rescue RestClient::Unauthorized, RestClient::Forbidden => e # , RestClient::Unauthorized => e
    raise e unless options[:refresh_token]
    raise e if options[:dont_reauth]

    options[:refresh_token].call # (dont_reauth: true)
    if (retries -= 1) > 0
      retry
    else
      fail e
    end
  rescue RestClient::TooManyRequests, RestClient::ServiceUnavailable, *retry_exception => e
    GoodData.logger.warn "#{e.message}, retrying in #{retry_time} seconds"
    sleep retry_time
    retry_time *= RETRY_TIME_COEFFICIENT
    # 10 requests with 1.5 coefficent should take ~ 3 mins to finish
    if (retries -= 1) > 0
      retry
    else
      fail e
    end
  end
  yield
end

Instance Method Details

#connect(username, password, options = {}) ⇒ Object

Connect using username and password



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/gooddata/rest/connection.rb', line 162

def connect(username, password, options = {})
  server = options[:server] || Helpers::AuthHelper.read_server
  options = DEFAULT_LOGIN_PAYLOAD.merge(options)
  headers = options[:headers] || {}

  options = options.merge(headers)
  @server = RestClient::Resource.new fix_server_url(server), options

  # Install at_exit handler first
  unless @at_exit_handler_installed
    begin
      at_exit { disconnect if @user }
    rescue RestClient::Unauthorized
      GoodData.logger.info 'Already logged out'
    ensure
      @at_exit_handler_installed = true
    end
  end

  # Reset old cookies first
  if options[:sst_token]
    headers = {
      :x_gdc_authsst => options[:sst_token],
      :x_gdc_authtt => options[:tt_token]
    }
    merge_headers!(headers)
    get('/gdc/account/token', @request_params)

    @user = get('/gdc/account/profile/current')
    GoodData.logger.info("Connected using SST to server #{@server.url} to profile \"#{@user['accountSetting']['login']}\"")
    @auth = {}
    refresh_token :dont_reauth => true
  elsif  options[:headers][:x_gdc_authsst]
    @request_params = options[:headers]
    @user = get('/gdc/account/profile/current')
    GoodData.logger.info("Connected using SST to server #{@server.url} to profile \"#{@user['accountSetting']['login']}\"")
    @auth = {}
    refresh_token :dont_reauth => true
  else
    GoodData.logger.info("Connected using username \"#{username}\" to server #{@server.url}")
    credentials = Connection.(username, password)
    generate_session_id
    @auth = post(LOGIN_PATH, credentials, :dont_reauth => true)['userLogin']

    refresh_token :dont_reauth => true
    @user = get(@auth['profile'])
  end
  GoodData.logger.info('Connection successful')
rescue RestClient::Unauthorized => e
  GoodData.logger.info('Bad Login or Password')
  GoodData.logger.info('Connection failed')
  raise e
rescue RestClient::Forbidden => e
  GoodData.logger.info('Connection failed')
  raise e
end

#delete(uri, options = {}) ⇒ Object

HTTP DELETE

Parameters:

  • uri (String)

    Target URI



327
328
329
# File 'lib/gooddata/rest/connection.rb', line 327

def delete(uri, options = {})
  request(:delete, uri, nil, options)
end

#disconnectObject

Disconnect



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/gooddata/rest/connection.rb', line 220

def disconnect
  # TODO: Wrap somehow
  url = @auth['state']

  begin
    clear_session_id
    delete(url, :x_gdc_authsst => sst_token, :tries => 0) if url
  rescue RestClient::Unauthorized
    begin
      refresh_token
      delete(url, :x_gdc_authsst => sst_token, :tries => 0) if url
    rescue RestClient::Unauthorized
      GoodData.logger.info 'Already disconnected'
    end
  end

  @auth = nil
  @server = nil
  @user = nil

  reset_headers!
end

#download(what, where, options = {}) ⇒ Object

Parameters:

  • what

    Address of the remote file.

  • where

    Full path to the target file.

  • [Bool] (Hash)

    a customizable set of options



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/gooddata/rest/connection.rb', line 246

def download(what, where, options = {})
  # handle the path (directory) given in what
  ilast_slash = what.rindex('/')
  if ilast_slash.nil?
    what_dir = ''
  else
    # take the directory from the path
    what_dir = what[0..ilast_slash - 1]
    # take the filename from the path
    what = what[ilast_slash + 1..-1]
  end

  option_dir = options[:directory] || ''
  option_dir = option_dir[0..-2] if option_dir[-1] == '/'

  # join the otion dir with the what_dir
  # [option dir empty, what dir empty] => the joined dir
  dir_hash = {
    [true, true] => '',
    [true, false] => what_dir,
    [false, true] => option_dir,
    [false, false] => "#{what_dir}/#{option_dir}"
  }
  dir = dir_hash[[option_dir.empty?, what_dir.empty?]]

  staging_uri = options[:staging_url].to_s

  base_url = dir.empty? ? staging_uri : URI.join("#{server}", staging_uri, "#{dir}/").to_s
  sanitized_what = options[:url_encode] == false ? what : CGI.escape(what)
  url = URI.join("#{server}", base_url, sanitized_what).to_s

  b = proc do |f|
    raw = {
      :headers => @webdav_headers.merge(:x_gdc_authtt => headers[:x_gdc_authtt]),
      :method => :get,
      :url => url,
      :verify_ssl => verify_ssl
    }
    RestClient::Request.execute(raw) do |chunk, _x, response|
      if response.code.to_s == '202'
        fail RestRetryError, 'Got 202, retry'
      elsif response.code.to_s != '200'
        fail ArgumentError, "Error downloading #{url}. Got response: #{response.code} #{response} #{response.body}"
      end
      f.write chunk
    end
  end

  GoodData::Rest::Connection.retryable(:tries => Helpers::GD_MAX_RETRY, :refresh_token => proc { refresh_token }, :on => RestRetryError) do
    if where.is_a?(IO) || where.is_a?(StringIO)
      b.call(where)
    else
      # Assume it is a string or file
      File.open(where, 'w') do |f|
        b.call(f)
      end
    end
  end
end

#enrich_error_message(exception) ⇒ Object



474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/gooddata/rest/connection.rb', line 474

def enrich_error_message(exception)
  begin
    return exception unless exception.response

    response = JSON.parse(exception.response.body, symbolize_names: true)
    return exception unless exception.message && response[:error] && response[:error][:message]

    request_id = exception.response.headers[:x_gdc_request] || 'unknown'

    exception.message = exception.message + ': ' + response[:error][:message] % response[:error][:parameters] + ' request_id: ' + request_id
  rescue JSON::ParserError # rubocop:disable Lint/HandleExceptions
  end
  exception
end

#generate_request_idObject



470
471
472
# File 'lib/gooddata/rest/connection.rb', line 470

def generate_request_id
  "#{@execution_id}:#{session_id}:#{call_id}"
end

#get(uri, options = {}, &user_block) ⇒ Object

HTTP GET

Parameters:

  • uri (String)

    Target URI



376
377
378
# File 'lib/gooddata/rest/connection.rb', line 376

def get(uri, options = {}, &user_block)
  request(:get, uri, nil, options, &user_block)
end

#log_error(e, uri, params, options = {}) ⇒ Object

Helper for logging error

Parameters:

  • e (RuntimeException)

    Exception to log

  • uri (String)

    Uri on which the request failed

  • params (Hash)

    Additional params



336
337
338
339
340
341
342
# File 'lib/gooddata/rest/connection.rb', line 336

def log_error(e, uri, params, options = {})
  return if e.response && e.response.code == 401 && !uri.include?('token') && !uri.include?('login')

  if options[:do_not_log].nil? || options[:do_not_log].index(e.class).nil?
    GoodData.logger.error(format_error(e, params))
  end
end

#post(uri, data = nil, options = {}) ⇒ Object

HTTP POST

Parameters:

  • uri (String)

    Target URI



390
391
392
# File 'lib/gooddata/rest/connection.rb', line 390

def post(uri, data = nil, options = {})
  request(:post, uri, data, options)
end

#put(uri, data, options = {}) ⇒ Object

HTTP PUT

Parameters:

  • uri (String)

    Target URI



383
384
385
# File 'lib/gooddata/rest/connection.rb', line 383

def put(uri, data, options = {})
  request(:put, uri, data, options)
end

#refresh_token(_options = {}) ⇒ Object



306
307
308
309
310
311
312
313
314
315
# File 'lib/gooddata/rest/connection.rb', line 306

def refresh_token(_options = {})
  begin # rubocop:disable RedundantBegin
    # avoid infinite loop GET fails with 401
    response = get(TOKEN_PATH, :x_gdc_authsst => sst_token, :dont_reauth => true)
    # Remove when TT sent in headers. Currently we need to parse from body
    merge_headers!(:x_gdc_authtt => GoodData::Helpers.get_path(response, %w(userToken token)))
  rescue Exception => e # rubocop:disable RescueException
    raise e
  end
end

#request(method, uri, data, options = {}, &user_block) ⇒ Object



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/gooddata/rest/connection.rb', line 344

def request(method, uri, data, options = {}, &user_block)
  request_id = options[:request_id] || generate_request_id
  log_info(options.merge(request_id: request_id))
  stats_on = options[:stats_on]

  payload = data.is_a?(Hash) ? data.to_json : data

  GoodData.rest_logger.info "#{method.to_s.upcase}: #{@server.url}#{uri}, #{scrub_params(data, KEYS_TO_SCRUB)}"
  profile method.to_s.upcase, uri, request_id, stats_on do
    b = proc do
      params = fresh_request_params(request_id).merge(options)

      params['X-GDC-VERSION'] = API_LEVEL

      case method
      when :get
        @server[uri].get(params, &user_block)
      when :put
        @server[uri].put(payload, params)
      when :delete
        @server[uri].delete(params)
      when :post
        @server[uri].post(payload, params)
      end
    end
    process_response(options, &b)
  end
end

#server_urlString

Returns server URI

Returns:

  • (String)

    server uri



320
321
322
# File 'lib/gooddata/rest/connection.rb', line 320

def server_url
  @server && @server.url
end

#sst_tokenObject

Reader method for SST token



397
398
399
# File 'lib/gooddata/rest/connection.rb', line 397

def sst_token
  request_params[:x_gdc_authsst]
end

#stats_table(values = stats) ⇒ Object



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/gooddata/rest/connection.rb', line 401

def stats_table(values = stats)
  sorted = values.sort_by { |_k, v| v[:avg] }
  Terminal::Table.new :headings => %w(title avg min max total calls) do |t|
    overall = {
      :avg => 0,
      :calls => 0,
      :total => 0
    }

    sorted.each do |l|
      avg = l[1][:avg]
      min = l[1][:min]
      max = l[1][:max]
      total = l[1][:total]
      calls = l[1][:calls]

      row = [
        l[0],
        sprintf('%.3f', avg),
        sprintf('%.3f', min),
        sprintf('%.3f', max),
        sprintf('%.3f', total),
        calls
      ]

      overall[:min] = min if overall[:min].nil? || min < overall[:min]
      overall[:max] = max if overall[:max].nil? || max > overall[:max]
      overall[:total] += total
      overall[:calls] += calls
      overall[:avg] += avg

      t.add_row row
    end

    overall[:avg] = overall[:avg] / sorted.length
    row = [
      'TOTAL',
      sprintf('%.3f', overall[:avg]),
      sprintf('%.3f', overall[:min]),
      sprintf('%.3f', overall[:max]),
      sprintf('%.3f', overall[:total]),
      overall[:calls]
    ]

    t.add_row :separator
    t.add_row row
  end
end

#tt_tokenObject

Reader method for TT token



453
454
455
# File 'lib/gooddata/rest/connection.rb', line 453

def tt_token
  request_params[:x_gdc_authtt]
end

#upload(file, options = {}) ⇒ Object

Uploads a file to GoodData server



459
460
461
462
463
464
465
466
467
468
# File 'lib/gooddata/rest/connection.rb', line 459

def upload(file, options = {})
  dir = options[:directory] || ''
  staging_uri = options[:staging_url].to_s
  url = dir.empty? ? staging_uri : URI.join("#{server}", staging_uri, "#{dir}/").to_s
  # Make a directory, if needed
  create_webdav_dir_if_needed url unless dir.empty?

  webdav_filename = options[:filename] || File.basename(file)
  do_stream_file URI.join("#{server}", url, CGI.escape(webdav_filename)), file
end