Class: OpenTox::RestClientWrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/rest-client-wrapper.rb

Constant Summary collapse

@@subjectid =
nil

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#requestObject

Returns the value of attribute request


5
6
7
# File 'lib/rest-client-wrapper.rb', line 5

def request
  @request
end

#responseObject

Returns the value of attribute response


5
6
7
# File 'lib/rest-client-wrapper.rb', line 5

def response
  @response
end

Class Method Details

.known_errorsArray

Returns of hashes with error code, method and class

Returns:

  • (Array)

    of hashes with error code, method and class


86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/rest-client-wrapper.rb', line 86

def self.known_errors
  errors = []
  RestClient::STATUSES.each do |code,k|
    if code >= 400
      method = k.underscore.gsub(/ |'/,'_')
      method += "_error" unless method.match(/_error$/)
      klass = method.split("_").collect{|s| s.capitalize}.join("")
      errors << {:code => code, :method => method.to_sym, :class => klass}
    end
  end
  errors
end

.subjectidObject


13
14
15
# File 'lib/rest-client-wrapper.rb', line 13

def self.subjectid
  @@subjectid
end

.subjectid=(subjectid) ⇒ Object


9
10
11
# File 'lib/rest-client-wrapper.rb', line 9

def self.subjectid=(subjectid)
  @@subjectid = subjectid
end

Instance Method Details

#methodRestClient::Response

REST methods Raises OpenTox::Error if call fails (rescued in overwrite.rb -> halt 502) Does not wait for task to finish and returns task uri

Parameters:

  • destination (String)

    URI

  • Payload (optional, Hash|String)

    data posted to the service

  • Headers (optional, Hash)

    with params like :accept, :content_type, :subjectid, :verify_ssl

Returns:

  • (RestClient::Response)

    REST call response


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/rest-client-wrapper.rb', line 24

[:head,:get,:post,:put,:delete].each do |method|

  define_singleton_method method do |uri,payload={},headers={},waiting_task=nil|

    # check input
    bad_request_error "Headers are not a hash: #{headers.inspect}", uri unless headers==nil or headers.is_a?(Hash) 
    headers[:subjectid] ||= @@subjectid
    bad_request_error "Invalid URI: '#{uri}'", uri unless URI.valid? uri
    #resource_not_found_error "URI '#{uri}' not found.", uri unless URI.accessible?(uri, @subjectid) unless URI.ssl?(uri)
    # make sure that no header parameters are set in the payload
    [:accept,:content_type,:subjectid].each do |header|
      if defined? $aa || URI(uri).host == URI($aa[:uri]).host
      else
        bad_request_error "#{header} should be submitted in the headers", uri if payload and payload.is_a?(Hash) and payload[header]
      end
    end
  
    # create request
    args={}
    args[:method] = method
    args[:url] = uri
    args[:verify_ssl] = 0 if headers[:verify_ssl].nil? || headers[:verify_ssl].empty?
    args[:timeout] = 1800
    args[:payload] = payload
    headers.each{ |k,v| headers.delete(k) if v==nil } if headers #remove keys with empty values, as this can cause problems
    args[:headers] = headers

    $logger.debug "post to #{uri} with params #{payload.inspect.to_s[0..1000]}" if method.to_s=="post"
    
    @request = RestClient::Request.new(args)
    # ignore error codes from Task services (may return error codes >= 400 according to API, which causes exceptions in RestClient and RDF::Reader)
    @response = @request.execute do |response, request, result|
      if [301, 302, 307].include? response.code and request.method == :get
        response.follow_redirection(request, result)
      elsif response.code >= 400 and !URI.task?(uri)
        #TODO add parameters to error-report
        #parameters = request.args
        #parameters[:headers][:subjectid] = "REMOVED" if parameters[:headers] and parameters[:headers][:subjectid]
        #parameters[:url] = parameters[:url].gsub(/(http|https|)\:\/\/[a-zA-Z0-9\-]+\:[a-zA-Z0-9]+\@/, "[email protected]") if parameters[:url]
        #message += "\nREST parameters:\n#{parameters.inspect}" 
        error = known_errors.collect{|e| e if e[:code] == response.code}.compact.first
        begin # errors are returned as error reports in turtle, try to parse
          content = {} 
          RDF::Reader.for(:turtle).new(response) do |reader|
            reader.each_triple{|triple| content[triple[1]] = triple[2]}
          end
          msg = content[RDF::OT.message].to_s
          cause = content[RDF::OT.errorCause].to_s
          raise if msg.size==0 && cause.size==0 # parsing failed
        rescue # parsing error failed, use complete content as message
          msg = "Could not parse error response from rest call '#{method}' to '#{uri}':\n#{response}"
          cause = nil
        end
        Object.method(error[:method]).call msg, uri, cause # call error method
      else
        response
      end
    end
  end
end