Class: Cielo24::WebUtils

Inherits:
Object
  • Object
show all
Includes:
JSON
Defined in:
lib/cielo24/web_utils.rb

Constant Summary collapse

BASIC_TIMEOUT =

seconds (1 minute)

60
DOWNLOAD_TIMEOUT =

seconds (5 minutes)

300
UPLOAD_TIMEOUT =

seconds (1 week)

60*60*24*7
LOGGER =
Logger.new(STDOUT)

Class Method Summary collapse

Class Method Details

.get_json(uri, method, timeout, query = nil, headers = nil, body = nil) ⇒ Object



15
16
17
18
# File 'lib/cielo24/web_utils.rb', line 15

def self.get_json(uri, method, timeout, query=nil, headers=nil, body=nil)
  response = http_request(uri, method, timeout, query, headers, body)
  return JSON.parse(response)
end

.http_request(uri, method, timeout, query = nil, headers = nil, body = nil) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/cielo24/web_utils.rb', line 20

def self.http_request(uri, method, timeout, query=nil, headers=nil, body=nil)
  http_client = HTTPClient.new
  http_client.cookie_manager = nil
  http_client.send_timeout = UPLOAD_TIMEOUT
  LOGGER.info(uri + (query.nil? ? '' : '?' + URI.encode_www_form(query)))

  # Timeout block:
  begin
    # Error is raised if the following block fails to execute in 'timeout' sec:
    Timeout.timeout(timeout) { # nil timeout = infinite

      response = http_client.request(method, uri, query, body, headers, nil)
      # Handle web errors
      if response.status_code == 200 or response.status_code == 204
        return response.body
      else
        json = JSON.parse(response.body)
        raise WebError.new(json['ErrorType'], json['ErrorComment'])
      end

    }
  rescue Timeout::Error
    raise TimeoutError.new('The HTTP session has timed out.')
  end
end