Class: NOMS::HttpClient::Real

Inherits:
NOMS::HttpClient show all
Defined in:
lib/noms/httpclient.rb

Instance Method Summary collapse

Methods inherited from NOMS::HttpClient

#allow_partial_updates, #allow_put_to_create, #dbg, #handle_mock, #ltrim, #method_missing, mock!, mockery, #myconfig, #opt, #rtrim, #trim

Constructor Details

#initialize(delegator) ⇒ Real

Returns a new instance of Real.



362
363
364
365
366
367
# File 'lib/noms/httpclient.rb', line 362

def initialize(delegator)
    @delegator = delegator
    @opt = @delegator.opt
    @opt['return-hash'] = true unless @opt.has_key? 'return-hash'
    self.dbg "Initialized with options: #{opt.inspect}"
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class NOMS::HttpClient

Instance Method Details

#_xml_to_hash(rexml) ⇒ Object



492
493
494
# File 'lib/noms/httpclient.rb', line 492

def _xml_to_hash(rexml)
    NOMS::XmlHash.new rexml.root
end

#config_keyObject



369
370
371
# File 'lib/noms/httpclient.rb', line 369

def config_key
    @delegator.config_key
end

#default_content_typeObject



373
374
375
# File 'lib/noms/httpclient.rb', line 373

def default_content_type
    @delegator.default_content_type
end

#do_request(opt = {}) ⇒ Object



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
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
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
489
490
# File 'lib/noms/httpclient.rb', line 382

def do_request(opt={})
    method = [:GET, :PUT, :POST, :DELETE].find do |m|
        opt.has_key? m
    end
    if method == nil
      method = :GET
      opt[method] = ''
    end
    rel_uri = opt[method]
    opt[:redirect_limit] ||= 10
    if opt[:absolute]
      url = URI.parse(rel_uri)
    else
      url = URI.parse(myconfig 'url')
      unless opt[method] == ''
        url.path = rtrim(url.path) + '/' + ltrim(rel_uri) unless opt[:absolute]
      end
      url.query = opt[:query] if opt.has_key? :query
    end
    self.dbg("#{method.inspect} => #{url.to_s}")
    http = Net::HTTP.new(url.host, url.port)
    http.read_timeout = myconfig.has_key?('timeout') ? myconfig['timeout'] : 120
    http.use_ssl = true if url.scheme == 'https'
    if http.use_ssl?
        self.dbg("using SSL/TLS")
        if myconfig.has_key? 'verify-with-ca'
            http.verify_mode = OpenSSL::SSL::VERIFY_PEER
            http.ca_file = myconfig['verify-with-ca']
        else
            http.verify_mode = OpenSSL::SSL::VERIFY_NONE
        end
    else
        self.dbg("NOT using SSL/TLS")
    end
    reqclass = case method
               when :GET
                   Net::HTTP::Get
               when :PUT
                   Net::HTTP::Put
               when :POST
                   Net::HTTP::Post
               when :DELETE
                   Net::HTTP::Delete
               end
    request = reqclass.new(url.request_uri)
    self.dbg request.to_s
    if myconfig.has_key? 'username'
        self.dbg "will do basic authentication as #{myconfig['username']}"
        request.basic_auth(myconfig['username'], myconfig['password'])
    else
        self.dbg "no authentication"
    end
    if opt.has_key? :body
      content_type = opt[:content_type] || default_content_type
      request['Content-Type'] = content_type
      request.body = case content_type
                     when /json$/
                       opt[:body].to_json
                     when /xml$/
                       opt[:body].to_xml
                     else
                       opt[:body]
                     end
    end
    response = http.request(request)
    self.dbg response.to_s
    if response.is_a? Net::HTTPRedirection
        if opt[:redirect_limit] == 0
            raise "Error (#{self.class}) making #{config_key} request " +
              "(redirect limit exceeded): on #{response['location']}"
        end
        # TODO check if really absolute or make sure it is
        self.dbg "Redirect to #{response['location']}"
        do_request opt.merge({ :GET => response['location'],
                               :absolute => true,
                               :redirect_limit => opt[:redirect_limit] - 1
                               })
    end

    unless response.is_a? Net::HTTPSuccess
        raise "Error (#{self.class}) making #{config_key} request " +
            "(#{response.code}): " + error_body(response.body)
    end

    if response.body
        type = ignore_content_type ? default_content_type :
            (response.content_type || default_content_type)
        self.dbg "Response body is type #{type}"
        case type
        when /xml$/
           doc = REXML::Document.new response.body
           if @opt['return-hash']
               _xml_to_hash doc
           else
               doc
           end
        when /json$/
            # Ruby JSON doesn't like bare values in JSON, we'll try to wrap these as
            # one-element array
            bodytext = response.body
            bodytext = '[' + bodytext + ']' unless ['{', '['].include? response.body[0].chr
           JSON.parse(bodytext)
        else
           response.body
        end
    else
        true
    end
end

#error_body(body_text, content_type = nil) ⇒ Object



496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# File 'lib/noms/httpclient.rb', line 496

def error_body(body_text, content_type=nil)
    content_type ||= default_content_type
    begin
        extracted_message = case content_type
                            when /json$/
                              structure = JSON.parse(body_text)
                              structure['message']
                            when /xml$/
                              REXML::Document.new(body_text).root.elements["//message"].first.text
                    else
                      Hash.new
                    end
        ['message', 'error', 'error_message'].each do |key|
            return structure[key].to_s if structure.has_key? key
        end
        body_text.to_s
    rescue
        body_text.to_s
    end
end

#ignore_content_typeObject



377
378
379
# File 'lib/noms/httpclient.rb', line 377

def ignore_content_type
    @delegator.ignore_content_type
end