Class: JSONRPC2::Client

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

Overview

Simple JSONRPC client

Instance Method Summary collapse

Constructor Details

#initialize(uri, options = {}) ⇒ Client

Create client object

Parameters:

  • uri (String)

    Create client object

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

    Global options



27
28
29
30
31
32
# File 'lib/jsonrpc2/client.rb', line 27

def initialize(uri, options = {})
  @uri = uri
  @client = HTTPClient.new
  @options = options
  @id = 0
end

Instance Method Details

#call(method, args = {}, options = {}, &block) ⇒ Object

Call method with named arguments

Parameters:

  • method (String)

    Remote method name

  • args (Hash<String,Value>) (defaults to: {})

    Hash of named arguments for function

  • options (Hash<String,String>) (defaults to: {})

    Additional parameters

Returns:

  • Method call result

Raises:

  • (RemoteError)

    Error thrown by API

  • Transport/Network/HTTP errors



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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/jsonrpc2/client.rb', line 41

def call(method, args = {}, options = {}, &block)
  headers = { 'Content-Type' => 'application/json-rpc' }

  # Merge one level of hashes - ie. merge :headers
  options = @options.merge(options) { |key,v1,v2| v2 = v1.merge(v2) if v1.class == v2.class && v1.is_a?(Hash); v2 }

  if options[:headers]
    headers = headers.merge(options[:headers])
  end

  if options[:user] && options[:pass]
    @client.set_auth(@uri, options[:user], options[:pass])
  end
  result = @client.post(@uri,
              { 'method' => method, 'params' => args, 'jsonrpc' => '2.0', 'id' => (@id+=1) }.to_json,
              headers)

  body = result.body
  body = body.content if body.respond_to?(:content) # Only on old versions of HTTPAccess2 ?

  if result.status_code == 200
    begin
      data = JSON.parse body
    rescue Exception
      body = result.body.to_s
      body = "#{body[0..256]}...[#{body.size-256} bytes trimmed]" if body.size > 256

      if result.contenttype =~ /^application\/json/
        raise RemoteDataError, "Content-Type is '#{result.contenttype}', but body of '#{body}' failed to parse."
      else
        raise WrongContentTypeError, "Content-Type is '#{result.contenttype}', but should be application/json-rpc or application/json (body='#{body}')"
      end
    end

    unless data.is_a?(Hash) && data["jsonrpc"] == "2.0"
      raise RemoteDataError, "No jsonrpc parameter in response.  This must be \"2.0\""
    end

    unless result.contenttype =~ /^application\/json/
      STDERR.puts "WARNING: Content-Type is '#{result.contenttype}', but should be application/json-rpc or application/json."
    end

    if data.has_key?('result')
      return data['result']
    elsif data.has_key?('error')
      if data['error']['code'] == -32000 && data['error']['message'] =~ /^AuthFail/
        raise RemoteAuthError, data['error']['message']
      else
        raise RemoteError, data['error']['message']
      end
    else
      body = result.body.to_s
      body = "#{body[0..256]}...[#{body.size-256} bytes trimmed]" if body.size > 256

      raise RemoteDataError, "A JSON-RPC 2.0 response must either have a 'result' or an 'error' value - in '#{body}'."
    end
  elsif result.status_code == 401
    if result.headers['WWW-Authenticate'].to_s =~ /realm="([^"]*?)"/
      suffix = " for #{$1}"
    end
    raise RemoteAuthError, "Authentication failed#{suffix}"
  else
    raise RemoteAuthError, "Call failed - HTTP status #{result.status_code}"
  end
end