Class: NiceHttp

Inherits:
Object
  • Object
show all
Defined in:
lib/nice_http.rb

Overview

Attributes you can access using NiceHttp.the_attribute: :host, :port, :ssl, :headers, :debug, :log, :proxy_host, :proxy_port, :last_request, :last_response, :request_id, :use_mocks, :connections, :active, :auto_redirect

Constant Summary collapse

Error =
Class.new StandardError
InfoMissing =
Class.new Error do
  attr_reader :attribute

  def initialize(attribute)
    @attribute = attribute
    message = "It was not possible to create the http connection!!!\n"
    message += "Wrong #{attribute}, remember to supply http:// or https:// in case you specify an url to create the http connection, for example:\n"
    message += "http = NiceHttp.new('http://example.com')"
    super message
  end
end

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ NiceHttp

Creates a new http connection.

Examples:

http = NiceHttp.new()
http = NiceHttp.new("https://www.example.com")
http = NiceHttp.new("example.com:8999")
http = NiceHttp.new("localhost:8322")
http2 = NiceHttp.new( host: "reqres.in", port: 443, ssl: true )
my_server = {host: "example.com",
             port: 80,
             headers: {"api-key": "zdDDdjkck"}
            }
http3 = NiceHttp.new my_server

Parameters:

  • args (defaults to: {})

    [] If no parameter supplied, by default will access how is setup on defaults

  • args (String) (defaults to: {})

    . The url to create the connection.

  • args (Hash) (defaults to: {})

    containing these possible keys:

    host – example.com. (default blank screen)

    port – port for the connection. 80 (default)

    ssl – true, false (default)

    headers – hash with the headers

    debug – true, false (default)

    log – :no, :screen, :file, :fix_file (default).

    A string with a path can be supplied.
    
    If :fix_file: nice_http.log
    
    In case :file it will be generated a log file with name: nice_http_YY-mm-dd-HHMMSS.log
    

    proxy_host

    proxy_port

Raises:



156
157
158
159
160
161
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
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
# File 'lib/nice_http.rb', line 156

def initialize(args = {})
  require "net/http"
  require "net/https"
  @host = self.class.host
  @port = self.class.port
  @ssl = self.class.ssl
  @headers = self.class.headers.dup
  @debug = self.class.debug
  @log = self.class.log
  @proxy_host = self.class.proxy_host
  @proxy_port = self.class.proxy_port
  @use_mocks = self.class.use_mocks
  @auto_redirect = false #set it up at the end of initialize
  auto_redirect = self.class.auto_redirect
  @num_redirects = 0

  #todo: set only the cookies for the current domain
  #key: path, value: hash with key is the name of the cookie and value the value
  # we set the default value for non existing keys to empty Hash {} so in case of merge there is no problem
  @cookies = Hash.new { |h, k| h[k] = {} }

  if args.is_a?(String)
    uri = URI.parse(args)
    @host = uri.host unless uri.host.nil?
    @port = uri.port unless uri.port.nil?
    @ssl = true if !uri.scheme.nil? && (uri.scheme == "https")
  elsif args.is_a?(Hash) && !args.keys.empty?
    @host = args[:host] if args.keys.include?(:host)
    @port = args[:port] if args.keys.include?(:port)
    @ssl = args[:ssl] if args.keys.include?(:ssl)
    @headers = args[:headers].dup if args.keys.include?(:headers)
    @debug = args[:debug] if args.keys.include?(:debug)
    @log = args[:log] if args.keys.include?(:log)
    @proxy_host = args[:proxy_host] if args.keys.include?(:proxy_host)
    @proxy_port = args[:proxy_port] if args.keys.include?(:proxy_port)
    @use_mocks = args[:use_mocks] if args.keys.include?(:use_mocks)
    auto_redirect = args[:auto_redirect] if args.keys.include?(:auto_redirect)
  end

  begin
    if @log.kind_of?(String)
      f = File.new(@log, "w")
      f.sync = true
      @logger = Logger.new f
    elsif @log == :fix_file
      f = File.new("nice_http.log", "w")
      f.sync = true
      @logger = Logger.new f
    elsif @log == :file
      f = File.new("nice_http_#{Time.now.strftime("%Y-%m-%d-%H%M%S")}.log", "w")
      f.sync = true
      @logger = Logger.new f
    elsif @log == :screen
      @logger = Logger.new STDOUT
    elsif @log == :no
      @logger = Logger.new nil
    else 
      raise InfoMissing, :log
    end
    @logger.level = Logger::INFO
  rescue Exception => stack
    raise InfoMissing, :log
    @logger = Logger.new nil
  end


  if @host.to_s != "" and (@host.include?("http:") or @host.include?("https:"))
    uri = URI.parse(@host)
    @host = uri.host unless uri.host.nil?
    @port = uri.port unless uri.port.nil?
    @ssl = true if !uri.scheme.nil? && (uri.scheme == "https")
  end

  raise InfoMissing, :port if @port.to_s == ""
  raise InfoMissing, :host if @host.to_s == ""
  raise InfoMissing, :ssl unless @ssl.is_a?(TrueClass) or @ssl.is_a?(FalseClass)
  raise InfoMissing, :debug unless @debug.is_a?(TrueClass) or @debug.is_a?(FalseClass)
  raise InfoMissing, :auto_redirect unless auto_redirect.is_a?(TrueClass) or auto_redirect.is_a?(FalseClass)
  raise InfoMissing, :use_mocks unless @use_mocks.is_a?(TrueClass) or @use_mocks.is_a?(FalseClass)
  raise InfoMissing, :headers unless @headers.is_a?(Hash)
  
  begin
    if !@proxy_host.nil? && !@proxy_port.nil?
      @http = Net::HTTP::Proxy(@proxy_host, @proxy_port).new(@host, @port)
      @http.use_ssl = @ssl
      @http.set_debug_output $stderr if @debug
      @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      @http.start
    else
      @http = Net::HTTP.new(@host, @port)
      @http.use_ssl = @ssl
      @http.set_debug_output $stderr if @debug
      @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      @http.start
    end

    @message_server = "(#{self.object_id}):"

    log_message = "(#{self.object_id}): Http connection created. host:#{@host},  port:#{@port},  ssl:#{@ssl}, mode:#{@mode}, proxy_host: #{@proxy_host.to_s()}, proxy_port: #{@proxy_port.to_s()} "

    @logger.info(log_message)
    @message_server += " Http connection: "
    if @ssl
      @message_server += "https://"
    else
      @message_server += "http://"
    end
    @message_server += "#{@host}:#{@port}"
    if @proxy_host.to_s != ""
      @message_server += " proxy:#{@proxy_host}:#{@proxy_port}"
    end
    @auto_redirect = auto_redirect

    self.class.active += 1
    self.class.connections.push(self)
  rescue Exception => stack
    puts stack
    @logger.fatal stack
  end
end

Class Attribute Details

.activeObject

Returns the value of attribute active.



56
57
58
# File 'lib/nice_http.rb', line 56

def active
  @active
end

.auto_redirectObject

Returns the value of attribute auto_redirect.



56
57
58
# File 'lib/nice_http.rb', line 56

def auto_redirect
  @auto_redirect
end

.connectionsObject

Returns the value of attribute connections.



56
57
58
# File 'lib/nice_http.rb', line 56

def connections
  @connections
end

.debugObject

Returns the value of attribute debug.



56
57
58
# File 'lib/nice_http.rb', line 56

def debug
  @debug
end

.headersObject

Returns the value of attribute headers.



56
57
58
# File 'lib/nice_http.rb', line 56

def headers
  @headers
end

.hostObject

Returns the value of attribute host.



56
57
58
# File 'lib/nice_http.rb', line 56

def host
  @host
end

.last_requestObject

Returns the value of attribute last_request.



56
57
58
# File 'lib/nice_http.rb', line 56

def last_request
  @last_request
end

.last_responseObject

Returns the value of attribute last_response.



56
57
58
# File 'lib/nice_http.rb', line 56

def last_response
  @last_response
end

.logObject

Returns the value of attribute log.



56
57
58
# File 'lib/nice_http.rb', line 56

def log
  @log
end

.portObject

Returns the value of attribute port.



56
57
58
# File 'lib/nice_http.rb', line 56

def port
  @port
end

.proxy_hostObject

Returns the value of attribute proxy_host.



56
57
58
# File 'lib/nice_http.rb', line 56

def proxy_host
  @proxy_host
end

.proxy_portObject

Returns the value of attribute proxy_port.



56
57
58
# File 'lib/nice_http.rb', line 56

def proxy_port
  @proxy_port
end

.request_idObject

Returns the value of attribute request_id.



56
57
58
# File 'lib/nice_http.rb', line 56

def request_id
  @request_id
end

.sslObject

Returns the value of attribute ssl.



56
57
58
# File 'lib/nice_http.rb', line 56

def ssl
  @ssl
end

.use_mocksObject

Returns the value of attribute use_mocks.



56
57
58
# File 'lib/nice_http.rb', line 56

def use_mocks
  @use_mocks
end

Instance Attribute Details

#activeInteger

Number of active connections

Returns:

  • (Integer)

    the current value of active



40
41
42
# File 'lib/nice_http.rb', line 40

def active
  @active
end

#auto_redirectBoolean

If true, NiceHttp will take care of the auto redirections when required by the responses

Returns:

  • (Boolean)

    the current value of auto_redirect



40
41
42
# File 'lib/nice_http.rb', line 40

def auto_redirect
  @auto_redirect
end

#connectionsArray

It will include all the active connections (NiceHttp instances)

Returns:

  • (Array)

    the current value of connections



40
41
42
# File 'lib/nice_http.rb', line 40

def connections
  @connections
end

#cookiesHash

Cookies set. The key is the path (String) where cookies are set and the value a Hash with pairs of cookie keys and values, example: { ‘/’ => { “cfid” => “d95adfas2550255”, “amddom.settings” => “doom” } }

Returns:

  • (Hash)

    the current value of cookies



40
41
42
# File 'lib/nice_http.rb', line 40

def cookies
  @cookies
end

#debugBoolean

In case true shows all the details of the communication with the host

Returns:

  • (Boolean)

    the current value of debug



40
41
42
# File 'lib/nice_http.rb', line 40

def debug
  @debug
end

#headersHash

Contains the headers you will be using on your connection

Returns:

  • (Hash)

    the current value of headers



40
41
42
# File 'lib/nice_http.rb', line 40

def headers
  @headers
end

#hostString

The host to be accessed

Returns:

  • (String)

    the current value of host



40
41
42
# File 'lib/nice_http.rb', line 40

def host
  @host
end

#last_requestString

The last request with all the content sent

Returns:

  • (String)

    the current value of last_request



40
41
42
# File 'lib/nice_http.rb', line 40

def last_request
  @last_request
end

#last_responseString

Only in case :debug is true, the last response with all the content

Returns:

  • (String)

    the current value of last_response



40
41
42
# File 'lib/nice_http.rb', line 40

def last_response
  @last_response
end

#logString, Symbol

:fix_file, :no, :screen, :file, “path and file name”. :fix_file will log the communication on nice_http.log. (default). :no will not generate any logs. :screen will print the logs on the screen. :file will be generated a log file with name: nice_http_YY-mm-dd-HHMMSS.log. String the path and file name where the logs will be stored.

Returns:

  • (String, Symbol)

    the current value of log



40
41
42
# File 'lib/nice_http.rb', line 40

def log
  @log
end

#loggerLogger

An instance of the Logger class where logs will be stored. You can access on anytime to store specific data, for example: my_http.logger.info “add this to the log file”

Returns:

  • (Logger)

    the current value of logger

See Also:



40
41
42
# File 'lib/nice_http.rb', line 40

def logger
  @logger
end

#num_redirectsInteger

Number of consecutive redirections managed

Returns:

  • (Integer)

    the current value of num_redirects



40
41
42
# File 'lib/nice_http.rb', line 40

def num_redirects
  @num_redirects
end

#portInteger

The port number

Returns:

  • (Integer)

    the current value of port



40
41
42
# File 'lib/nice_http.rb', line 40

def port
  @port
end

#proxy_hostString

the proxy host to be used

Returns:

  • (String)

    the current value of proxy_host



40
41
42
# File 'lib/nice_http.rb', line 40

def proxy_host
  @proxy_host
end

#proxy_portInteger

the proxy port to be used

Returns:

  • (Integer)

    the current value of proxy_port



40
41
42
# File 'lib/nice_http.rb', line 40

def proxy_port
  @proxy_port
end

#request_idString

If the response includes a requestId, will be stored here

Returns:

  • (String)

    the current value of request_id



40
41
42
# File 'lib/nice_http.rb', line 40

def request_id
  @request_id
end

#responseHash

Contains the full response hash

Returns:

  • (Hash)

    the current value of response



40
41
42
# File 'lib/nice_http.rb', line 40

def response
  @response
end

#sslBoolean

If you use ssl or not

Returns:

  • (Boolean)

    the current value of ssl



40
41
42
# File 'lib/nice_http.rb', line 40

def ssl
  @ssl
end

#use_mocksBoolean

If true, in case the request hash includes a :mock_response key, it will be used as the response instead

Returns:

  • (Boolean)

    the current value of use_mocks



40
41
42
# File 'lib/nice_http.rb', line 40

def use_mocks
  @use_mocks
end

Class Method Details

.defaults=(par = {}) ⇒ Object

Change the default values for NiceHttp supplying a Hash

Parameters:

  • par (Hash) (defaults to: {})

    keys: :host, :port, :ssl, :headers, :debug, :log, :proxy_host, :proxy_port, :use_mocks, :auto_redirect



98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/nice_http.rb', line 98

def self.defaults=(par = {})
  @host = par[:host] if par.key?(:host)
  @port = par[:port] if par.key?(:port)
  @ssl = par[:ssl] if par.key?(:ssl)
  @headers = par[:headers].dup if par.key?(:headers)
  @debug = par[:debug] if par.key?(:debug)
  @log = par[:log] if par.key?(:log)
  @proxy_host = par[:proxy_host] if par.key?(:proxy_host)
  @proxy_port = par[:proxy_port] if par.key?(:proxy_port)
  @use_mocks = par[:use_mocks] if par.key?(:use_mocks)
  @auto_redirect = par[:auto_redirect] if par.key?(:auto_redirect)
end

.inherited(subclass) ⇒ Object

If inheriting from NiceHttp class



86
87
88
# File 'lib/nice_http.rb', line 86

def self.inherited(subclass)
  subclass.reset!
end

.reset!Object

to reset to the original defaults



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/nice_http.rb', line 64

def self.reset!
  @host = nil
  @port = 80
  @ssl = false
  @headers = {}
  @debug = false
  @log = :fix_file
  @proxy_host = nil
  @proxy_port = nil
  @last_request = nil
  @last_response = nil
  @request_id = ""
  @use_mocks = false
  @connections = []
  @active = 0
  @auto_redirect = true
end

Instance Method Details

#closeObject

Close HTTP connection



759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
# File 'lib/nice_http.rb', line 759

def close
  begin
    pos = 0
    found = false
    self.class.connections.each { |conn|
      if conn.object_id == self.object_id
        found = true
        break
      end
      pos += 1
    }
    if found
      self.class.connections.delete_at(pos)
    end

    unless @closed
      if !@http.nil?
        @http.finish()
        @http = nil
        @logger.info "the HTTP connection was closed: #{@message_server}"
      else
        @http = nil
        @logger.fatal "It was not possible to close the HTTP connection: #{@message_server}"
      end
      @closed = true
    else
      @logger.warn "It was not possible to close the HTTP connection, already closed: #{@message_server}"
    end
  rescue Exception => stack
    @logger.fatal stack
  end
  self.class.active -= 1
end

#delete(argument) ⇒ Hash

Delete an existing resource

Examples:

resp = @http.delete(Requests::Customer.remove_session)
assert resp.code == 204

Parameters:

  • arg (Hash)

    containing at least key :path

  • arg (String)

    the path

Returns:

  • (Hash)

    response Including at least the symbol keys: :data = the response data body. :message = plain text response. :code = code response (200=ok,500=wrong…). All keys in response are lowercase. data, message and code can also be accessed as attributes like .message .code .data. In case of fatal error returns { fatal_error: “the error description”, code: nil, message: nil, data: ‘’ }



654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
# File 'lib/nice_http.rb', line 654

def delete(argument)
  begin
    if argument.kind_of?(String)
      argument = {:path => argument}
    end
    path, data, headers_t = manage_request(argument)
    @start_time = Time.now if @start_time.nil?
    if argument.kind_of?(Hash)
      arg = argument
      if @use_mocks and arg.kind_of?(Hash) and arg.keys.include?(:mock_response)
        data = ""
        if arg[:mock_response].keys.include?(:data)
          data = arg[:mock_response][:data]
          if data.kind_of?(Hash) #to json
            begin
              require "json"
              data = data.to_json
            rescue
              @logger.fatal "There was a problem converting to json: #{data}"
            end
          end
        end
        @logger.warn "Pay attention!!! This is a mock response:"
        @start_time_net = Time.now if @start_time_net.nil?
        manage_response(arg[:mock_response], data.to_s)
        return @response
      end
    end

    begin
      @start_time_net = Time.now if @start_time_net.nil?
      resp = @http.delete(path, headers_t)
      data = resp.body
    rescue Exception => stack
      @logger.warn stack
      @logger.warn "The connection seems to be closed in the host machine. Trying to reconnect"
      @http.finish()
      @http.start()
      @start_time_net = Time.now if @start_time_net.nil?
      resp, data = @http.delete(path)
    end
    manage_response(resp, data)

    return @response
  rescue Exception => stack
    @logger.fatal stack
    return {fatal_error: stack.to_s, code: nil, message: nil, data: ""}
  end
end

#get(arg) ⇒ Hash

Get data from path

Examples:

resp = @http.get(Requests::Customer.get_profile)
assert resp.code == 200
resp = @http.get("/customers/1223")
assert resp.message == "OK"

Parameters:

  • arg (Hash)

    containing at least key :path

  • arg (String)

    the path

Returns:

  • (Hash)

    response Including at least the symbol keys: :data = the response data body. :message = plain text response. :code = code response (200=ok,500=wrong…). All keys in response are lowercase. data, message and code can also be accessed as attributes like .message .code .data. In case of fatal error returns { fatal_error: “the error description”, code: nil, message: nil, data: ‘’ }



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/nice_http.rb', line 299

def get(arg)
  begin
    path, data, headers_t = manage_request(arg)
    
    @start_time = Time.now if @start_time.nil?
    if @use_mocks and arg.kind_of?(Hash) and arg.keys.include?(:mock_response)
      data = ""
      if arg[:mock_response].keys.include?(:data)
        data = arg[:mock_response][:data]
        if data.kind_of?(Hash) #to json
          begin
            require "json"
            data = data.to_json
          rescue
            @logger.fatal "There was a problem converting to json: #{data}"
          end
        end
      end
      @logger.warn "Pay attention!!! This is a mock response:"
      @start_time_net = Time.now if @start_time_net.nil?
      manage_response(arg[:mock_response], data.to_s)
      return @response
    end
    begin
      if path.start_with?("http:") or path.start_with?("https:") #server included on path problably because of a redirection to a different server
        require "uri"
        uri = URI.parse(path)
        ssl = false
        ssl = true if path.include?("https:")

        server = "http://"
        server = "https://" if path.include?("https:")
        if uri.port != 443
          server += "#{uri.host}:#{uri.port}"
        else
          server += "#{uri.host}"
        end

        http_redir = nil
        self.class.connections.each { |conn|
          if conn.host == uri.host and conn.port == uri.port
            http_redir = conn
            break
          end
        }

        if !http_redir.nil?
          path, data, headers_t = manage_request(arg)
          http_redir.cookies.merge!(@cookies)
          http_redir.headers.merge!(headers_t)
          resp = http_redir.get(path.gsub(server, "")) #todo: remove only the server at the begining in case in query is the server it will be replaced when it should not be
          @response = http_redir.response
        else
          @logger.warn "It seems like the http connection cannot redirect to #{server} because there is no active connection for that server. You need to create previously one."
        end
      else
        @start_time_net = Time.now if @start_time_net.nil?
        resp = @http.get(path, headers_t)
        data = resp.body
        manage_response(resp, data)
      end
    rescue Exception => stack
      @logger.warn stack
      @logger.warn "The connection seems to be closed in the host machine. Trying to reconnect"
      @http.finish()
      @http.start()
      @start_time_net = Time.now if @start_time_net.nil?
      resp = @http.get(path)
      data = resp.body
      manage_response(resp, data)
    end

    if @auto_redirect and @response[:code].to_i >= 300 and @response[:code].to_i < 400 and @response.include?(:location)
      if @num_redirects <= 30
        @num_redirects += 1
        current_server = "http"
        current_server += "s" if @ssl == true
        current_server += "://#{@host}"
        location = @response[:location].gsub(current_server, "")
        @logger.info "(#{@num_redirects}) Redirecting NiceHttp to #{location}"
        get(location)
      else
        @logger.fatal "(#{@num_redirects}) Maximum number of redirections for a single request reached. Be sure everything is correct, it seems there is a non ending loop"
        @num_redirects = 0
      end
    else
      @num_redirects = 0
    end
    return @response
  rescue Exception => stack
    @logger.fatal stack
    return {fatal_error: stack.to_s, code: nil, message: nil, data: ""}
  end
end

#head(argument) ⇒ Hash

Implementation of the http HEAD method. Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.

Parameters:

  • arg (Hash)

    containing at least key :path

  • arg (String)

    the path

Returns:

  • (Hash)

    response Including at least the symbol keys: :message = plain text response. :code = code response (200=ok,500=wrong…). All keys in response are lowercase. message and code can also be accessed as attributes like .message .code. In case of fatal error returns { fatal_error: “the error description”, code: nil, message: nil }



719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
# File 'lib/nice_http.rb', line 719

def head(argument)
  begin
    if argument.kind_of?(String)
      argument = {:path => argument}
    end
    path, data, headers_t = manage_request(argument)
    @start_time = Time.now if @start_time.nil?
    if argument.kind_of?(Hash)
      arg = argument
      if @use_mocks and arg.kind_of?(Hash) and arg.keys.include?(:mock_response)
        @logger.warn "Pay attention!!! This is a mock response:"
        @start_time_net = Time.now if @start_time_net.nil?
        manage_response(arg[:mock_response], "")
        return @response
      end
    end

    begin
      @start_time_net = Time.now if @start_time_net.nil?
      resp = @http.head(path, headers_t)
      data = resp.body
    rescue Exception => stack
      @logger.warn stack
      @logger.warn "The connection seems to be closed in the host machine. Trying to reconnect"
      @http.finish()
      @http.start()
      @start_time_net = Time.now if @start_time_net.nil?
      resp, data = @http.head(path)
    end
    manage_response(resp, data)
    return @response
  rescue Exception => stack
    @logger.fatal stack
    return {fatal_error: stack.to_s, code: nil, message: nil}
  end
end

#patch(*arguments) ⇒ Hash

Patch data to path

Examples:

resp = @http.patch(Requests::Customer.)

Parameters:

  • arguments (Hash)

    containing at least keys :data and :path. In case :data not supplied and :data_examples array supplied, it will be taken the first example as :data.

  • arguments (Array<path, data, additional_headers>)

    path (string). data (json data for example). additional_headers (Hash key=>value).

Returns:

  • (Hash)

    response Including at least the symbol keys: :data = the response data body. :message = plain text response. :code = code response (200=ok,500=wrong…). All keys in response are lowercase. data, message and code can also be accessed as attributes like .message .code .data. In case of fatal error returns { fatal_error: “the error description”, code: nil, message: nil, data: ‘’ }



575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
# File 'lib/nice_http.rb', line 575

def patch(*arguments)
  begin
    path, data, headers_t = manage_request(*arguments)
    @start_time = Time.now if @start_time.nil?
    if arguments.size > 0 and arguments[0].kind_of?(Hash)
      arg = arguments[0]
      if @use_mocks and arg.kind_of?(Hash) and arg.keys.include?(:mock_response)
        data = ""
        if arg[:mock_response].keys.include?(:data)
          data = arg[:mock_response][:data]
          if data.kind_of?(Hash) #to json
            begin
              require "json"
              data = data.to_json
            rescue
              @logger.fatal "There was a problem converting to json: #{data}"
            end
          end
        end
        @logger.warn "Pay attention!!! This is a mock response:"
        @start_time_net = Time.now if @start_time_net.nil?
        manage_response(arg[:mock_response], data.to_s)
        return @response
      end
    end

    begin
      @start_time_net = Time.now if @start_time_net.nil?
      resp = @http.patch(path, data, headers_t)
      data = resp.body
    rescue Exception => stack
      @logger.warn stack
      @logger.warn "The connection seems to be closed in the host machine. Trying to reconnect"
      @http.finish()
      @http.start()
      @start_time_net = Time.now if @start_time_net.nil?
      resp, data = @http.patch(path, data, headers_t)
    end
    manage_response(resp, data)
    if @auto_redirect and @response[:code].to_i >= 300 and @response[:code].to_i < 400 and @response.include?(:location)
      if @num_redirects <= 30
        @num_redirects += 1
        current_server = "http"
        current_server += "s" if @ssl == true
        current_server += "://#{@host}"
        location = @response[:location].gsub(current_server, "")
        @logger.info "(#{@num_redirects}) Redirecting NiceHttp to #{location}"
        get(location)
      else
        @logger.fatal "(#{@num_redirects}) Maximum number of redirections for a single request reached. Be sure everything is correct, it seems there is a non ending loop"
        @num_redirects = 0
      end
    else
      @num_redirects = 0
    end
    return @response
  rescue Exception => stack
    @logger.fatal stack
    return {fatal_error: stack.to_s, code: nil, message: nil, data: ""}
  end
end

#post(*arguments) ⇒ Hash

Post data to path

Examples:

resp = @http.post(Requests::Customer.update_customer)
assert resp.code == 201
resp = http.post( {
                    path: "/api/users",
                    data: {name: "morpheus", job: "leader"}
                   } )
pp resp.data.json

Parameters:

  • arguments (Hash)

    containing at least keys :data and :path. In case :data not supplied and :data_examples array supplied, it will be taken the first example as :data.

  • arguments (Array<path, data, additional_headers>)

    path (string). data (json data for example). additional_headers (Hash key=>value).

Returns:

  • (Hash)

    response Including at least the symbol keys: :data = the response data body. :message = plain text response. :code = code response (200=ok,500=wrong…). All keys in response are lowercase. data, message and code can also be accessed as attributes like .message .code .data. In case of fatal error returns { fatal_error: “the error description”, code: nil, message: nil, data: ‘’ }



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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# File 'lib/nice_http.rb', line 420

def post(*arguments)
  begin
    path, data, headers_t = manage_request(*arguments)
    @start_time = Time.now if @start_time.nil?
    if arguments.size > 0 and arguments[0].kind_of?(Hash)
      arg = arguments[0]
      if @use_mocks and arg.kind_of?(Hash) and arg.keys.include?(:mock_response)
        data = ""
        if arg[:mock_response].keys.include?(:data)
          data = arg[:mock_response][:data]
          if data.kind_of?(Hash) #to json
            begin
              require "json"
              data = data.to_json
            rescue
              @logger.fatal "There was a problem converting to json: #{data}"
            end
          end
        end
        @logger.warn "Pay attention!!! This is a mock response:"
        @start_time_net = Time.now if @start_time_net.nil?
        manage_response(arg[:mock_response], data.to_s)
        return @response
      end
    end

    begin
      @start_time_net = Time.now if @start_time_net.nil?
      if headers_t["Content-Type"] == "multipart/form-data"
        require "net/http/post/multipart"
        headers_t.each { |key, value|
          arguments[0][:data].add_field(key, value) #add to Headers
        }
        resp = @http.request(arguments[0][:data])
      else
        resp = @http.post(path, data, headers_t)
        data = resp.body
      end
    rescue Exception => stack
      @logger.warn stack
      @logger.warn "The connection seems to be closed in the host machine. Trying to reconnect"
      @http.finish()
      @http.start()
      @start_time_net = Time.now if @start_time_net.nil?
      resp, data = @http.post(path, data, headers_t)
    end
    manage_response(resp, data)
    if @auto_redirect and @response[:code].to_i >= 300 and @response[:code].to_i < 400 and @response.include?(:location)
      if @num_redirects <= 30
        @num_redirects += 1
        current_server = "http"
        current_server += "s" if @ssl == true
        current_server += "://#{@host}"
        location = @response[:location].gsub(current_server, "")
        @logger.info "(#{@num_redirects}) Redirecting NiceHttp to #{location}"
        get(location)
      else
        @logger.fatal "(#{@num_redirects}) Maximum number of redirections for a single request reached. Be sure everything is correct, it seems there is a non ending loop"
        @num_redirects = 0
      end
    else
      @num_redirects = 0
    end
    return @response
  rescue Exception => stack
    @logger.fatal stack
    return {fatal_error: stack.to_s, code: nil, message: nil, data: ""}
  end
end

#put(*arguments) ⇒ Hash

Put data to path

Examples:

resp = @http.put(Requests::Customer.remove_phone)

Parameters:

  • arguments (Hash)

    containing at least keys :data and :path. In case :data not supplied and :data_examples array supplied, it will be taken the first example as :data.

  • arguments (Array<path, data, additional_headers>)

    path (string). data (json data for example). additional_headers (Hash key=>value).

Returns:

  • (Hash)

    response Including at least the symbol keys: :data = the response data body. :message = plain text response. :code = code response (200=ok,500=wrong…). All keys in response are lowercase. data, message and code can also be accessed as attributes like .message .code .data. In case of fatal error returns { fatal_error: “the error description”, code: nil, message: nil, data: ‘’ }



509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/nice_http.rb', line 509

def put(*arguments)
  begin
    path, data, headers_t = manage_request(*arguments)
    @start_time = Time.now if @start_time.nil?
    if arguments.size > 0 and arguments[0].kind_of?(Hash)
      arg = arguments[0]
      if @use_mocks and arg.kind_of?(Hash) and arg.keys.include?(:mock_response)
        data = ""
        if arg[:mock_response].keys.include?(:data)
          data = arg[:mock_response][:data]
          if data.kind_of?(Hash) #to json
            begin
              require "json"
              data = data.to_json
            rescue
              @logger.fatal "There was a problem converting to json: #{data}"
            end
          end
        end
        @logger.warn "Pay attention!!! This is a mock response:"
        @start_time_net = Time.now if @start_time_net.nil?
        manage_response(arg[:mock_response], data.to_s)
        return @response
      end
    end

    begin
      @start_time_net = Time.now if @start_time_net.nil?
      resp = @http.send_request("PUT", path, data, headers_t)
      data = resp.body
    rescue Exception => stack
      @logger.warn stack
      @logger.warn "The connection seems to be closed in the host machine. Trying to reconnect"
      @http.finish()
      @http.start()
      @start_time_net = Time.now if @start_time_net.nil?
      resp, data = @http.send_request("PUT", path, data, headers_t)
    end
    manage_response(resp, data)

    return @response
  rescue Exception => stack
    @logger.fatal stack
    return {fatal_error: stack.to_s, code: nil, message: nil, data: ""}
  end
end